Wednesday, 31 October 2012

Rest WebService Example Using Spring


Spring MVC framework support for RESTful Web services. This feature is available in Spring 3.
The highlighted approach for implementing RESTful Web services is Sun's JAX-RS specification.
Many tools are available that support JAX-RS such as RESTEasy, Jersey,  CXF and Restlet. Most of them are also providing Spring support. Spring does not directly support JAX-RS. RESTful feature is added to spring MVC itself.

Following series of events are happening when a request is sent to the Spring MVC Framework When a
  • At First the DispatcherServlet receives the request.
  • The DispatcherServlet interacts with the HandlerMapping and invokes the Controller associated with the request.
  • By calling the appropriate service methods the Controller process the request  and returns a ModeAndView object to the DispatcherServlet. The ModeAndView object contains the model data and the view name.
  • The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke.
  • The DispatcherServlet passes the model object to the View to render the result.
  • The View with the help of the model data renders the result and return it back to the user.
Example - Rest web service using Spring

STEPS

1) Create a web project in Eclipse.
2) Name it as WelcomeWithSpring.
3) Create a package in src folder and name as spring.example.controller.
4) Create a class named as WelcomeController.java
5) Use the below code in WelcomeController.java
  
package spring.example.controller;
import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
@RequestMapping
("/welcome")
public class WelcomeController {
@RequestMapping(value="/{username}", method = RequestMethod.GET)
public String getUserName(@PathVariable String username, ModelMap model) {
model.addAttribute(
"welcomeValue", username);
return "welcome";
     }
}

6) Modify the web.xml file as below

<web-app id="WebApp_ID" version="2.4"

xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Welcome Using Spring</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app> 
7) Create an xml file and named it as mvc-dispatcher-servlet.xml.Use the below code :

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 
<context:component-scan base-package="spring.example.controller" /> 
<mvc:annotation-driven /> 
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>

8) Create a folder named pages inside WEB-INF folder 
9) Create a jsp file and name it as welcome.jsp. Use the below code.

<html>
<body>
<h1>This is the Example of Spring REST web service Calling getUserName Method</h1>
<h3>User Name : ${welcomeValue}</h3>
</body>
</html>

10) Use the below jars as library in order to compile and execute this project.



11) Select this project, right click on it, go to option RUN as, select RUN ON SERVER option.

12) Configure Tomcat 6.0 or Tomcat 7.0 version here and add this project. Authomatically server will start after configuring server, adding the project and clicking on the finish option.

13) After hitting the below URL, you will get the output as attached below .
 http://localhost:<port number>/WelcomeWithSpring/welcome/gaurav


 14) Final Project Architecture in Eclipse as below:




Friday, 19 October 2012

Immutability example using final class


About  Immutable classes objects

If Immutable objects are used properly then it can simplify programming as they are simple to construct, test and use. Immutable objects are automatically thread-safe and have no synchronization issues.
Immutable classes are ideal for representing values of abstract data types, such as numbers, enumerated types etc.Integer, Long, and Float, are immutable in the Java class library.
Immutable objects are used to make good Map keys and Set elements.
Immutable classes can be write in easy way. A class will be immutable if all of the following are true:

  •   The class should be declared as final
  •   All of its(class) fields should be final
  •   this reference should not allow to escape during construction
  •  Any fields that contain references to mutable objects, such as arrays, collections, or mutable 
     classes like Date should be private.
  •  Do not change the state of the referenced objects after construction.
  •  Avoid any methods which can change the state of the object

//This is the sample program for the creation of immutable class.

package com.corejava.gaurav.examples;

public final class ImmutableClassTestExample {
   
    private final int[] myArray;

    public ImmutableClassTestExample(int[] anArray){

        //this.myArray = anArray;//Wrong way not to use like this...
       
        this.myArray = anArray.clone();//Defensive Copy This is the example for pure immutable class
    }
    public String toString(){
        StringBuffer strBuf = new StringBuffer("Number are: ");
        for(int i=0;i<myArray.length;i++){
            strBuf.append(myArray[i]+" ");
        }
        return strBuf.toString();
    }
}


//This is the sample program for the testing of immutability of another class

