The import io.restassured.RestAssured cannot be resolved

While consuming restassured maven dependencies it has been observed that even after downloading the dependencies eclipse is not able to resolve io.restassured package. Maven repository (https://mvnrepository.com/artifact/io.rest-assured/rest-assured) has the scope set to test in the dependency tag. This limits your code from accessing that dependency’s classes within your source code. That is, you can access those classes only within your test sources (ex: ${project.dir}/src/test/java/, ${project.dir}/test/. Mostly that is not the intended use case, so just remove the scope attribute. <!– https://mvnrepository.com/artifact/io.rest-assured/rest-assured –> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>4.3.2</version> <!– <scope>test</scope> –> </dependency>

Fundamentals of Microservices Design

Define the correct microservice scope When we talk about the scope of a microservice, we are referring to the features of an independent software module. The ability of microservices to perform as a nearly-stateless system allows it to be developed independently. Create a unique service which will act as an identifying source, much like a unique key in a database table. Have loose coupling with high cohesion We should create correct API and take special care during integration. The microservices style is usually organized around business capabilities and priorities.  Unlike a traditional monolithic development approach—where different teams each have a specific focus on, say, UIs, databases, technology layers, or server-side logic—microservice architecture utilizes cross-functional teams.  The responsibilities of each team are to make specific products based on one or more individual services communicating via message bus. In microservices, a team owns the product for its lifetime. Restrict access to data… Read more“Fundamentals of Microservices Design”

Feign Client

Netflix provides Feign as an abstraction over REST-based calls, by which microservices can communicate with each other, but developers don’t have to bother about REST internal details. 1.Add the feign dependency to your project e.g. <dependency>           <groupId>org.springframework.cloud</groupId>           <artifactId>spring-cloud-starter-feign</artifactId> </dependency> 2.Tell to project that we will use Feign client, so scan its annotation, add the below annotation to your application class @EnableFeignClients 3. Now, we have to create an interface where we declare the services we want to call. Please note that Service Request mapping is same as the Actual Service Rest URL. @FeignClient(name=”MySearch” ) //Service Id of service you want to call public interface MySearchServiceProxy { – – – } 4. Add or create a Controller where we autowire our Feign Interface so Spring can Inject actual implementation during runtime. @RefreshScope @RestController public class FeignMySearchController {    @Autowired    MySearchServiceProxy… Read more“Feign Client”

Why Spring cloud is required?

When we develop microservices with Spring Boot , we might face the below mentioned issues hence spring cloud project helps to eliminate these issues.Spring cloud is set of tools to manage and establish the service Discovery, config management and Circuit Breakers etc. It manages and handles following very efficiently, 1. Any of the network and security issues. 2. Service discovery tools manage how processes and services in a cluster can find and talk to one another. It involves a directory of services, registering services in that directory, and then being able to lookup and connect to services in that directory. 3. Redundancy issues in distributed systems. 4. Load balancing improves the distribution of workloads across multiple computing resources, such as computers, a computer cluster, network links, central processing units, or disk drives. 5. Performance issues due to various operational overheads. 6. Requirement of deployment and continuous integration.

JVM (Java) and it’s Memory Management

JVM (Java Virtual Machine) is an abstract machine or can say it is a software implementation of a Physical Machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent). What is JVM It is: A specification: Where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Oracle and other companies. An implementation: Its implementation is known as JRE (Java Runtime Environment). Runtime Instance: Whenever you write java command on the command prompt to run the java class, an instance of JVM is created. What it does The JVM performs following operation: Loads code Verifies code Executes code Provides runtime environment JVM provides definitions for the: Memory area Class file format Register set Garbage-collected heap Fatal error reporting… Read more“JVM (Java) and it’s Memory Management”

Java OOPs

What are the principle concepts of OOPS? There are four principle concepts upon which object oriented design and programming rest. They are: Abstraction Polymorphism Inheritance Encapsulation (i.e. easily remembered as A-PIE). What is Abstraction? Abstraction refers to the act of representing essential features without including the background details or explanations. What is Encapsulation? Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object. What is the difference between abstraction and encapsulation? Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented. Abstraction solves the problem in the design side while Encapsulation is the Implementation. Encapsulation is the deliverables of Abstraction. Encapsulation barely… Read more“Java OOPs”

Difference between Static and Dynamic Web Content

