Wednesday, November 20, 2013

How to Marshall and UnMarshall POJO using Java

This blog explains about converting POJO(Plain Old Java Object) to XML and XML to POJO

- Below is the EmployeeDTO, Ensure to specify @XMLRootElement
       

  package com.fm.xmlutil.dto;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class EmployeeDTO {
    public EmployeeDTO() {
        super();
    }
    private String fName;
    private String lName;
    private String address1;

    public void setFName(String fName) {
        this.fName = fName;
    }

    public String getFName() {
        return fName;
    }

    public void setLName(String lName) {
        this.lName = lName;
    }

    public String getLName() {
        return lName;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress1() {
        return address1;
    }
}

       
 

- Below is the XMLUtil class

       

  package com.fm.xmlutil;

import com.fm.xmlutil.dto.EmployeeDTO;

import java.io.StringReader;
import java.io.StringWriter;

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

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * This class has the util methods to convert the POJOs to XML and vice versa using JAXB API.
 *
 * @author Fortune Minds
 */
public class XMLUtil {
   /**
     *This methodd converts Java Object to XML String
     * @param rootObject
     * @return
     * @throws Exception
     */
    public static String javaToXml(Object rootObject) throws Exception {
        StringWriter writer = new StringWriter();
        JAXBContext jaxbContext =
            JAXBContext.newInstance(rootObject.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(rootObject, writer);
        return writer.toString();
    }



    /**
     * This method converts XML to Java Object
     * @param rootObject
     * @param xmlString
     * @return
     * @throws Exception
     */
    public static Object xmlToJava(Object rootObject,
                                   String xmlString) throws Exception {
        JAXBContext jaxbContext =
            JAXBContext.newInstance(rootObject.getClass());
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        return jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
    }
    
    public static void main(String args[]){
        EmployeeDTO dto = new EmployeeDTO();
        dto.setFName("FortuneMinds");
        dto.setLName("Inc");
        dto.setAddress1("8000 Corporatecenter Drive");
        try {
            String r =javaToXml(dto);
            System.out.println(r);
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        
    }
}

       
 

Note :  Have jaxb-api-2.2.jar on class path

Thursday, November 14, 2013

How to split String using String Tokenizer



    String test ="Hello||FortuneMinds";
    StringTokenizer StrTkn = new StringTokenizer(test, "||");
    while(StrTkn.hasMoreTokens())
    {
      System.out.println(StrTkn.nextToken());
    }

Wednesday, November 6, 2013

Java Best Practices & Naming Standards


Java Best Practices

- Avoid creating unnecessary objects and always prefer to do Lazy Initialization, Create object only if needed.

- Never make an instance/object fields of class public, Ensure to give right access specifier based on requirement.

- Try to make classes immutable, This can be achieved by having private constructor and have public static method to get the instance of the class.
- Try to prefer Interfaces instead of Abstract classes

- Always try to limit the scope of Local variable, This can be achieved by declaring variable just before use.

- Use existing libraries instead of writing your own framework from scrach.

- Wherever possible user primitive data types and avoid unnecessary usage of wrapper class .
 For eg : use 'int' data type rather than 'Integer' just to hold    some integer values.


- Never use String constructor, For eg : String name ="Fortune Minds" is best practice , String name = new String("Fortune Minds") is not a best practice.  

Standard Java Naming Conventions



The below list outlines the standard Java naming conventions for each identifier type, Give meaningful name for every identifier you define/create in Java.

Packages: Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:
              package com.fm.employee
              package mathutil 
In software companies and large projects where the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features:
         package com.mycompany.utilities
         package org.bobscompany.application.userinterface 

 Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:
                 class Customer
                 class Account 

 Interfaces: Starts with Upper case and follows CamelCase. They tend to have a name that describes an operation that a class can do:
                interface Comparable
                interface Enumerable 
Note that some programmers like to distinguish interfaces by beginning the name with an "I":
            interface IComparable
           interface IEnumerable 

Methods: Names should be in mixed case. Use verbs to describe what the method does:
               void calculateTax()
               string getSurname() 

Variables: Names should be in mixed case. The names should represent what the value of the variable represents: Make sure to give meaningful names
         string firstName
         int orderNumber 
Only use very short names when the variables are short lived, such as in for loops:
 for (int i=0; i<20;i++)
 {
    //i only lives in here
 } 

Constants: Names should be in uppercase.
         static final int DEFAULT_WIDTH
         static final int MAX_HEIGHT