package com.corejava.gaurav.examples;

public class ImmutableClassCaller {
    public static void main(String args[]){
    int[] array = {15,21};
    ImmutableClassTestExample immutableRef = new ImmutableClassTestExample(array);
    System.out.println("Before Constructing - "+immutableRef);
    array[1] = 55;//change the element
    System.out.println("After Constructing - "+immutableRef);
    }
}

Note:- First remove the comment for the below line
//this.myArray = anArray; and comment this line this.myArray = anArray.clone();
and test for immutability. Again do the reverse and test for immutability, you will get the difference.

In multi-threaded programs Immutability is very important , because then we know that one thread won't corrupt / override a value used in another thread and it's also very useful in a single-threaded programs.


Externalizable interface example for Serialization and Deserialization


Difference between Externalization and Serialization

Externalizable gives control over the read/write process by implementing the readExternal and writeExternal methods. In Serializable JVM has full control for serializing object but on the other hand in Externalizable application/developer gets control for persisting objects. writeExternal() and readExternal() method provides complete control on format and content of Serialization process.

1. In Externalization custom Serialization process is used which is implemented by application but in Serialization, default serialization process is used.

2. JVM gives call back to readExternel() and writeExternal() of java.io.Externalizalbe interface for restoring and writing objects into persistence.
 



//This is the sample program for using Externalizable interface for Serialization and Deserialization

package com.corejava.gaurav.examples;

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

class First implements Externalizable {
    public First() {
        System.out.println("Constructor of class First");
    }

    public void writeExternal(ObjectOutput out) {
        System.out.println("WriteExternal method of class First");
    }

    public void readExternal(ObjectInput in) {
        System.out.println("ReadExternal method of class First");
    }
}

class Second implements Externalizable {
    public Second() {
        System.out.println("Constructor of class Second");
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        System.out.println("WriteExternal method of class Second");
    }

    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
        System.out.println("ReadExternal method of class Second");
    }
}

public class ExternalizableImplementation {
    public static void main(String[] args) throws IOException,
            ClassNotFoundException {
        System.out.println("Constructing objects to persist:");
        First objectDemo1 = new First();
        Second objectDemo2 = new Second();
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
                "ExternalizationExampleFile.out"));
        System.out.println("Persisting objects:");
        o.writeObject(objectDemo1);
        o.writeObject(objectDemo2);
        o.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(
                "ExternalizationExampleFile.out"));
        System.out.println("Reading back the objectDemo1:*****************");
        objectDemo1 = (First) in.readObject();
        System.out.println("Reading back the objectDemo2:*****************");
        objectDemo2 = (Second) in.readObject();

    }
}

Comparable and Comparator example


 Difference between Comparable and Comparator


[1]. java.lang.Comparable

  
  To implements comparable interface, A class must implement a single method compareTo().

    int obj1.compareTo(obj2)

 
java.util.Comparator

    To implements comparator interface, A class must implement a single method compare().

    int compare (obj1,obj2)

[2] Comparable

If a class implements the java.lang.Comparable interface then it will be able to compare its instances
itself with its another object

Comparator

This class will not compare its instances but it will be able to compare some other class’s instances.
A comparator object is capable of comparing two different objects.

[3]  Comparable interface having public int compareTo(Object o) method  returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Comparator interface having public int compare (Object o1, Object o2) method  returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

// This is the sample program for Comparable interface.

package com.corejava.gaurav.examples;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Collections;


@SuppressWarnings("rawtypes")
public class EmployeeComparableTestExample implements Comparable{
    private int empAge;
    private String empName;
   
    public EmployeeComparableTestExample(int age,String name){
        this.empAge = age;
        this.empName = name;
       
    }

    public int compareTo(Object obj){
        EmployeeComparableTestExample empTest = (EmployeeComparableTestExample)obj;
        int result = 0;
        Integer in1 = new Integer(this.empAge);
        Integer in2 = new Integer(empTest.empAge);
        result = in1.compareTo(in2);
        if(result==0){
            result = this.empName.compareTo(empTest.empName);
        }
        return result;
    }
   
