java unit testing or junit

Junit is popular java unit testing framework. Junit is developed to unit test the piece of code.

What do you mean by unit testing? Unit testing is test code written for checking the runtime errors for each function/line of a java code. Junit can be used to regress the each small change so that large application should not give errors even adding small changes

Testing is piece of code written for checking the validity of actual business logic code like null check, and comparing actual and expected values.

Unit testing is a developer activity as part of software quality assurance process

junit can be coded in to test correctness of executions paths of java unit code
junit tests are coded by developers as part of software development life cycle.
Java unit testing can also be called as white box testing. Where as black box testing means functioaly of the system done by QA/testers.
After analysis and design phase, before writing code development, normal practise is to write the unit test code for the new functionally, then code new functionally, this way we find the all the issues for the new functionally

Junit is a open source testing framework and current version is 4.x. There are two types of test cases in junit. One is single test case, other is multiple test cases called Test suit

Junit can be shipped as jar file. You can download junit 4.x jar from junit site. Junit test can be executed in multiple following ways.
1 junit with maven plugin: - You need to define the junit dependency for your project where you are going to write unit test code. Here we will specify artefact name, groupId and version
2. junit with ant task:- Ant is provided different task to run the test case by configuring task in build.xml
Junit plugin in eclipse:-
Junit plugin should be installed to eclipse. Eclipse Galileo has default junit plugin installed.
3. junit eclipse:-
Junit examples

package org.cloudhadoop;