Static contents : The contents of the Web page which do not change frequently irrespective of user who is requesting or the time at which request has been sent. Working of the Web Application (Static Contents): The user send the request by typing the specific URL in the client browser. The DNS server resolves the URL to the IP address and return’s it to requesting browser. The browser then send the request to the Server with IP address as obtained above The Web Server will be listening in to the requests at Port No 80 The browser connects to Port No 80 of the specified Server Since the user is requesting for the static contents, Web server retrieve a file (normally html) and sends it to the requesting client browser as a response. The client has to wait till the response has not been received.   Dynamic Contents : The contents… Read more“Difference between Static and Dynamic Web Content”

Generics in Java

Generics Many algorithms work in a similar way irrespective of the data types on which they are applied on All Stacks work in a similar way irrespective of the type of object they hold Generics help to write algorithms independent of a data type These algorithms can be applied to a variety of data types The data type is parameterized A class, interface or a method that works on a parameterized type is called a generic public class List<T>{ protected T [] list; public List(T [] list){ this.list = list; } public void put(T element, int position){ list[position] = element; } public T get(int position){ return list[position]; } } In above code, T represents a data type. While declaring an object of List, the programmer can decide the actual type for T. List<String> list = new List<String>(new String[5]); list.put(“Hello”, 0); list.put(“Welcome”, 1); list.put(“Ok”, 2); System.out.println(list.get(0)); System.out.println(list.get(1)); System.out.println(list.get(2));   Just like… Read more“Generics in Java”

Collection Framework in Java

The Collection Framework is a set of classes and interfaces Helps in handling groups of objects Standardizes the way in which groups of objects are handled The important interfaces of the Collection Framework are Collection List Queue Set SortedSet All these interfaces are generic interfaces Collection interface declares the methods that any Collection should have Any class that defines a Collection should implement this interface Some of the important methods are add remove contains isEmpty List List interface extends Collection interface List interface declares the behavior of a Collection that stores a sequence of elements Elements can be inserted and accessed by their position Some of the important methods are add (adds to the specified position) get (gets from the specified position) indexOf Set Set interface extends Collection interface Set interface declares the behavior of a Collection that does not allow duplicate elements Does not declare any new method on… Read more“Collection Framework in Java”

Exceptions and Errors in Java

Exception Exception is an exceptional case that can happen in a program An Exception occurs during the execution of a program and disrupts the normal flow of instructions. When there is an exception Normally the program crashes and prints a system generated error message Not acceptable in a mission critical application The programmer can handle the exception, preventing the program from crashing Exception Handler is a set of instructions that handles an exception The Java programming language provides a mechanism to help programs report and handle errors When an error occurs, the program throws an exception The exception object that is thrown contains information about the exception The runtime environment attempts to find the Exception Handler The exception handler attempts to recover from the error If the error is unrecoverable, provide a gentle exit from the program after clean up operations like closing open files etc Helpful in separating the… Read more“Exceptions and Errors in Java”

Error while decryption of SOAPUI response- “Error Getting Response :null”

In SOAPUI in many cases when we apply the wss keystore for decryption it hits error and shows message: “Error Getting Response :null”. But shows nothing in SOAPUI logs and blank output screen. When you remove Incoming WSS it shows the encrypted response. To solve this you can try below steps: Go to C:\Program Files\SmartBear\SoapUI-5.3.0\lib Rename wss4j-1.6.16.jar to wss4j-1.6.16.jar.old Copy wss4j-1.6.2.jar from same location for SoapUI 4.5 to this folder. You can down load wss4j jars from : http://central.maven.org/maven2/org/apache/ws/security/wss4j/1.6.2/wss4j-1.6.2.jar Some other jar versions also may work. You may still face issue with decryption then check the logs at: C:\Program Files\SmartBear\SoapUI-5.3.0\bin\soapui.log. In case it’s showing “org.apache.xml.security.encryption.XMLEncryptionException: Illegal key size” error that suggests that JCE error due few jar files are missing from installation. This issue can be resolved by installing the Oracle® Java JCE unlimited strength jars. These jars can be downloaded from the following links depending on which Java version you are… Read more“Error while decryption of SOAPUI response- “Error Getting Response :null””

Thread and its various states in Java

What is Thread A thread is a single sequential flow of control within a program Facility to allow multiple activities within a single process Referred as lightweight process Each thread has its own program counter, stack and local variables Threads share memory, heap area, files   Why to use Thread To perform asynchronous or background processing Increases the responsiveness of GUI applications Better utilization of system resources Simplify program logic when there are multiple independent entities A very good example of a multi-threaded application is game software where the GUI display, updating of scores, sound effects and timer display are happening within the same application simultaneously. Other Thread Advantages Threads are memory efficient. Many threads can be efficiently contained within a single EXE, while each process will incur the overhead of an entire EXE. Threads share a common program space, which among other things, means that messages can be passed… Read more“Thread and its various states in Java”