    @SuppressWarnings({"unchecked" })
    public static void main(String args[]){

        List arrayLst = new ArrayList(0);
        arrayLst.add(new EmployeeComparableTestExample(55,"Nayan"));
        arrayLst.add(new EmployeeComparableTestExample(15,"Mihika"));
        arrayLst.add(new EmployeeComparableTestExample(34,"Dhiraj"));
        arrayLst.add(new EmployeeComparableTestExample(55,"Avantika"));
        Collections.sort(arrayLst);
        Iterator itr = arrayLst.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
    @Override
    public String toString(){
        return "Employee Age - "+empAge +" And His Name is - "+empName;
    }
   
}


// This is the sample program for Comparator interface.

package com.corejava.gaurav.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Employee2{
    int empId;
    String empName;
    public Employee2(int id,String name){
        this.empId = id;
        this.empName = name;
    }
   
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    @Override
    public String toString(){
        return "Employee Id is "+ empId +" And Employee Name is "+empName;
    }
}


@SuppressWarnings("rawtypes")
public class EmployeeComparator implements Comparator{
   
    public int compare(Object obj1,Object obj2){
        int result = 0;
        Employee2 emp = (Employee2)obj1;
        Employee2 emp1 = (Employee2)obj2;
       
        Integer int1 = new Integer(emp.getEmpId());
        Integer int2 = new Integer(emp1.getEmpId());
       
        result = int1.compareTo(int2);
       
        if(result == 0){
            result = emp.getEmpName().compareTo(emp1.getEmpName());
       
        }
       
        return result;
    }

    @SuppressWarnings("unchecked")
    public static void main(String args[]){

        List arLst = new ArrayList(0);
        arLst.add(new Employee2(32785,"Gaurav"));
        arLst.add(new Employee2(62653,"Pritish"));
        arLst.add(new Employee2(12345,"Anita"));
        arLst.add(new Employee2(32885,"Bhupesh"));
        Collections.sort(arLst, new EmployeeComparator());
        for(Object obj:arLst){
            System.out.println(obj);
                 }
        }
}

Note:-  In Java Comparable interface is used to implement natural ordering of object. String, Date and wrapper classes implements Comparable interface. Comparator is used for sorting customization.

With the help of comparator we can provide more then one order behavior while this is not true with comparable.

Use of StreamTokenizer


StreamTokenizer significance

The StreamTokenizer class is used to break any InputStream into a sequence of “tokens,” which are bits of text delimited by whatever we will choose. A stream tokenizer takes an input stream and parses it into tokens and it is allowing the tokens to be read one at a time.


//This is the sample program for counting words and numbers in a file available in file system.

package com.corejava.gaurav.examples;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;


public class countWordsAndNumbersUsingStreamToenizer {
   
    /**
     * Example method for using the StreamTokenizer class
     */
    public void countWordsAndNumbers(String filename) {
       
        StreamTokenizer sTokenizer = null;
        int wordCount = 0, numberCount = 0;
       
        try {
           
            sTokenizer = new StreamTokenizer(new FileReader(filename));
           
            while (sTokenizer.nextToken() != StreamTokenizer.TT_EOF) {
               
                if (sTokenizer.ttype == StreamTokenizer.TT_WORD)
                    wordCount++;
                else if (sTokenizer.ttype == StreamTokenizer.TT_NUMBER)
                    numberCount++;
            }
           
            System.out.println("Number of words in file: " + wordCount);
            System.out.println("Number of numbers in file: " + numberCount);
           
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new countWordsAndNumbersUsingStreamToenizer().countWordsAndNumbers("D://welcome.txt");
    }
}

Note: - Below is the contents of welcome.txt file

India is second biggest Country in Asia
234 hello 123 Welcome
7612 242542 4525 india
is great 145.( Sample text).

Collection Class methods example(binarySearch, sort, reverseOrder etc.)



//Sample Example for available methods of Collection class

package com.corejava.gaurav.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;

public class CollectionsClassMethodTestExample {