public class Calc {
public int add(int a, int b) {
return a + b;

package org.cloudhadoop;

import junit.framework.Assert;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.junit.Test;

public class CalcTest {
Calc calc = null;

public void setup() {
calc = new Calc();


public void testAdd() {
int a = 10;
int b = 20;
int actual = 30;
int expected = c.add(a, b);
Assert.assertEquals(actual, expected);

public void testAddErorcase() {
int a = 10;
int b = 20;
int actual = 30;
Calc c = new Calc();
int expected = c.add(a, b);
Assert.assertEquals(actual, expected);

public void tearDown() {



Java unit testing rules:-
All test classes name end with XXXXTest, for example class is Calculator, the Test class should be CalculatorTest
All test methods start with tesMethod and annoted the method as @Test

Cron Expression examples

Cron expressions are fixed size certain string formated characters to represents the particular time or set of specific interval times used in scheduler programming.
Cron expressions are used in either unix programming or any other programming languages like java. Java has quartz framework as the scheduler to run jobs or task in specific interval of time.

In Quartz scheduler, cron expression are specified for job triggers which will be executed by quartz scheduler.

Cron expression are specified by 6 characters or 7 characters(not required, but option 7th character)in the format of asterick with sepated by white space.

Cron expression format

* * * * * *

Each asteric has meaning

1st asterick represents - seconds
2nd asterick represents - minutes
3rd asterick represents - hours
4th asterick represents - day of month
5th asterick represents - month
6th asterick represents - Day of week
7th asterick represents - Year

and there are special characters like ,* - / ? apart from asterick

special character '?' is used to specific 15th of the month etc..
-* means ranges, if we specified in months field as 5-7, runs daily from dated 5 to 7

Cron expression samples or examples
following are the few cron expressions that would be used for developers to execute the task in specificic period of time

Cron expressions to execute for every 30 minutes

0 0 0 * * 30

Cron expression to run job for every minute starting from 4pm and ending at 4:59 daily
0 * 16 * * ?

Execute job or taks for every 5 minutes

0 0/5 * * * ?

To run job on 11:30 AM every day

0 30 11 ? * *

executes job January 1st 12:10AM

0 10 12 11 1 ?

Please leave a comment if you have any thing to share on this short article

Grails Constraints

grails is framework developed in groovy framework which internally uses java to build the applications very quickly. I got chance to work on grails application. so i want to blog about the grails constraints.

As you know in any web programming language, we need to do the form level validations. which we can do it either at client level validation or server level validation
client level validations means, the entered data can not be send to server an d do the validation at the browser, To do this, we have lot of scripting languages like JavaScript or vb scripts.
For Server level validations, the entered data send to server and server checks for different validations that we define at domain level.
we can use java or .net languages to do domain level validations. Groovy uses the java language to do validations
Grails can define the domain level constraints

Grails can be defined the constraints validation on domain class on the following way

class Employee {
String eid
String name
String email
Integer sal
static constraints = { eid:unique,name:blank, email:email:true


In the Employee domain class, validation constraints are defined in Groovy on Grails. groovy constraints are defined with in block containing all the required validation configuration for this domain class.

i am listing out the following domain level constraints.

List of domain validation constrains available in groovy and grails
blank constraint is to specify the member variable in domain can be null or not
usage is name blank: true/false

creditCard:- this is used to check the member variable is credit card
email:- email validator check is used to check correct valid email validation rules
inList :- to check the valid values between the list of values
To check for the set of valid values with in range
matches :- this used to compare with the regular expression
max :- checks for allowed maximum value
maxSize :- this specifies the maximum size
min :- this is minimum value that would not allow specified
minSize :- minimum value to allow
notEqual :- this checks for the value is not equal specified
nullable:- the member value is null able or not
range:- specifies the range of values
unique :- unique constraint specifies that where the variable is duplicate or not

The above validators are predefined validators that come with grails plugin framework, we can also define our custom validator using grails framework. The validators checks and validates on form as server side validator

Application servers and web servers two type of servers need to know in web application development in software world. Developer write the piece code,packs this code as war and deploy/host the code in

one of the web server or application server, then users of the application can access the features of the application from any where in the world

Web server tutorial:-

Webservers are used to generate the dynamic content as well as static content. Clients send the http requests, process the request and gives response back to the user. Web servers process the html content, images, stylesheets elements. Popular webserver are apache webserver and Microsoft IIS.
Webserver is hardware and software, machine which has IP Address assigned to domain name, for example, client browser request for, webserver on that box request index.html content and give back the response to the browser. This communication from client to webserver is happening over http protocol defined by w3c org
web server is most basic server to know in web based application development. The application s are packed as folder as well as web archives developed in java, php or Microsoft net technologies. webserver is used for small scale projects.

Application Servers tutorial:-

Application Servers is a java server which provides different following set of reusable following services. Application servers are used mostly in N-tier based projects, in which webserver act as front controller for application servers. Application servers host the EJB projects in the form of ear i.e. enterprise archive structure which contains jars and war modules

1.Object lifecycle management:- This service is basic service in any application servers, and create a pool of objects, does garbage collection and share this objects states in among user sessions calls.
2. Connection pooling :- Provides pre created pool of connections to the different databases and manages the connections, returns the connections to the pool whenever the connections are not used by the applications
3. Security Management:- application servers provides different levels of securities including authorization and authentication with different providers like databases realms, text files, and different LDAP Providers. Provides security at domain object level, web resource level as well as web context level. messaging services:- Application servers provides in build java messaging services as well as integrated with different JMS providers like SUN MQ providers.
5. Transaction management:- To maintain the ACID properties for the application transaction, application servers integrate with JTA and ORM Transactions
6. Load Balance and clusters:- To accommodate the load on the servers, group of application servers act as node, connected with group of nodes and serve the response even one of the node in group of node fails.
7. Fault Tolerance: - application servers provide the 99.999 up time to provide the reliable application with 367X24 up time.

I have listed few services here, but there are more services provided by application servers.
Developers need not write the above services when developing any j2ee applications, and write his business functionality code and can reuse those above services

Difference between application server and webserver

Difference between Application server and web servers is a basic interview question on j2eee world.
application servers are used to provide the different business services as mentioned below, web servers provides receives the request and get the dynamic content and send the response to the client.
Application servers are used in large scale enterprise projects, web servers are used in small scale projects.
the architecture for application servers is N-tier node architecture where number of nodes are connected as clustered environment.
webserver can be used in 2 tier as well as n tier architecture, and act as front controller for n tier architecture

The following are the list of popular application servers in java

1.apache Tomcat
2.Cauche resin
3.BEA Weblogic later acquired by Oracle
4.Linux Jboss
5.IBM Websphere
6.SAP Netweaver WebAs 6.4
7.Oracle Application Server
6.Apache Geronima application server
List of popular web servers for webapplicaiton development

1. Apache web server
2. Microsoft IIS
Groovy on Grails is open source application framework build on java language using groovy scripting languages.
what is groovy framework:-

Groovy is scripting programming language which runs on java virtual machine. Groovy is a java module that has one dependency jar file.
Groovy is scripting framework for building applications on top of java. It will reduce lot of java code to write the applications and the files are saved with extension as .groovy. The syntax for groovy and java looks similar.

Grails Framework:-

Grails is java web application development framework for building rapid web applications. Grails are integrated with spring and hibernate technologies to develop the applications very quickly. In Grails, to story any model object, we don't define any configuration or much files to do crud on model. just by coding by convention approach, we can simplify the development and do our logic quickly.

Grails applications can be build by java developers as well as developers who has development experience easily.

Advantages of Grails framework:-

support for building web applications quickly without focusing on software conventions
Integrate with persistent orm frameworks like hibernate and other frameworks like spring
Provide riche templates build on Groovy server pages to build standard UI elements and MVC features
Good documentation and lot of companies are using these technologies
Learning framework is easy and building web applications with this framework is straightforward.
Generate code automatically based on templates.
Building new applications is very easy

Disadvantages with Grails:-

It is developed on java, learning curve is there for non-java developers
Integrating with existing custom frameworks is very difficult and complex.
There is time consuming process while compiling grails apps as Interpretation of the scripts and conversion to .class files is to be done.

Grails is integrated with maven for building grails projects.

Grails project code architecture
controllers – grails-app/controllers :- here we can write the groovy files for controller related code
domain – grails-app/domain Contains the list of groovy model objects with package structure

view - grails-app/views

has the list of gsp files which are groovy based server pages to display the UI elements. Groovy server pages are like java server pages with support of groovy scripting languages.

This is just basic idea that i got to know and blogged.

Please share your views on this.

Implicit objects

are java objects in jsp which will be created by servlet container. usually if we want to access any data in a class, we have to create a object using new operator and then access the methods on that object. for implicit objects, we can use them directly on jsp pages.
JSP is used in mvc model architecture so i will clearly separates presentation logic with model logic. JSP used as presentation logic which we can use the objects with out creating the instances.

In servlets API, we have to create the objects, calls the methods on the objects. but to use the servlet specific information in JSP, implicit object can be used without creating any object.
I want blog this as part of j2ee tutorials in my blog


1. request implicit Objects:-
request scope is similar to HttpServletRequest object which holds request specific information. request object in jsp is equal to HttpServlet in servlets.
request object is used to persist the request scope parameters, and reqeust meta header information like
2. response implicit Objects:-

response is an similar to HttpServletResponse object in a servlet. Response object holds the information returned to client. This object holds cookies, content and type and http header
3. Page implicit Objects:- page indicates current jsp page and has the scope of jsp page execution

Session implicit Objects:- Session object is HttpSession class in Servlets. Session holds personalized data of a user.
In a real scenarios, Session object is created one for each user

application implicit Objects:- application is global object similar to in Servlets. application objects holds information about webapplication and only one application for each webapplication
PageContext implicit Objects:- jsp pageContext is object of PageContext in servlets.

5.Config implicit Objects:- Jsp config is instance of ServletConfig class. which holds configuration parameters at servlet level.

Web application can have Config objects in such way that each servlet only one config objects.
6.Exception implicit Objects:- Exception object is instance of Throwable class.

javac compiler

Java Compiler

Javac is java compiler tool developed by Sun framework. Java compiler used to read the java program and compiles this java program into machine readable byte code.Javac tool is shipped as part of JDK software installation and found in bin folder of jdk installed folder. This tool is mostly basic tool to learn for java programming developer. This article talks about the javac tutorials and examples with known issues with javac for the developers who are new to java.

javac command usage:-
javac is a command in java used to compile the java programs, there are three parameters are passed.
javac {options} {sourcejavafile} {commandlinearguments}

Options in javac are standard options provided by jdk framework
sourcejavafile is java program to read and compile
command line arguments are arguments passed to the java program at command line which read by java program at runtime using argument String[] args of main() method.

javac command line options in java:-

Following are the all options for javac command using -help command

C:\work>javac -help
Usage: javac  
Where possible options include:
  -g                         Generate all debugging info
  -g:none                    Generate no debugging info
  -g:{lines,vars,source}     Generate only some debugging info
  -nowarn                    Generate no warnings
  -verbose                   Output messages about what the compiler is doing
  -deprecation               Output source locations where deprecated APIs are used
  -classpath           Specify where to find user class files and annotation processors
  -cp                  Specify where to find user class files and annotation processors
  -sourcepath          Specify where to find input source files
  -bootclasspath       Override location of bootstrap class files
  -extdirs             Override location of installed extensions
  -endorseddirs        Override location of endorsed standards path
  -proc:{none,only}          Control whether annotation processing and/or compilation is done.
  -processor [,,...]Names of the annotation processors to run; bypasses default discovery process
  -processorpath       Specify where to find annotation processors
  -d              Specify where to place generated class files
  -s              Specify where to place generated source files
  -implicit:{none,class}     Specify whether or not to generate class files for implicitly referenced files
  -encoding        Specify character encoding used by source files
  -source           Provide source compatibility with specified release
  -target           Generate class files for specific VM version
  -version                   Version information
  -help                      Print a synopsis of standard options
  -Akey[=value]              Options to pass to annotation processors
  -X                         Print a synopsis of nonstandard options
  -J                   Pass  directly to the runtime system

Compile java file using javac:-
D:\work>javac is read by java compiler and complies into First. Class and place this file in current directory.
Frequent important options for java coder.
How to set Classpath with javac:-
usually javac with classpath settings are configured to have dependency of class for the compiled java class.
classpath is environment settings configuration value that are used by java runtime system to find the classes and other java related objects when java programs are running. Usually CLASSPATH is configured at machine level as well as inline classpath settings. At machine level, we can configure using environment variable CLASSPATH and inline classpath settings are configured by supplying -cp or -classpath option to jdk tools like javac.
We can set classpath in javac with classes as well as jar. Configuring javac classpath in windows and javac classpath in linux environments are same.

javac classpath example :-
C:\javac -classpath .;d:/project or 
C:\javac -cp .;d:/project
we can also set classpath at command prompt using the below command.javac compiled directory is current directory in the above example.
C:\set CLASSPATH=.;pathtodirectoryforclasses or jars;
classpath value should be either current directory (representing .) or any other directory which points to .class files, jar and zip files.
classpath default settings are current directory. if we set CLASSPATH using javac -classpath commandline options overrides the default directory.
javac sourcepath option :-
Whenever java programs are complied, javac looks for the source of java files in the current directory from where javac is executing. if javac wants to search for the java source files other than current directory, we have to provide source path options to javac.
C:\javac -sourcepath c:\javawork\javafiles;.;
javac source option :-
javac can also be used to compile the java programs with supporting lower versions of jdk version using -source option. With this option, we can always configure the options to have the java source code compatibility for the desired java releases. This option is flexibility to have lower version of java releases for java source only.
C:\javac -source 1.4
javac target option :- By using target option in javac, compiled classes are combatable to the jdk versions releases. Once .class files are generated with this option , those are combatable to particular jvm only
Javac Known issues for basic java programmer:-

For the first time user, when we are compiling java program, we used to get a lot of issues. i am listing down the two important issues that i have faced while learning java
Fix for Javac' is not recognized as an internal or external command, operable program or batch file issue in java:-

javac is the tool available jdk software, once jdk is installed say(d:\jdk1.6), javac.exe is available in d:\jdk1.6\bin location.
Suppose you are running javac command from different directory say d:\code, with command as javac, it will give error "Javac' is not recognized as an internal or external command, operable program or batch file" in java.
javac should available in the directory where java files are compiling.
We can fix this in many ways by using inline path settings or environment variable settings.

javac -classpath settings:-

d:\code\ set path=%path%;.;d:\jdk1.6\bin;
Configure environment variable path for java in windows:-
when java is installed, windows doest not know where javac is located, we have to set environment variables path pointed to bin folder.
Go to My Computer, and right click on it and select properties, go to advanced tab, add Path environment variable which point to location of d:\jdk1.6\bin
Once these settings are configured, we can able to compile in windows system from any location
javac: file not found: issue in java:-
"javac: file not found" is one of other error that used to get for basic java developer. This error is
javac: file not found:
Usage: javac  
use -help for a list of possible options

When we compile java file with javac command, the above error is thrown in the system console. javac is working fine no issues with javac settings.
But the possible solution is that there is no java file located in the current directory.
The solution is to find the java file in the directory using dir command in windows or ls command with Linux, if java file is not there, give the complete path of the java as input to javac compiler. Hope it works and compiles fine.

Please leave a comment if you like this.

How to fix for java.lang.NoClassDefFoundError error in java

fix for NoClassDefFoundError in java
NoClassDefFoundError in java is one of the strange error used to get in java applications.
Usually when we run java programs, we used to get the Exception in thread “main” java.lang.NoClassDefFoundError: in our programs I got this exception alot of times. Solving this NoClassDefFoundError is very easy but we have to know the ways to solve this. NoClassDefFoundError exception will be in different cases like windows,linux,unix and tomcat/websphere,jboss. I am going to explains about the sample program assumes that which throws NoClassDefFoundError  and fix for this error.

public class HelloWorldDemo {
 public static void main(String args[]) {
  System.out.println("Hello world test message");

This is sample hello world program,When i compile this program using javac command, this compiles fine and generates HelloWorld.class in the current directory,

After running this programm using java HelloWorld command, I am getting the below exceptions.

Exception in thread "main" java.lang.NoClassFoundError: HelloWorld

thread main throws this error and exit the program abnormally.

This reason for this error is java virtual machine can not find class file at run time. java command looks for the classes that are there in the current directory, so if your class file is not in current directory, you have to set in classpath, so the solution is to place this .class file in the classpath

classpath is the enviornment variable in every system which points to class files in the directories. if you classfile is in jar file, jar should be in classpath. classpath can be absolute(complete path) or relative path( related to directory )

Many ways to solve java.lang.NoClassDefFoundError exception.
Following are the different cases where this error is occured and fix for them.

1. solve java.lang.NoClassDefFoundError :-

HelloWorld.class is not avialble at runtime, so we have to set the class file to java command using -classpath option

java -classpath . HelloWorld

This is for fixing NoClassDefFoundError error by setting classpath inline for java command.

We are instructing the jvm to look for the HelloWorld.class in the current directory by specifying .

if class file is in different directory, we need specify the complete directory absolute or relative path instead of . for java command

2. Fix for java.lang.NoClassDefFoundError in windows:-

To solve NoClassDefFoundError error in windows , we have to set CLASSPATH environment variable.

to set classpath in windows, we have to configure the below values


%CLASSPATH% means existing classpath to be added and . points to current directory

After setting classpath,
java HelloWorld
command works fine and prints hello world message

3. Fix for java.lang.NoClassDefFoundError in linux/unix:-

This is like setting classpath in linux
so we have to set the class or directory of the class files to classpath environment variable.


After setting classpath in linux,
java HelloWorld
command works fine and prints hello world message

4. Fix for java.lang.NoClassDefFoundError in eclipse:-
java.lang.NoClassDefFoundError in eclipse usually ocurrns that your project is missing some of required jars in your build path.
we have to first configure your project build path.
we can configure by right click on project-->properties-->java build path--> select libraries for jars or for classes in folder select source..

5. Fix for java.lang.NoClassDefFoundError error for jar files:-

and also we found that when we are running java class file presented in jar file, java.lang.NoClassDefFoundError error occurs, sho you have to set classpath in MANIFEST.MFin eclipse:-

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.2
Created-By: 1.6.0-beta2-b86 (Sun Microsystems Inc.)
Implementation-Version: 3.0
Class-Path: exntension.jar
class-path attribute value jar is missing in your classpath, so we have to set the jar to the classpath

5. Fix for java.lang.NoClassDefFoundError error in tomcat,jboss,websphere-
NoClassDefFoundError error in servers occurs because of the jar is not in classpath. To fix this, see the complete stack trace and find the jar which contains jar and tries to copy in the server classpath or application classpath. Please leave a comment if you are seeing any issues with servers.

we have seen that NoClassDefFoundError throws at runtime but what about java.lang.ClassNotFoundException error. both looks similiar and related to classpath only but ClassNotFoundException exception throws application tries load the class using name of the class or class calling other class which is not loaded.

what is java.lang.ClassNotFound Exception : classnot found exception is thrown when classes are loaded by different classloaders at runtime. here child class which load in parent class is not available for class loader to load the class. then what is different between java.lang.NoClassDefFoundError and java.lang.ClassNotFoundException? we will see in the below paragraph

Difference between ClassNotFoundException and NoClassDefFoundError?
Both are unable to load at run time,
NoClassDefFoundError errors thrown if .class file cannot be found,
where as ClassNotFoundException error occurs if only when you try to load a class by string name by ClassLoader using class.forName or Class loader's findSystemClass method or LoadClass in ClassLoader.

Hope you understand the fix to solve NoClassDefFoundError in java. Please leave a comment and share this.

Static Import in java 5:-

static import is java language feature introduced in java version 5 alias code name as tiger version. This was introduced to simplify the access of static variables and static members without using classname.Before static import is introduced, we have normal import statetements for every java class to use the methods and classes with using class name

How the java code looks like before static import feature is introduced?

Normally in java coding, if we want to use the any static member variables or a method of a class in our code,
we have to first import that class using normal import keyword, after that we have to use variables/methods with class name in the code (Math.E)). below is the example for normal import usage with access the member variables using qualified class name.
import java.lang.*;
public class ImportDemo {
 public static void main(String args[]) {
  System.out.println("This is sample program without using static import functionality" + Math.E);

In the above program, we have used System and Math classes are used from java.lang package. In java program, we don't need to import any java.lang package as default package imported is java.lang package for every program. i have written in the above program and imported java.lang package for our this tutorial purpose

The basic difference between normal import and static import is normal import can call the member variables with class name in the package.
static import can be defined and static member fields can not refere any class name and use directly without classname.

static import usage example:-

Now we will see the example for static import feature which we can use the static member variables of java.lang.System and java.lang.Math classes without qualified class name.

import static java.lang.System.*;
import static java.lang.Math.*;
public class ImportDemo {
 public static void main(String args[]) {
  out.println("This is sample program without using static import functionality" + E);
out is static field in java.lang.System class and E is static member variable for java.lang.Math class

For using static member variable E in Math class in java.lang Package, we have coded by adding static import something like import static java.lang.Math.*; or java.lang.Math.E. It will always good idea to define for each static member(Math.E) instead of all static members(Math.*) in static import declaration

Advantages of Static import feature:-

To call the static members without using class name in our code. By making static import code statments makes all the static members of that class are avilable to declared java class
Static import can be used for static member variables as well as static members without refering class name in java code. It simplifies the code readablity for the constants.

Disadvantages of Static import feature:-

if we are importing the two same static constansts from different classes in the same class. there is possiblity of ambiguity for the compilier to throw error.

Please let us know your comments on this.

StackOverflowError is one of frequent exception/issue in java projects. This exceptions should not be caught by programmer but thrown by java virtual machine at runtime. whenever this exception is thrown, applciation stopped it's execution

java stackoverflowerror class overview:-

StackOverflowError extends java.lang.VirtualMachineError class which inturns extends java.lang.Error. so what is java.lang.Error?. Error class extends Throwable class specifies unusual errors that application unable to catch these exceptions.These exceptions are not programming related exceptions but thrown by java virtual machine.

StackOverflowError exception thrown in the method when the method are called recursively in infinite times.

Let us see the below program how it throws the exceptions

public class StackDemo {

 public static void main(String[] args) {
  StackDemo sd=new StackDemo();

 public void hello(){
output for the above program is exception with message like "Exception in thread "main" java.lang.StackOverflowError" thrown by applications.

The below is the program execution in memory in java vitural machine
1. Main method is starting point for the exectuion in the parent thread called main, once execution starts, main method makes one entry in the bottom of the call stack. please note that each thread has one own call stack.
2. After that,StackDemo Object is created and method hello() is called from the main thread, method area would be stored in the call stack above main () method area.
this method calls hello() method reursively calls same method infinte times, this makes call stack stores all method entires in memory. and size of the call stack is grown and the exception throwns when call stack unable to accomdates enough size for all these entries in memory. here stack is full with all the entries, StackOverflowError is thrown.
3.hello method is called recursively itself infinite times. so please make sure that avoid recursie infinite method calls.

This erros are thrown by java vitural machin, so be causeful with recursive calls in the methods.

Please leave a comment your thoughts on this.

Inject Enum of java 5 in Spring Framework:-

Spring framework is popular opensource framework developing applicaitons in java.
Enum is java enumeration keyword introduced in java 5 features.

ususally, In Spring configuraiton file, we will inject different custom classes as well as predefined classes like Integer,String.

But injecting enum class in spring container is different as if we not correctly inject, we will end of with exceptions like "org.springframework.beans.TypeMismatchException: Failed to convert property value of type".
so what is the solution of avoiding TypeMismatchException in spring? The solution is to use either custom property editors in spring custom configuraiton files
we have to conver the enum to string to inject enum to class in spring.

This tutorials is to find out the ways to inject enum objects in spring.
here is the enum defination java class

package com.cloudhadoop.constants;
enum Day {
 private final int dayNumber;

 private Day(int dayNumber) {
  this.dayNumber = dayNumber;

 public int getDayNumber() {
  return dayNumber;


There are many ways to inject the enum object of java 5 in spring framework

one way is to inject the enum single value using enumProperty as described in the below screenshot
spring property editors are internally assigned the correct value to enum property

second approach is to inject using factory-method as in below screen shot.

The above approaches is light weight and spring container validates the configuraiton when container is stated

or other approach is to as is to assign all enum values using util:constant tag

This approach provides for bean validation in IDE's at development time. Please click below screenshot for the spring code configuration file.

The three apporaches works with enum in java with spring 2.5.6 version

Please share your comments on this topics

Fix for IllegalArgumentException in java:-

IllegalArgumentException is one of frequent exceptions occured in java programming language. This exception extends RunTimeException class. These are also called UncheckedExceptions and need not to be handled in java code for this exceptions occurs at runtime. Exceptions in java are used to indicate that there is an error in your code.

IllegalArgumentException is good way of handling in the code.This exception occurs when caller calling method with incorrect arugment types for the methods. Methods in java are written in such way that we have to deal with valid data as well as invalid data,if it is valid data,process the data,and result is returned.In case of bad data, we have to throws this exception with detailed message to the caller. This is good way of handling invalid data with approriate message to the caller, then the caller should pass the correct data to the method.,

public class IllegalExceptionDemo {
   public static void main(String[] args) {
 MathServiceImpl service=new MathServiceImpl();
 System.out.println(" value "+service.divide(12,0));
class MathServiceImpl {
 public int divide(int number1,int number2)
    throw new  IllegalArgumentException("Number 2 can not be zero "+number2);
    return number1/number2;
The above code throws IllegalArgumentException when an argument is passed with zero values and the error message looks like as follows.
Exception in thread "main" java.lang.IllegalArgumentException: Number 2 can not be zero 0
 at MathServiceImpl.divide(
 at IllegalExceptionDemo.main(

Whenever any expceiton occurs, please see the complete stack trace for debugging, stack trace gives the exception type(IllegalArgumentException), detailed message(Number 2 can not be zero 0) and line number of the code( where exception is thrown.

method divide() is throwing exception when an agument(number2 is zero) using throw keyword
called method should have to handle the exception, throws this exception to the caller with proper message.Caller method need not be handled this exceptiona as this is runtime exception

In programming, IllegalArgumentExceptions are coded in the following scenarios to validated the invalid arguments for methods

1.Service API methods
4.Unit testing

When to throws IllegalArgumentException :-
This exception throwns for invalid arguments types for the below values

1.When object as argument in methods should check for null references before accessing the object methods
2.Invalid data check for methods arguments like checking for valid numbers, custom data check.

Please share your thoughts on how do you handle this exception.

deque in java:-

Deque is abbrevateted as double ended queue like a normal queue, can store the collection of objects. It is one of the collections class introduced in java 6. Why deque is different from other collection classes? the answer is, in deque, we can inserts and deletes the objects from the both start, end of the the collection. where as normal collection inserts/deletes are happeneing at last only.

Deque is interface introduced in java 6 java.util.collections package which implements java.util package. Deque interface extends java.util.Queue which in turns extends java.util.Collection, so we can insert/delete/iterate of all the objects that collections provides.

Deque is interface so you can not create a objects,Deque is implemented by two classes ArrayDequeand LinkedList.

ArrayQueue is just like array list implementaiton of queue, LinkedList is implementation of double linked list.

So you got the basic idea on ArrayQueue, When i am learning Deque, ArrayList class came into my mind, and immediately question came into my mind, what is the difference between ArrayQueue and ArrayList?.When to use ArrayList and ArrayQueue?. Answers for these questions are found in my below table.

ArrayList ArrayDeque
Elemetns are inserted/deleted at any location including last Elements are inserted/deleted at both ends i.e start and last
Elements are accessed by index elements are accessed by starting index or ending index
ArrayList are growable array of objects ArrayDeque are growable array of objects,better for implementing statck(LIFO) or Queue(FIFO)
Performances better for accessing elements, not for insert/delete operations Queue performs better for insert/delete operations compared to access elements

Basic Deque examples :-

1.How to add elements to Queue?

For queue, we can add object to deque in may ways one way is using add version methods other is offer version methods as well as push() method
Deque dequelist=new ArrayDeque();

System.out.println(" "+dequelist);

and output is
equity Derivative commondities stocks
add() method ads the elements at starting list of objects
addFirst() method adds the elements starting list of objects
addLast() method adds the lements end of the list.

offer() version of methods also do the same as like add() version of methods.
but the difference is if the deque is fixed size of collection, we can use Offer version of methods.
if we add objects using Add methods for fixed queue, it throws IllegalStateException if objects are unable to add the objects

There is one more method i.e push() which adds an element to the end of queue,returns true if added, otherwise returns false, throws IllegalStateException if no enough space in the collection

2.How to remove elements in Deque?:-
Deque API provides many types of methods to delete the objects from the queue 1. remove version methods 2. Poll Version methods 3. using pop() method
deque provides the following methods to remove elements.
poll() method deletes the first matched object from the deque
pollFirst() method deletes the first object from the deque
pollLast() method deletes the last object from the deque

remove version of methods also do the same thing like poll() methods except it throws NoSuchElementException if collection is empty.
poll() methods returns null if the deque is empty

there is one more method i.e pop() which deletes an element from the queue,returns delted element.

3.How to Access elements in Queue?:-
traversing elements in deque is same as list, we can use either Iterator, for each loop, or using specific methods using peek()

Iterate objects in Queue:-
//using iterator for deque
Iterator forwardIterator=dequelist.Iterator(); // for forward iteration
Iterator BackwardsIterator=dequelist.descendingIterator(); // for iteration of elements in reverse order
System.out.println(" "+(String)forwardIterator.nextElement());
//using for each loop in deque
for(String element:dequelist){
and output is
equity Derivative commondities stocks

get the specific elements in deque:-
the above methods retrieves the elements from the queue, elemetns throws NoSuchElementException if queue is empty, where as peek returns empty

4.How to find if element exists in deque?:-

To check an element available in queue, we have to use contains(Object) method, returns true if available,else return false

Please share your comments if you like this posts.

Basic Usage of NumberFormat in java


When we are developing any applications targeted to different countries, the presentation of the data shoulld be

specific to each country eventhough data storage is always same. This is tedious task for java programmers to handle of formating the same data to specific country. java introduced Globallization and localization concept. As part this there are number of formatting classes including NumberFormat are introduced in java.text package.

What is internalization(i18n) and localization in java?
internilization is a concept programming technique to code in sucha way that any software applicaitons works for multiple languages as well as countries. data from application should be displayed as per the locale specific.

Usually, considering financial applicaiton, the data stored in backend database is always same ,but the format for displaying is always different for each country. that means USA has dollar symbol as currency in representing any price of object and dollar always displayed before the price number ($100) Where as India has different symbol for currency and this symblo should be displayed after price of any number (100 Rs). So we have to write a applicaiton in sucha way that it supports multiple languages and multiple countries.

one more scenario is if we develope a web applicaiton that is targeted to different countries to display such data, we have to handle the different scenario as per below
the 1000000.11 number is stored in database and should have to display based on thousand separator as per specific country, that means, If i am accessing the applicaiton from USA, USA specific format should be displayed.

1,000,000.11 should be displayed for USA people
1 000 000,11 should be displayed for Genrmap people
The number stored is independent of any local, but the display should as per the locale

NumberFormat solves all above display of all the number formating capabilities as just mentioned above.

NumberFormat provides custom Format to format the numbers based on applicaiton needs

java provides API for solve all those display formats NumerFormat is one of the class in java.text, with these we can format the below cases.

1. Format the number as per the country and language
2. Format the numbers as per the currencies
3. Format the number percentages like thousand separator and precision

NumberFormat is abstract factory class which we can create objects using static getInstance() method Only

NumberFormat examples:- These examples are used to give basic idea of NumberFormat class or Subclass using custom format.

1. How to format a number to thousand separator?

We can do in many ways to format the format the number into thousand separator. One way is to use String.format() method 2. Using regular expression
and third way is using NumberFormat java class.

pasting the code using NumberFormat example.

Locale usaLocale = new Locale("en", "US");
Locale canadalocale = new Locale("fr", "CA");
NumberFormat formatusa = DecimalFormat.getInstance(usaLocale);
System.out.println("USA " + formatusa.format(123456789));
NumberFormat formatCanada = DecimalFormat.getInstance(canadalocale);
System.out.println("Canada " + formatCanada.format(123456789));

value is 123456789 and out put value should be separated with thousand separator and returned output 123,456,789

2. How to format the number to decimal places. or DecimalFormat example

DecimalFormat class is used to format the number to decimal places.NumberFormat is parent class for DecimalFormat. Mosttly decimal Format class is used to format the number specific to local settings

DecimalFormat df=new DecimalFormat("##.0000");
System.out.println("Decimal value with 4 digits "+df.format(12345.893477));

There are two things to note as we are providing pattern "##.0000" to DecimalFormat object
Format object format thes double/float number to 4 digits after decimal point.
This example also round the double value apply the decimal places for specific pattern.

3. How to display the number in currency format?

Locale englishLocale = Locale.US;
String numberDisplay = NumberFormat.getCurrencyInstance(englishLocale).format(89756.862);
Locale germanyLocale = Locale.GERMANY;
String numberDisplayInGermany = NumberFormat.getCurrencyInstance(germanyLocale).format(89756.862);
System.out.print(" "+numberDisplay+" "+numberDisplayInGermany);

and the output should be
$89,756.86 89.756,86 €

Hope you understood the basic usage of NumberFormat class in java . Please share your comments on this

Array List in java:-

ArrayList is implementation of List interface in java.utils package.ArrayList stores the collection of objects in the order of insertion. ArrayList stores the objects and grows the size of the list dynamically that's why array list is re sizable array. where as array is static once assigned the values, the size is fixed.In the real time programming, ArrayList is used to manipulate the collection of custom objects.

Arraylist is popular collection framework used in every day life of java developer.
In most of the backend programming, HashMap is used to store as temparary cache for either request scope or session scope.HashMap is combination of key and values. key and values should be either String,primitives or any custom object. The key stored in the HashMap is based on the hashCode computed for key'object Map is implemented by HashMap in utils package

Important points to remember for ArrayList:-
1.Object stored in ArrayList are insertion order
2.ArrayList is used to store the collection of objects with size increasing dynamically
3.ArrayList stores the objects including null values.
4.ArrayList is not synchronized

1. How to create a ArrayList:-
ArrayList has default constructor as well as constructor with integer parameter.
arraylist can be intialized with integer number also.

ArrayList emptylist=new ArrayList(); or
 ArrayList list=new ArrayList(10);
The above lines of code create ArrayList object with empty size as well as fixed size of array list.second case, the fixed size is 10

2. How to add Objects to ArrayList.
ArrayList provides add method to add the object to ArrayList
he map.
ArrayList list=new ArrayList();

3. How to show the elements in the ArrayList:-
using for each look, we can iterate each object in the list

for (Object str : list) {
 System.out.print(" " + (String) str);
and the output is
One Two Three Four Five
. Always make sure that you check for null check for list as it will throws NullPointerException if list is null. add the following code snippet for avoiding NullPointerException in ArrayList
add the for loop code here

4.How to find the size of ArrayList?:-

Java arraylist API provides size() method to find the number of elements in the HashMap
return the size of the arry list , as 5 is returned for the above code

5.How to check if the object/element is find in ArrayList:-
arraylist api provides contains() method which returns true if particular object found in the systme
System.out.print(" " + list.contains("One"));
and also other way is to use indexOf() method to get the index of an element in arraylist. This method returns position if the element is found the in
array list else return -1 if element/object is not avialble in array list.

6. How to Convert ArrayList to array:-
As array list to array is one of common mechanism in day to day programming.

collection API provides arrayList.toArray() method used to convert to array of objects
String[] strArray=(String [])list.toArray(new String[list.size()]);
  for (Object str : strArray) {
   System.out.print(" " + (String) str);
and the output is
One Two Three Four Five

7.How to convert array to ArrayList in java:-
to conver the array to arraylist, collection API provides java.util.Arrays class asList() method to be passed to ArrayList constructor
String[] strObjects = {"One1", "two2", "three3", "four4"};
List arrayList= new ArrayList(Arrays.asList(strObjects));

8.How to remove/delete element in list:-
ArrayList has remove method to remove the object from the list.

9.How to get the elements in list:-

list provides get() method to return the return the object found in the list

if element is not found, null is returned.

10.How to sort objects in ArrayList:-

if we are displaying the objects from the list, ther order is of insertion order onlly.
to sort the objects in the arraylist, collection api provides Collections.sort(List) method to sort in natural order.
This elements sort in natural order by the hashcode as well equals method default implementation order.

if we wan to display the custom order for primitive types or object based on member variables, we have to write our custom comparable java class which is passed to Collections.sort() method as other parameter.

Collections.sort(list,Comparable interface);

I hope you got the basic idea on array list with examples to work.

Please share your comments on this.

Enums in java:-

Enum is one of the cool language featured introduced as part of java 5 version.
enum values are constants meaning which can not be changed. These constants are specified using upper case letters as per java coding specifications

Enum is introduced in java 5 version,Before java 5 was introduced, we have to write our own constants to handle enum functionality as follows
public class MonthsConstants{
public static final String JAN="1";
public static final String FEB="2";
public class MonthsConstantsTest
{ int monthsCode; //can assign any value like 1,2 or 100

You have to handle all your constants yourself and causes error prone.
These values are valid type for compile time only and gives error if wrong type is assigned to these values. Moreover you can assign any values
if we want to add new constants, it would be more work is required for maintenance of your code.Because of all these enum class is introduced.

By default, enum implements java.lang.Enum which implements and java.lang.Comparable interfaces.

java enum API provides different methods like toString(),name() as well as valueOf() methods

I am listing down the best enum examples in java
1.How to define enum class?
This is one of the way to define enum in java
public enum Months{
This is going to create in java class and enum class name. Please note that enum constants has semicolon at the end of constant defination.

2.How to define enum inside an other class:-
public class MonthsClass{
public enum Months{
Months monthsNames;
In the above example, enum class is created in inside the class, please note that semicolo is not required after defining enum constants.

3.How to create enum object?:-
MonthsClass monthsObject=new MonthsClass();
we can create enum objects using new operator. and also we can attach constants to the enum class
4. how to define enum constructor :-
public enum Months{
private int monthCode
Months(int monthCode){
public int value(){
return monthCode;
enum constructor in enum are private, meaning outside classes should not able create enum objects creation.

5. How to compare Enum objects in java:-
normally we can compare objects using == and equals methods
enum constants can also be compared using the same.
if(Months.JAN==Months.FEB){return true else return false;}
we can also use equals method to compare the enum objects of same type.

6.iterate enum constants:-
enum class provides values() method for iteration which returns list of enum constants in the order of constants creation.

for(Months months:Months.values()){
System.out.print(" "+months);
and output is:-
7.How to convert enum to integer ?:-
We have encountered in our programming to convert enum constant to integer.
As defined enum declartion in steps #4
Months months=Months.Jan;
Integer int=new Integer(months.value());
value method in enum provides the value for the enum constants.

8.How to convert integer to enum constant?:-
we have to define the following method in enum class for returning the Enum for the given input as integer
static Months getMonths( int monthCode ) throws Exception
for (Months months : Months.values())
if (months.value() == monthCode)
return months;
Hope this solves the conversion to enum by providing integer as input to the above method

9. How to convert String to enum object?
enum class provides valueOf(String )method to pass the string as an argument, which return enum constants
Months month=Months.valueOf("JAN");
Months month=Months.valueOf("abc");
For first line in the above code,month object prints the string value as jan

second, valid string is not passed to enum class, it throws java.lang.IllegalArgumentException with message No enum constants for your class. to use enum class in switch condition:-

one of the coolest feature of enum is we can use enum objects in switch case as like a primitive type
Months month=Months.JAN;
 case JAN:
 case FEB:

Advantages of Enum class:-

1.By default enum classes are implementing serialization, and overidng equals and hashcode methods so no need for explicit serialization implementation
2.With usage of Enum class, EnumSet and EnumMap are introduced,collection of enums operations can be achieved
3. Maintenance of code using enums is very easy

Disadvantages of Enum class:-
enum class is extending java.lang.Enum, the classes in java.lang are final,so enum classes can not be subclassed.

Hope you understand enum examples in java.

Please share your comments that how you are using the enum class in your development/

Maven build debug

Maven is automated build project management tool and automates the build process by defining the all the dependencies in pom.xml.Developers encounters lot of issues while building maven project in development phase as well as release phase.we need to know the ways to debug any issues with maven build.I am listing down the different ways to debug the maven build issues.

There are number of ways to debug an maven project.
I am listing down the required steps for findout the real issues.

1. maven debug mode:-
if you are experience with running maven goals like compile or install, mostly informative message will bedisplayed. if any failure happens, These messages are not helpful to find out the exact cause.
In such case, try to run maven with -X flag to give the clear message of where the error is occured and also plugin configuration and detailed class loading information which is very helpful for the coders to find the real cause of an issue. This is perfect suitable debug option for maven plugin coders.
mvn -X  prints debugging messages
 mvn -e shows error messages
Please remember that this is debugging information for what maven do while building your project. This is not for your project debugging. i.e different concept. i will write one more post about the java project debug tips later posts.

This option will start the maven in debug mode. It will give the complete information messages like what are the different dependencies that are loading to your project and what goals are running.

2.dependencies issues in maven:-

In a real time, for maven project build,we have seen that our project has direct dependencies as well as indirect dependencies.

suppose in your project, you have direct dependency on one module say log4j-1.2.12 and you have other indirect dependency of log4j-1.2.12(coming from spring 2.0.6 which has dependency for your project). This would be the case of your project having two same modules(log4j) with different versions. This would be an class incompatible issue once your project is started in webserver. Then you have to keep the required module in your pom.xml and ignoring other module by specifying exclusion configuration.

To find out the dependency tree for your project, you have to use the below command
mvn dependency:tree
This list out all the dependencies for your project in tree explorer format.all these dependencies are downloaded to your local repository.

3.Debugging tests with maven surefire:-

we will use mvn test for running test cases of your maven project. As you know maven surefire plugin is used to run with your unit test of your project.

you have to provide the maven.surefire.debug property with maven test goal
mvn -Dmaven.surefire.debug test

This will run the tests in separate process.This will listen on port 5005. You can attach this process to eclipse for remote debug.
In the eclipse you have to create and configure the maven debug options as follows.
hostname is localhost
and port  is 5005

This is one of coolest feature provided by maven with eclipse remote debugging.
whenever we started the maven test case execution, you can put break points for stopping the debugger in your test classes for debugging purpose. Once the maven execution is over, eclipse debugger terminate the process.

and other way is to not to run the debugger in fork mode meaning is to execute the tests in the same process, we can use

mvn -DforkMode never test

Best Find command examples in linux and unix:-

find command is one of frequent command used in linux and unix operating systems.
find command is used by unix/linux users to search the specific files in directory as well as sub directories.
 find command examples in unix and linux
I use this command as part of my programming development with java for searching logs as well as java files in linux operating system.

In windows enviornment, users have the ability to search the any files directly using windows explore. But in Linux/Unix, we have to use command based options to search files.

Most of the people working on development projects, need to know the basics of find command, because they need to search source code files as well as applicaiton logs where the errors occured.

Find command can be combined with grep and other file related commans to make the powerful search in linux/unix.

So i am listing down the some of the find commands that i use daily as part of my software project development.

Find command options in unix and linux:-
usuall find command syntax is as follows.
find {directorytosearch} {options}

The following are the options to be given to find command.
1.File name to be search in the list of files.
2. directory or list of files to be specified where search for file name is to find.
3. type of files or directories to list all the files in the directory and subdirectories?:-

find . or find . -print
. represents the all the files in the current directory as well as sub directory.
this command shows all the files in the directory and sub directories to the console.

2. how to find files using name in the current directory:-
find . -name "" 
the above command, file name "" specified using the option -name searched in the current directory specified by option .
and print the file name to console.

3.How to execute last executed find command:-
find . -name
The last executed command usually stored in the session level cache, so typing the same command is time consuming alternative step is using this command will execute the last executed find command.
This ! can be used with any linux command to executed the last specified command.

4. Find all files that are owned by specific user?
$find /directory -user kiran 
usually if we search the files that are not owned by specific user, it gives output as 'filename and permission denied' message to the user

5 how to find file search using name ignoring case sensitive :-
$ find . -iname
Here the file name case is ignored and displays all the files with ignoring case

6. Find the files which are modified in the last one day:-
$ find . -mtime 0
This is very useful for applicaiton log changes that were modified in the last 24 hours. This is my one of the favourite find command bash to know the modified files in the last one day.

7. How to find the files which are modified in the last 10 mins in unix.
find . -mmin 10
This is basicall used to search files which are modified/created in the last 10 mins. This is one of my favourite find command
and few more examples for finding the modified files between 10 and 20 minutes in the linux
find . -mmin +9 -mmin -21 

8.How to list only the subdirectories and directories in file system.
find . -type d
9.How to find file names in subdirectory that is one level down current directory?
find -maxdepth 2 -name ""
-maxdepth 2 means subdirectories i.e level 2
if we want to find the files in the current directory , we have to use -maxdepth 1 with find command.

10.find all files based on file types?
normally, with find command, we search files only. with find command by providing -type option, we can search directories and symlinks in linux
1.Find regular files in linux
find . -type f
1.Find directories in linux
find . -type d
Find all the symlinks using find command
find . -type s

I hope you understand the basics of find command with examples.
I will write one article about advanced usage of find command in linux and unix.

Please share your comments .

How HashMap works in java:-

HashMap is implementation of Map interface in java. HashMap is popular collection framework used in every day life of java developer.
In most of the backend programming, HashMap is used to store as temparary cache for either request scope or session scope.HashMap is combination of key and values. key and values should be either String,primitives or any custom object. The key stored in the HashMap is based on the hashCode computed for key'object Map is implemented by HashMap in utils package

Important points to remember for HashMap:-
1. Order of keys stored in HashMap is based on hashing. Eventhough order is not fixed.
2.HashMap allows null keys and null values
3.HashMap is not synchronized meanning is not thread safety
4. Hashmap is fail fast meaning, if we are modifying/adding/remove any object while iteration of HashMap, it throws ConcurrentModificationException

keys stored in order of calculating the Hashing mechansizm .

1. Create HashMap Object using new in java:-
HashMap provides default constructor as well as other constructor with integer number
HasMap map=new HashMap() or
HasMap map=new HashMap(10)
The above one of the two lines create HashMap with emptry constructor or construtctor with integer. This number represetns initial capacity

2. Adding Objects to HashMap.
HashMap provides put method to store the key and values in the map.
HashMap map=new HashMap(10);
map.put("11", "oneone");
map.put("21", "twoone");
map.put("31", "threeone");
map.put("41", "fourone");

3. Itertion of all values in HashMap:-
HashMap provides values() method to iterate all the values
Collection collection=map.values();
 for(String str:collection){
  System.out.print(" "+str);
values() return the colleciton object which we can used in for each loop to return the each object
out put is
twoone fourone threeone oneone

4.Find out the size of hashmap:-

size() method is used to find out the size of the hashmap
return the size as 4 for the above map.

5. Check if key object available in HashMap:-

To check if specific key exist in HashMap, we have to use containsKey(Object obj) of HashMap. if the key is found in the map, it returns true other wise it returns false

map.containsKey("11") return true
map.containsKey("134") return false
6. Check if value object available in HashMap:-

To check if specific value exist in HashMap, we have to use containsValue(Object obj) of HashMap. if the value is found in the map, it returns true other wise it returns false

map.containsValue("oneone") return true
map.containsValue("cloudmap") return false
7. How to delete object from HashMap:-
map provides remove method which will removes key and value from the HashMap object.

To delete key object from HashMap, we have to use remove(Object key) method of HashMap and returns the value for that key

remember only key object should be passed to remove method and returns value for that key if removed, otherwise returns null.

String value=map.remove("21");
the above key "21" is found in map,then removes that key and value pair from the map, and returns the value object.

if key is not found, then null is returned.

8. remove all the objects from the HashMap:-

to remove all the key and value pairs from the map, use clear() method of HashMap.

After clear() method is used, if isEmpty() is called , it returns tru as all the objects has been removed.

9. Converting Map keys to Set:-

To convert the HashMap keys to set, we have to use keySet which returns Set of keys
Set keys=map.keySet();
 for(String str:keys){
  System.out.print(" "+str);
10. How to Synchrnoze HashMap in java:-

HashMap is not synchronized. meaning more than one thread modifies the state of an object. But we can mak HashMap as synchronized if

Map synchronizedHashMap = Collections.synchronizeMap(map);
maven clirr plugin  from org.codehaus.mojo:-
Maven Clirr  plugin is used to give the report of your current project by comparing with other same old project.Basically if we configured this plugin to your project, it checks your project jar with an older version jar that is configured in pom.xml to compare.This plugin is to compare the source code as well as jar comparisions for incompatable issues to find in early stage of any module before releasing the module.

Why maven clirr is important before maven release:- 
 if you are releasing any maven module, that module should be well worked with backward combatble with modules that uses it. Once module is released. that module is used by different developers of different teams, if you find any issues after release, then we have to fix that issue rerelasing is the tedious task. To avoid this, It is always good idea  to use clirr plugin execution checks against previous version to verify compatability before releasing any your project module. This will specify any binarly combatable issues with the previous code.
Adding this plugin is stright forward in pom.xml. we have to add this plugin element in pluginManagement section of your project's pom.xml. This is same process for any new plugin to add to your project.

org.codehaus.mojo is providing the plugin to maven repository. Once this plugin is configured,clirr-maven-plugin is downloaed into your local repository.

Maven Clirr plugin reporting:- Once you configured the clirr plugin, you have to generate the reports for the combatable issues.
This reports shows the list of all errors and warnings with detailed messages messages
if your current project version is 1.2, you need to check with oldest project jar (1.1), then you have to define that version in comparisonVersion element in the reporting section.

How to generate the Clirr report?
Once plugin configuration and reporting configuraiton is configured in pom.xml, we have to run maven site command to generate the report.
maven site
By running this on command prompt, This will generate a clirr html report under the target/site directory with clirr-report.html
Alternatively you can also run mvn clirr:clirr to generate the report .
mvn clirr:clirr

Hope you understand the basics of maven clirr plugin with examples.

Please feel to share your comments on this.

Hibernate criteria API:-

criteria are used to select the specific type of data from the database.
Let us take the usecase, where website has search capability provided, you have to search the website with different conditions, To handle this using hibernate, we can compose different parameters to Criteria object and make custom sql queries to database to retireve the data.

Hibernate criteria API is alternative to Hibernate query language or HQL and generate complex queries using different crierias. Here we can not write much sql or hql queries instead we can add the different critiera parameters, generates combatable sql queries

Criteria can be created using Session Object.

Create Criteria object using Hibernate API:-

Hibernate provides org.hibernate.Criteria to create criterias on a persistent object. This object is created from the avilable session objects.

HomeEquity is java persistence object which is mapped to home_equity in hibernate configuration.

Criteria equityCriteria = sess.createCriteria(HomeEquity.class);
	List homeEquitys = equityCriteria.list();

The above command retrieves all the rows in the table_homeequity table and store this all the rows in the list of HomeEquity Objects.

The following is the equvalent native SQL query that executes at database level is

select * from home_equity
The above results all rows in the table, instead if we wan to restrict only 20 records, then we have to configure number to restrict the data using Criteria.setMaxResults(Integer no)

Criteria equityCriteria = sess.createCriteria(HomeEquity.class);
List homeEquitys = equityCriteria.list();
the corresponding SQl query executed in different databases are

select * from home_equity limit 20  
For Oracle
select * from home_equity rownum <=20 

Sort the objects using Criteria Order by query:-

To order the list of objects with based on loan amount ordered by asecending order. we have to used criteria.addOrder method.
we can also add conditioninal order by parameter to criteria

Criteria equityCriteria = sess.createCriteria(HomeEquity.class);
List homeEquitys = equityCriteria.list();
The equivalent query executed at database is

select * from home_equity order by loan_amount asc

Criteria Distinct Query for retrieve unique objects:-

We have many number of approaches to retrieve the distinct result

First approach does the unique object filter in two steps, one step is retrieve all the objects into the memory, and next step is to filter for required unique nes
second approache using criteria projects
the qual native sql executed at database is 
select distinct loan_type from home_equity

Criteria Restrictions Query for comparison of objects:-

hibernate Criteria API provides Restrictions class which has built in methods(ne,eq,isNotNull,gt) to do comparison operators.

equityCriteria.add("name", "A%") );

the equal native sql query executed at Database is
select * from home_equity where name like 'A%'
equityCriteria.add( Restrictions.lit("loan_amount", "100000") );
the equal native sql query exected at database is
select * from home_equity where loan_amount <10000

equityCriteria.add(Restrictions.between("loan_amount", "10000", "50000"));

natvive sql for the above criteria is
select * from home_equity where loan_amount between 10000 and 50000
Hope you understand the basic criteria queries. This is part 1 for hibernate criteria queries

Maven assembly plugin in maven2:-

Maven is project build management tool , it automate the build phase of any java

projects.whenever the project is build, it crease single modules with the format of jar or war.
so it builds and zip your project including configuration files and other xml files into different customized output module types lik zip,jar,wat and other tar.gz formats.

As you know maven-war-plugin generates only war files, but in the projects, you need to archive in different formats like zipped formats, in that case we will use this plugin.

usually any project builds either war or jar file. so if the project(artifact name is CloudHadoop), the result of your install command is CloudHadoop-1.0.0-SNAPSHOT.war. More over, it generates single war file.

But using this plugin, we can multiple zip files like jar,zip with one exection

if you want to generate a zip file ( your project source code with it's dependencies as well as configuration files,There are three task involved to use  the maven-assembly-plugin in our project.

1.Configure maven-assembly-plugin plugin
2.Create custom assembly file
3.Run assembly maven goal command

Configure maven-assembly-plugin plugin:-

Maven is plugin based architecture so you need to configure plugin if we want to support any extra functionality.

Add the following plugin code in your pom.xml


maven-assembly-plugin is plugin is defined with plugin element with groupId and version
descriptorRef represents the type of folder structure in zipped bundled file.

the possible elements for descriptorRef are jar-with-dependencies(jar format like MANIFEST),project(zipped in project directory structure),src (only the src folder with sub folders)

descriptor specifies the cusotmized assembly xml which contains the code

execution phase represents the goal where this assembly code is executed

2.create custom assembly descriptor file:-

we can define our own custom assembly file to create our module. and the file name is zipCode.xml. you can define multiple assembly files by configuring this files in plugin declaration.

format specifies the result for format of you zipped file.
FileSets defined the files in the source directory of your project. and target directory is zipDirectory after your package goal is run.

Building your project with assembler:-

assembele plugin can be run in two ways.

one way with independent way of execution.

  mvn assembly:assembly 
.once the above goal is executed, it crease zipped file which contains files in the form of same project directory strucutre.

and other ways is attach the plugin execution with any predefined goals.

maven package

How to create multiple jar files with maven:-

listing down highlevel steps to generate multiple jar files with in single execution

1.maven-assembler-plugin configuration in pom.xml
2.define multiple exections element in maven-assembler-plugin plugin configuration and configure multiple fule custom assembler xml files
3.For each jar, define own custom assembler file with format type and source and target directories information and also include include and exclude elements
4. define the goal execution as single or attached with any predefined goals
5.Finally build your project using maven command in the command line.

Hope you understand basic idea on maven2 assembler plugin with basic example.

String class or object in java

Strigns are sequence of characters in any language. For java, sequence of characters are stored in the form of java.lang.String object.

Strings are immutable objects, meaning once created, the contents of the string, can not be modified in memory that means string objects are readonly.

String class is final class meaning we can't able to overried the behaviour of the methods defined in strings
why String objects are read only:-
String s="hadoop";

In the above example, string 's' is created with value as hadooop, in the next line, appending the string with cloud that means, string "cloud" object is created,
and the new string is created with value 'cloudhadoop' which is referenced by s, original value "Hadoop" is unreferenced

ways to String object creation:-

there are many wasy to create a string object in java using overloaded constructors

String cloudString=new String(); string object created without value

String cloudString=new String("cloudhadoop"); string object created with cloudhadoop value

String cloudChars="{'c','l','o','u','d'}"
String cloudString=new String(cloudChars);

String cloudString="cloudhadoop"
String cloudString=new String(cloudChars);

Length of the string.

to find out the number of characters in string, String.length method is used.

Concate strings or adding the strings in java:-

we can use either concat or plus operator to add the strings. Both will be used to add the strings at the end.

String sObj="cloud";
String addedString="hadoop+sObj; or

String sObj="cloud";
String addedString="s.concat("hadoop");

Comparison of two Strings:-

String sObj="cloud";
String addedString="cloud";
In the above how many objects are create? answer is only one object but the references are created two which are pointing to the cloud object.

In java we can compare references the two strings using "==" operator
if we want to compare two string objects data ,we can use equals method.
In the above example, == returns true and equal method returns true.

we can also use equalsIgnoreCase method to ignore the string case sensitivity

How to Split string into substrings:-

strings are separeted into list of sub strings with delimeter specified using String.split(String) method

String s="Best String examples";
String delimeter=" ";
String array[]=s.split(delimeter);

output:- Best String examples

format String with example in java:-

format method is provided in String object which is similar to c language println format.

To format the one of the string, we use codes to represent the different value types

String.format("Hi %s, today is %d day of month","Kiran",29);

and the output is Hi Kiran, today is 29 day of month.

%s represents strings type

%d represents integer type

%f represents float type

capital codes represents capital types of types

Hope you understand the basics of Strings in java