Difference between Abstract Class and Interface

Abstract Classes Interfaces Can have concrete methods Can have only abstract methods Can have variables Can have only static final (constant) data members Can have private and protected members All  members are public by default Can be extended from one class Can be extended from any number of interfaces A class can extend only one abstract class A class can implement any number of interfaces

Anonymous Inner Class in Java

An inner class is a class defined within another class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class. An inner class is fully within the scope of its enclosing class. An anonymous inner class is a class that is not assigned any name. It is important to note that class Inner is known only within the scope of class Outer. The Java compiler generates an error message if any code outside of class Outer attempts to instantiate class Inner. Generally, these are used whenever you need to override the method of a class or an interface. Example- public class AnonymousInnerClassDemo extends Applet { public void init() { addMouseListener(new MouseAdapter(){ public void mousePressed (MouseEvent ev) { showStatus(“Mouse Pressed !!”); } } } In this example init() method calls addMouseListener() method. Its argument is an expression that defines… Read more“Anonymous Inner Class in Java”

Analyzing http and https traffic using fiddler

Fiddler tool can be used for analyzing HTTP and HTTPS (must be enabled from within the fiddler tool) transactions. This tool is a simple to use and by following below tips you can capture and analyze the request and network traffic causing any performance issue. Also you can send the captured logs to support team to get these analyzed if needed. It enables us to inspect all HTTP traffic, set breakpoints, and dig through the incoming or outgoing data. Using fiddler we can check reason for performance bottleneck of a web page, which cookies are being sent to server or what downloaded content is marked as cacheable etc. Installation, Firstly you need to download and install the fiddler tool (https://www.telerik.com/download/fiddler/fiddler4 ) and follow the screen instructions to get this installed. Enabling the traffic for https Open Fiddler and from the top menu click on Tools -> Options and click on the HTTPS tab Check… Read more“Analyzing http and https traffic using fiddler”

Url Encoding and Decoding in Java

URL encoding/decoding in java is very useful while working with the URL which is transmitted through the network. In case your URL contains some special characters in it then it might get replaced with some other special character. Few important notes, Always use the same scheme to encode and decode the URL. URLs can be encoded multiple times hence always keep this in mind while comparing or retrieving the original URL. Before encoding, recommendation is to decode the URL first and see if resulted URL differs from original URL which means URL is already encoded. Sample Java Code public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException { // added the escape characters String url = “https:\\\\ourhints.com\\test-java\\page1?attribute1=23&attribute2=45”; // encoding the orginal url String encodeUrl = java.net.URLEncoder.encode(url, “UTF-8”); System.out.println(encodeUrl); // getting the orginal url by decoding System.out.println(java.net.URLDecoder.decode(encodeUrl, “UTF-8”)); }

Microservices and their key benefits

Microservices are a kind of software architectural solution that allows software to be developed into relatively small, distinct and loosely coupled components. Each of the components provides a distinct subset of the functionality of the entire application. Each microservice, can then be designed, developed, and managed independently. This allows for distributed ownership of a large application across a large organisation, with each microservice owned by a specific team. Microservices are an independent components and are smaller in size hence can be easily built and maintain by a small team. Microservices are scalable. Technology diversity i.e. This eliminates long-term commitment to a single technology stack, if you want to try out a new technology stack on an individual service, you can go ahead. Fault isolation i.e. larger applications remain unaffected by the failure of small component. Better support for parallel team to work on separate components. Independent deployment and easy integration…. Read more“Microservices and their key benefits”

SOAP and REST web service comparison

SOAP stands for Simple Object Access Protocol. REST stands for Representational State Transfer. SOAP is a XML based messaging protocol and REST is not a protocol but an architectural style. REST does not enforces message format as XML or JSON etc. Since SOAP messages are wrapped in a SOAP envelope it can be sent over to any transport mechanism e.g. TCP, FTP, SMTP or any other protocol. On the other hand, RESTful Web services are heavily dependent upon HTTP protocol. SOAP uses services interfaces to expose the business logic.REST uses URI to expose business logic. SOAP has a set of standard specifications e.g. specification for security (WS-Security) , specifications for messaging, transactions, etc. Unlike SOAP, REST does not has dedicated concepts for each of these. REST predominantly relies on HTTPS. SOAP is strongly typed, has strict specification for every part of implementation.  REST gives the concept and less restrictive about… Read more“SOAP and REST web service comparison”

Java Performance Tuning Tips

Sometime we need to improve the performance of our application into our code. Below are the recommendations for Java code tuning. Don’t optimize before you know it’s necessary Use a profiler to find the real bottleneck Work on the biggest bottleneck first   Managing Objects Here, idea is used to use garbage collection less frequently either by canonicalization or by references. Lesser number of garbage collection happens, lesser overhead occurs. Avoid creating temporary objects within repeated routines Pre-size collection objects Better to reuse objects than creating Use custom conversion methods for converting data types to reduce creation of temporary objects Canonicalize objects (Replacing multiple objects with single object) whenever required and compare by identity Replace string and other objects with integer constants and compare by identity Better to use primitive types instead of objects for instance variables Use StringBuffer than string concatenation operator Appropriate use of weak, soft references Use cloning… Read more“Java Performance Tuning Tips”

Analysing and fixing Java Heap related Issues

Java Heap related issues can cause severe damage to our application and we might see poor user experience. Java Heap is memory used by your application which is used to create and store objects. We can define the maximum memory for heap by specifying -Xmx<size> by setting the java variable. When your application runs, it will gradually fill up Heap and memory must be released to keep our application working. Hence Java periodically runs a process called ‘Garbage collection(GC)‘ which will scan the heap and clear objects that are no longer referenced by your application.One cannot request Garbage Collection on demand. Only JVM can decide when to run GC. A Heap dump is a snapshot of the memory of when the heap dump was taken.Heap dumps are not commonly used because they are difficult to interpret. But, they have a lot of useful information in them if you know where/how… Read more“Analysing and fixing Java Heap related Issues”

Basic Java constructs

Java is a strongly typed language, which means that all variables must first be declared before they can be used. The basic form of variable declaration is “Variable Type followed by variable name”. For example “int myVar;” Doing so tells your program that the variable named “myVar” exists and holds numerical data[ i.e integer value]. A variable’s data type determines the values it may contain, plus the operations that may be performed on it. The data types are of two types. They are primitive data types and reference data types. Primitive Data Types are pre defined by the language and is named by a reserved keyword. Example: int, float etc. Reference Data types are often referred as non-primitive data types. Example: Objects and Arrays They are called as reference data types because they are handled “by reference” – in other words, the address of the object or array is stored in… Read more“Basic Java constructs”

New features of various java releases and their comparison

Java is the choice of many software developers for writing applications. It is a popular platform that provides API and runtime environment for scripting and running enterprise software, including network applications and web-services. Oracle claims that Java is running in 97% of enterprise computers. Each Java programmer must know about these new features. Types of Applications that Run on Java are below, Desktop GUI Applications Mobile Applications Embedded Systems Web Applications Web Servers and Application Servers Enterprise Applications Scientific Applications Below is the consolidated list of important new features added in various java releases.

Installing java SDK and writing first java program

Installing and using Java Install the java SDK from below location and follow the installation instructions, http://www.oracle.com/technetwork/java/javase/downloads/index.html Setting environment variable for Java Environmental variable is a variable that describes the operating environment of the process. Common environment variables describe the home directory, command search path etc. JAVA_HOME JAVA_HOME is a environment variable (in Unix terminologies), or a PATH variable (in Windows terminology) which contains the path of Java installation directory. On window operating system follow the below steps, 1.Right click My Computer and select Properties. 2. On the Advanced tab, select Environment Variables, and then edit JAVA_HOME to point to where the JDK software is located. or run the below from command prompt, Set JAVA_HOME = <jdk-install-dir> example, C:\Program Files\Java\jdk1.6.0_02. On Unix operating system run the below command, export JAVA_HOME=<jdk-install-dir> CLASSPATH Set PATH =%PATH%;%JAVA_HOME%\lib\tools.jar PATH Set PATH =%PATH%;%JAVA_HOME%\bin; Please note, changing the JAVA_HOME will reflect to path and class path… Read more“Installing java SDK and writing first java program”

Core Java Architecture and JVM

In this lesson, we are going to explain the core Java Architecture. Java Java was conceived by a team of engineers in Sun Microsystems in 1991 as a part of a research project, which was led by James Gosling and Patrick Naughton. It was initially called Oak but was renamed as Java in 1995. This is designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level, which means that the same Java program can run on any machine. Features of Java Java is an Object Oriented Language. Object-Oriented design is a technique that helps the programmer visualize the program using real-life objects. Java is a Simple Language. The reason is, Certain complex features like operator overloading, multiple inheritance, pointers, explicit memory de allocation are not present in Java language. Using Java we can write Robust Programs. The Two main… Read more“Core Java Architecture and JVM”

Object oriented concepts used in Java

Java is an Object-Oriented Language hence before learning java let us understand the object oriented Concepts first. Object An object in the software world means a bundle of related variables and functions known as methods variables and functions known as methods. Software objects are often used to model real-world objects you find in everyday life. The real world objects and software objects share two characteristics : 1. State : condition of an item. 2. Behaviour : Observable effects of an operation or event including its results. State can be of two types : Active state which reflects the behaviour and Passive State refers to state which does not change which does not change. The behaviour of an object forms the interface to the external world. Class A class is a blueprint or prototype that defines the variables and the methods (or funtions) common to all objects of a certain kind. Constituents… Read more“Object oriented concepts used in Java”

How to integrate elastic search with spring boot application

We can use elastic search with spring boot application and for this below are the detailed steps which can be followed. (Please note there some compatibility issue with some version of elastic search hence choose the appropriate one as per your need, I have used the version 2.4.0 with my spring boot app version 1.4.0.RELEASE) 1. Download and unzip the elastic search from http://www.elastic.co/downloads/past-releases/elasticsearch-2-4-0 2. Open config file \elasticsearch-2.4.0\config\elasticsearch.yml and change the cluster name if needed, uncomment and add the value to property 3. Run the elastic search by clicking on batch file, \elasticsearch-2.4.0\bin\elasticsearch.bat (Here this is going to run the elastic search on separate server than your application i.e localhost:9300 ) 4. Add the below dependency to your spring application <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> 5. Add the below properties to application.properties file spring.data.elasticsearch.cluster-name= spring.data.elasticsearch.cluster-nodes=localhost:9300 6. To enable the elastic search repository which will be used to save/generate/delete the search… Read more“How to integrate elastic search with spring boot application”

Email validator in java

You can use the below validator class for email address in your java projects, /* Email Validator */ package com.tms.utility; import java.util.regex.Pattern; /** * * @author aarnav */ public class EmailValidator { private static final String EMAIL_PATTERN = “^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@” + “[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$”; public EmailValidator() { } /** * Validate hex with regular expression * * @param email for validation * @return true valid email, false invalid email */ public static boolean validate(String email) { Pattern pattern = Pattern.compile(EMAIL_PATTERN); return pattern.matcher(email).matches(); } }

Converting a number to english word in java

You can use the below java class to convert a number to english word, /* * Number to English word converter */ package com.tms.utility; /** * * @author aarnav */ import java.text.DecimalFormat; public class EnglishNumberToWords { private static final String[] tensNames = { “”, ” ten”, ” twenty”, ” thirty”, ” forty”, ” fifty”, ” sixty”, ” seventy”, ” eighty”, ” ninety” }; private static final String[] numNames = { “”, ” one”, ” two”, ” three”, ” four”, ” five”, ” six”, ” seven”, ” eight”, ” nine”, ” ten”, ” eleven”, ” twelve”, ” thirteen”, ” fourteen”, ” fifteen”, ” sixteen”, ” seventeen”, ” eighteen”, ” nineteen” }; private EnglishNumberToWords() {} private static String convertLessThanOneThousand(int number) { String intialNum; if (number % 100 < 20){ intialNum = numNames[number % 100]; number /= 100; } else { intialNum = numNames[number % 10]; number /= 10; intialNum = tensNames[number %… Read more“Converting a number to english word in java”

Integration of Rich File Manager with ckeditor

This article is helpful to those developers or programmers who are facing the issues with file upload functionality and are using the ckfinder a paid service. Rich file manager is open source and is free to use. You can follow the below steps to integrate this with ckeditor in your spring boot or java application. 1.Download the latest version of ckeditor  and rich file manager. Add the above downloaded files under resources folder of your project. Make sure to add ckeditor and RichFilemanager-master directories in parallel under resource folder. 2.Open the js file /Resources/ckeditor/config.js and add below lines, config.filebrowserImageBrowseUrl =’/RichFilemanager-master/index.html?filter=image’ (Note, we have added the filter Image to support the upload of images only moreover you can remove or modify the filter as per your need. 3. Enabling the java connector – We need to use the java connector to connect rich file manager with ckeditor. i) Modify the rich… Read more“Integration of Rich File Manager with ckeditor”