    public static void main(String args[]){
        ArrayList<Integer> lst = new ArrayList<Integer>(0);
        lst.add(9);
        lst.add(7);
        lst.add(3);
        lst.add(10);
        Object obj = Collections.min(lst);
        System.out.println("miminum obj is-"+obj);
       
        Object obj1 = Collections.max(lst);
        System.out.println("maximum object is-"+obj1);
       
               
        ArrayList<Integer> numLst = new ArrayList<Integer>(0);
        numLst.add(15);
        numLst.add(21);
        numLst.add(33);
        numLst.add(44);
       
        Collections.copy(numLst, lst);
       
        System.out.println("numlist is-"+numLst);
       
        ArrayList<String> slst = new ArrayList<String>(0);
        slst.add("A");
        slst.add("B");
        slst.add("C");
        slst.add("D");
       
        Enumeration e = Collections.enumeration(slst);
        while(e.hasMoreElements()){
            System.out.println("elements are-"+e.nextElement());
        }
       
        Collections.sort(lst);
        System.out.println("Elements after sorting-"+lst);
        int index = Collections.binarySearch(lst, 9);
        System.out.println("element available at index-> "+index);
       
        Collections.swap(lst,0,3);
        System.out.println("Lst is after swap="+lst);
       
       
        Comparator comparater = Collections.reverseOrder();
        Collections.sort(slst,comparater);
        System.out.println("slst elements are after sort in desc order-"+slst);
    }
}

CopyOnWriteArrayList and CopyOnWriteArraySet


 Fundamentals of CopyOnWriteArrayList and CopyOnWriteArraySet

[1.] The basic thing behind the CopyOnWriteArrayList and CopyOnWriteArraySet is all mutable operations make a copy of the backing array first, make the change to the copy, and then replace the copy.

[2]. If we want to share the data structure among several threads where we have few writes and many reads then we can use CopyOnWriteArrayList and CopyOnWriteArraySet.

[3]. The CopyOnWrite... collections avoid ConcurrentModificationException issues during traversal by traversing through the original collection and the modifications happening in a copy of the original store.

[4]. CopyOnWriteArrayList is a thread-safe version of ArrayList without the syncrhonized access limitations. Both are available in java.util.concurrent package.
 


//Sample example of CopyOnWriteArrayList  which is used to avoid ConcurrentModificationException and  UnsupportedOperationException
package com.corejava.gaurav.examples;

import java.util.Iterator;
import java.util.ListIterator;
import java.util.concurrent.CopyOnWriteArrayList;


public class CopyOnWriteArrayListTestExample {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String args[]){
        CopyOnWriteArrayList clst = new CopyOnWriteArrayList();
        clst.add("Shivam");
        clst.add("Priyanka");
        ListIterator itr = clst.listIterator();
        while(itr.hasNext()){
            System.out.println("Elements are->"+itr.next());
            clst.add("Dhanush");
       
        }
        Iterator itr1 = clst.iterator();
        while(itr1.hasNext()){
            System.out.println("after Modification Elements are->"+itr1.next());
        }
    }
}


//Sample example of CopyOnWriteArraySet  which is used to avoid ConcurrentModificationException and  UnsupportedOperationException

package com.corejava.gaurav.examples;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;


public class CopyOnWriteArraySetTestExample {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String args[]){
        CopyOnWriteArraySet cset = new CopyOnWriteArraySet();
        cset.add("Mitali");
        cset.add("Nikhil");
       
        Iterator itr = cset.iterator();
       
        while(itr.hasNext()){
            System.out.println("Set Elements are-"+itr.next());
            cset.add("Vishal");
        }
       
        Iterator itr1 = cset.iterator();
       
        while(itr1.hasNext()){
            System.out.println("After Modification Set Elements are-"+itr1.next());
           
        }
    }
}

Thursday, 18 October 2012

How to create JSON object and read back as java object using jackson api


//Sample Example to convert Java Map object to JSON object using jackson API.

package com.json.jackson.example;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JavaMap2JSON {

 public static void main(String args[]) {

  ObjectMapper objMapper = new ObjectMapper();
  Map<String, Object> userMap = new HashMap<String, Object>();
  userMap.put("name", "Gaurav");
  userMap.put("age", 32);
  List<Object> list = new ArrayList<Object>(0);

  list.add("MUMBAI");
  list.add("HYDERABAD");
  list.add("ANDHRA PRADESH");

  userMap.put("messages", list);

  try {
           objMapper.writeValue(new File("C:\\userMap.JSON"), userMap);
           System.out.println("User Map Converted Successfully");
                } catch (JsonGenerationException jge) {
              jge.printStackTrace();
        } catch (JsonMappingException jme) {
     jme.printStackTrace();
  } catch (IOException ioe) {
     ioe.printStackTrace();
    }
  }
}


//Sample Example to read JSON object back into JAVA object using jackson API.

package com.json.jackson.example;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class JSON2JavaMapConvertion {

 public static void main(String args[]) {
  ObjectMapper objMapper = new ObjectMapper();
  try {
           Map<String, Object> userMap = objMapper.readValue(new File("C:\\userMap.JSON"),
           new TypeReference<Map<String, Object>>() {
     });
           System.out.println("Name -" + userMap.get("name"));
           System.out.println("Age -" + userMap.get("age"));

 @SuppressWarnings("unchecked")
   ArrayList<String> alist = (ArrayList<String>) userMap.get("messages");

for (String listVal : alist) {
    System.out.println("List Values are-" + listVal);
                }
              } catch (JsonGenerationException jge) {
           jge.printStackTrace();
        } catch (JsonMappingException jme) {
       jme.printStackTrace();
      } catch (IOException ioe) {
     ioe.printStackTrace();
    }
  }
}
Note:- For the Execution of above programs jackson API is required.

How to use GSON API


//A sample pojo for the creation of GSON objects.

package com.json.googlegson.example;

import java.util.ArrayList;
import java.util.List;

public class UserPojo {

 private int age = 5;
 private String name = "Gaurav";

 @SuppressWarnings("serial")
 private List<String> messages = new ArrayList<String>(0) {
  {
   add("WIFE");
   add("FATHER");
   add("MOTHER");
   add("SISTER");
  }
 };

 @Override
 public String toString() {
  return "User [age=" + age + ", name=" + name + ", " + "messages="
    + messages + "]";
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public List<String> getMessages() {
  return messages;
 }

 public void setMessages(List<String> messages) {
  this.messages = messages;
  }

}



//Sample Program to create a json object file using GSON API.

package com.json.googlegson.example;

import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;

public class ToJSONExampleUsingGSON {

 public static void main(String rags[]) {

  UserPojo userPojo = new UserPojo();
  Gson gson = new Gson();
  String json = gson.toJson(userPojo);

  try {
             FileWriter fWriter = new FileWriter("C:\\UserPojoUsingGson.json");
             fWriter.write(json);
             fWriter.close();
          System.out.println("*****File Written Successfully*****");
         } catch (IOException ioe) {
       ioe.printStackTrace();
      }
   }
}

//Sample Program to read a json object file using GSON API.

package com.json.googlegson.example;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;

public class FromJSONExampleUsingGSON {

 public static void main(String args[]) {

  Gson gson = new Gson();
  try {
            BufferedReader br = new BufferedReader(new FileReader("C:\\UserPojoUsingGson.json"));
            UserPojo userPojo = gson.fromJson(br, UserPojo.class);
            System.out.println(userPojo);
          } catch (IOException ioe) {
          ioe.printStackTrace();
        }
     }
}

Note:- To execute this above example gson-2.1.jar is required.

How to handle NumberFormatException

//Sample program to handle Number Format Exception.

package com.gaurav.java.others;

public class NumberFormatExceptiontest {

 private static String number = "140.56";
 private static String testStr = "GAURAV";

 private static Double getTransactionAmount(String number) {
                      Double xx = Double.parseDouble(number);
                      return xx;
                 }

public static boolean isNum(String s) {
                try {
                        Double.parseDouble(s);
                     } catch (NumberFormatException nfe) {
                return false;
            }
          return true;
        }

 public static void main(String args[]) {

  // Check for number.

  boolean flag = isNum(number);
  Double num = 0.0;

  System.out.println("flag--" + flag);

             if (flag) {
                            num = getTransactionAmount(number);
                       }
  System.out.println("Number is-" + num);

  // Check for actual String value.

                    boolean flag1 = isNum(testStr);
                    Double num1 = 0.0;
                    System.out.println("flag1 value --" + flag1);

           if (flag1) {
                             num1 = getTransactionAmount(testStr);
                         }
                     System.out.println("Number is-" + num1);
                    }
               }

How to get IP address and MAC address of system


//Sample example to get IP and MAC address of our system.

 
package com.gaurav.java.others;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class GetMacAddress {

 public static void main(String[] args) {

  InetAddress ip;
  try {
           ip = InetAddress.getLocalHost();
           System.out.println("System Current IP address : "+ ip.getHostAddress());
           NetworkInterface network = NetworkInterface.getByInetAddress(ip);
           byte[] mac = network.getHardwareAddress();
          
          System.out.print("System Current MAC address : ");

          StringBuilder sb = new StringBuilder();

for (int i = 0; i < mac.length; i++) {
    sb.append(String.format("%02X%s", mac[i],
      (i < mac.length - 1) ? "-" : ""));
                  }
                    System.out.println(sb.toString());
               } catch (UnknownHostException e) {
            e.printStackTrace();
          } catch (SocketException e) {
        e.printStackTrace();
        }
     }
}

Note: - For execution of the above program JDK 1.6 is required because the method getHardwareAddress() is intoduced in JDk1.6.

How to create a zip file by converting jar file using Java API




//Sample example to create a zip file from a jar file using java api.


package com.gaurav.java.others;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GZipFile {

 private static final String OUTPUT_GZIP_FILE = "C:/zipFolder/javaee.zip";
 private static final String SOURCE_FILE = "C:/zipFolder/javaee.jar";
public static void main(String[] args) {

                 GZipFile gZip = new GZipFile();
                 gZip.gzipIt();
              }
 /**
  * GZip it
  *
  * @param zipFile
  *            output GZip file location
  */
 public void gzipIt() {
          byte[] buffer = new byte[1024];
             try {
                   GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(
                   OUTPUT_GZIP_FILE));
                   FileInputStream in = new FileInputStream(SOURCE_FILE);
                   int len;
                     while ((len = in.read(buffer)) > 0) {
                     gzos.write(buffer, 0, len);
                    }
                  in.close();
                  gzos.finish();
                  gzos.close();
                  System.out.println(" File Convertion Completed");
            } catch (IOException ex) {
          ex.printStackTrace();
         }
     }
}

How to merge two arrays


//Sample Example of how to merge two different array.

package com.gaurav.arrayexamples;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayMerge {

 public static void main(String args[]){
  String first[] = {"Kumar","Amit","Bimal"};
  String second[] = {"Shivam","Gaurav"};
  List<String> lst = new ArrayList<String>();
  lst.addAll(Arrays.asList(first));
  lst.addAll(Arrays.asList(second));

  Collections.sort(lst);

  Object [] third = lst.toArray();
  for(Object str: third){
   System.out.println("Elements are-"+str);
  }


 }
}

Coding Tips


Beauty Is in Simplicity


•      Beauty of style and harmony and grace and good rhythm depends on simplicity.
  • Readability
  • Maintainability
  • Speed of development
  • The elusive quality of beauty
  • Reusability
Refactoring

•Avoid Long blocks of code
•Remove Duplication
•Avoid multiple boolean expressions
•Remove Inconsistent or uninformative names
•Don't Provide Objects exposing their internal state
•Avoid Long sequences of conditions


Quotes : -->
“It’s ridiculous to live 100 years and only be able to remember 30 million bytes.  You know, less than a compact disc.  The human condition is really becoming more obsolete every minute.”
(Marvin Minsky)
“Controlling complexity is the essence of computer programming.”
(Brian Kernigan)
“The function of good software is to make the complex appear to be simple.”
(Grady Booch)
 “Good code is its own best documentation.”
(Steve McConnell)

Serialization Example(Read and Write)

//Example to Serialize an address.

//Example of Serialization
package com.corejava.gaurav.examples;
import java.io.Serializable;

public class Address4Serialization implements Serializable{
   
     /**
     *
     */
    private static final long serialVersionUID = 7488167097372042706L;
    private String city;
    private String colony;
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getColony() {
        return colony;
    }
    public void setColony(String colony) {
        this.colony = colony;
    }
   
    @Override
    public String toString(){
        return new StringBuilder(" Colony: ").append(this.colony).append(" City:--").append(this.city).toString();
    }

}
 
 //Writing the Address in the address4serialization.ser file
 
package com.corejava.gaurav.examples;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;


public class AddressSerializableClass4Write {
  
    public static void main(String args[]){
      
        Address4Serialization add = new Address4Serialization();
        add.setColony("Hitech City");
        add.setCity("Hyderabad");
        try{
        FileOutputStream fos = new FileOutputStream("C:\\address4serialization.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(add);
        System.out.println("address4serialization.ser is created*");
        oos.close();
        System.out.println("File Serialization Completed-");
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
}


//Reading the persist file(address4serialization.ser) from file system
 
package com.corejava.gaurav.examples;
import java.io.FileInputStream;
import java.io.ObjectInputStream;


public class AddressSerializableClass4Read {
   
    public static void main(String args[]){
        Address4Serialization address;
       
        try{
            FileInputStream fis = new FileInputStream("C:\\address4serialization.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            address = (Address4Serialization)ois.readObject();
            System.out.println("Colony is-"+address.getColony());
            System.out.println("City is-"+address.getCity());
            ois.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

}

How to access private variable outside using reflection


//Example of acessing private variable outside the class using reflection api.

package com.gaurav;
import java.io.File;

public class DisplayAllDrivesInSystem {
    private String accessPrivateVariableTest = "Welcome Gaurav";    
        -- We will acess this variable outside this class.
    public static void visitAllFiles(File dir) {
        if (dir.isDirectory()) {
          String[] children = dir.list();
          for (int i = 0; i < children.length; i++) {
            visitAllFiles(new File(dir, children[i]));
          }
        } else {
          System.out.println(dir);
        }
      }
    public static void main(String args[]){
        File dir = new File("C://Tomcat 5.5");
        File[] drives = File.listRoots();
        for(File i : drives){
                    System.out.println("Available Drives are-> "+i);
        }
        visitAllFiles(dir);
    }
}

// This is the another class where we will acess the private variable of above class using reflection api.


package com.gaurav; 
import java.lang.reflect.Field;

public class AccessPrivateVariableUsingReflection {
   
    public static void main(String args[]){
        try{
        @SuppressWarnings("rawtypes")
        Class c = Class.forName("DisplayAllDrivesInSystem");
        Field fields[] = c.getDeclaredFields();
       
        for(Field fld : fields){
            System.out.println("field values-->"+fld);
        }
        DisplayAllDrivesInSystem ref = new DisplayAllDrivesInSystem();
        c = ref.getClass();
        Field flds = c.getDeclaredField("accessPrivateVariableTest");
        flds.setAccessible(true);
        System.out.println("the private field value before change is-"+flds.get(ref));
        flds.set(ref, "Changed value Kumar Gaurav");
        System.out.println("Now the Private field Value after change is-"+flds.get(ref));
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

Java 5 - What's New

J2SE Version 5.0

Code named Tiger and released on September 30, 2004.


  • Generic— enhance compile time type checking and eliminates the need for casting every time we get an object out of Collections.
  • Autoboxing/unboxing— eliminates need of manual conversion between primitive types (such as int) and wrapper types (such as Integer), improves readability.
  • Enhanced For loop— eliminates error-proneness of iterators, Improves readability, reducing of writing unnecessary codes and it works with both arrays as well as objects that expose an iterator.
  • Static import— improves utility functions, relieve need for implementing a Constant Interface
  • Varargsallows to improve API usability and Variable args allow formatted I/O.
  • Typesafe enumsenumeration is a list of named constants, it improves readability and organization of constants.
  • Metadata—allows programmers to avoid writing boiler unnecessary codes and gives the opportunity to developers for declarative programming.
Some of other minor tweaks and incremental upgrades of JDK 5 are as follows:-


  • Instrumentation
  • StringBuilder class in jdk 1.5 (java.lang package)
  • Swing: new skinnable look and feel, called synth and Ocean, a new theme for Metal- beyond look and feels.
  • Automatic stub generation for rmi objects.
  • Scanner class for parsing data from various input streams and buffers.
  • Three new interfaces have been added to the Collection framework which is Queue, BlockingQueue, and ConcurrentMap. Queue is intorduce in java.util package where as BlockingQueue, and ConcurrentMap is available in java.util.concurrent package.
  • The Queue implementation classes are AbstractQueue, PriorityQueue, ConcurrentLinkedQueue where as  BlockingQueue implementation classes are ArrayBlockingQueueDelayQueue, LinkedBlockingQueuePriorityBlockingQueueSynchronousQueue.
  • ConcurrentHashMap is the implementation of ConcurrentMap.
  • Special purpose List and Set implementations are added like CopyOnWriteArrayListand CopyOnWriteArraySet. For example refer : - http://javatechtipssharedbygaurav.blogspot.in/2012/10/copyonwritearraylist-and.html

Demo exampleof Generics, Autoboxing/unboxing, Enhanced For loop and Static import

package com.gaurav.jdk5features;

import static java.lang.System.out;
import java.util.ArrayList;
import java.util.List;

public class ImplementaionOfJava5Features {
    public static void main(String[] args) {

        Integer testAutoboxing = 500; // demo of autoboxing, I am assigning int value
        out.println("integer Value is - " + testAutoboxing); // Use of Static Import
                                                               

        int testUnBox = testAutoboxing; // demo of auto-unboxing
        out.println("int value is - " + testUnBox); // Use of Static Import

        List<String> lst = new ArrayList<String>(0); // Use of Generics
        lst.add("Kumar");
        lst.add("Gaurav");
        lst.add("Shivam");
        for (String str : lst) // Use of Enhanced For loop
            out.println("Added elements are-" + str); // Use of Static Import
    }
}

Demo example of  Varargs(Variable Arguments):-

package com.gaurav.jdk5features;

import static java.lang.System.out;

public class ImplementaionOfJava5FeatureVarargs {
    static void variableArgumetTestForInt(int... num) { //Use of Varargs
        out.println("the variable length ->" + num.length);
        for (int number : num) {
            out.println("int arguments are-" + number);
        }
    }

    static void variableArgumetTestForBoolean(boolean... flag) { //Use of Varargs
        out.println("boolean variable length ->" + flag.length);
        for (boolean f : flag) {
            out.println("boolean arguments are-" + f);
        }
    }

    public static void main(String args[]) {
        variableArgumetTestForInt(1, 2);    //Use of Varargs
        variableArgumetTestForInt(11, 28, 56);    //Use of Varargs
        variableArgumetTestForBoolean(true, false);    //Use of Varargs

    }

}

Demo example of  Typesafe enums

package com.corejava.gaurav.examples;

public class ImplementaionOfJava5FeatureEnumType {
    public static void main(String args[]) {
        System.out.println("Gaurav Age is - " + Name.Gaurav.getAge());

    }

    enum Name { // Use of enum type
        Gaurav(33), Kumar(19), Raju(45);
        private int age;

        Name(int ageVal) {
            age = ageVal;
        }

        int getAge() {
            return age;
        }

    }

}

Demo example of  Metadata(Annotations)

package com.gaurav.jdk5features;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
// Use of Metadata(Annotations)
@interface MyFirstAnnotation {
    String strTestValue();

    double doubleTestval();
}

public class ImplementaionOfJava5FeatureAnnotation {
    @MyFirstAnnotation(strTestValue = "Two Parameters", doubleTestval = 3.275)
    public static void annotationUseMethod() {
        ImplementaionOfJava5FeatureAnnotation annotationsTest = new ImplementaionOfJava5FeatureAnnotation();
        // obtaining the annotation for the method annotationUseMethod()
        // displaying the values of the annotated members.
        try {
            Method m = annotationsTest.getClass().getMethod(
                    "annotationUseMethod");
            MyFirstAnnotation anno = m.getAnnotation(MyFirstAnnotation.class);

            System.out.println("String value is - '" + anno.strTestValue()
                    + "' and double value is - " + anno.doubleTestval());
        } catch (NoSuchMethodException nex) {
            System.out.println(nex.getMessage());
        }
    }

    public static void main(String args[]) {
        annotationUseMethod();
    }

}