Sunday 24 February 2019

Marshalling And UnMarshalling in java



Explanation:Marshalling
As I told u earlier, to convert Java Object into an XML Document we are going to use JAXB API. Let’s see the steps to convert Java Object to XML (Marshalling using JAXB API).
Annotate the Java class with
@XmlRootElement annotation
Create a JAXBContext instance
JAXBContext context = JAXBContext.newInstance(Product.class);
Create a Marshaller reference with the help of JAXBContext instance by calling createMarshaller() method.
Marshaller marshaller = context.createMarshaller();
Creating XML object with the help of marshaller reference by calling marshal() method.
marshaller.marshal(Product, System.out);
Explanation:-UnMarshalling
Let’s see the steps to convert XML Object to Java (Unmarshalling using JAXB API)
Create a JAXBContext instance
JAXBContext context = JAXBContext.newInstance(Product.class);
Create a Unmarshaller reference with the help of JAXBContext instance by calling createUnmarshaller() method.
Unmarshaller unmarshaller = context.createUnmarshaller();
Creating Java Object with the help of unmarshaller reference by calling unmarshal() method.
Employee unmarshalledEmployee =(Product)unmarshaller.unmarshal(new File(“Product.xml”));


package govind; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; Product.java ProductObjectToXml.java ProductXmlToObject.java MarshallingUnmarshallingMain.java ================================================================================================================================ @XmlRootElement public class Product { private int productId; private String ProductName; private float price; public Product() { } @XmlAttribute public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } @XmlElement public String getProductName() { return ProductName; } public void setProductName(String productName) { ProductName = productName; } @XmlElement public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public Product(int productId, String productName, float price) { super(); this.productId = productId; ProductName = productName; this.price = price; } } =============================================================================================================================== package govind; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class ProductObjectToXml { public void marshallProductData() { try { JAXBContext jaxbcontext = JAXBContext.newInstance(Product.class); Marshaller marshaller = jaxbcontext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); Product p1=new Product(1001, "Laptop", 45000.0f); marshaller.marshal(p1,new FileOutputStream("product.xml")); marshaller.marshal(p1, System.out); System.out.println("Marshalling SuccessFully"); } catch (JAXBException | FileNotFoundException e) { e.printStackTrace(); } } } ============================================================================================================================ package govind; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class ProductXmlToObject { public void unmarshallProductData() { try { File f=new File("product.xml"); JAXBContext jaxbcontext = JAXBContext.newInstance(Product.class); Unmarshaller unmarshaller = jaxbcontext.createUnmarshaller(); Product p1 = (Product)unmarshaller.unmarshal(f); System.out.println(p1.getProductId()+" "+p1.getProductName()+" "+p1.getPrice()); System.out.println("Unmarshalling Successfully"); } catch (JAXBException e) { e.printStackTrace(); } } } =============================================================================================================================== package govind; public class MarshallingUnmarshallingMain { public static void main(String[] args) { ProductObjectToXml p1=new ProductObjectToXml(); p1.marshallProductData(); ProductXmlToObject p2=new ProductXmlToObject(); p2.unmarshallProductData(); } } o/p:------------------------ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <product productId="1001"> <price>45000.0</price> <productName>Laptop</productName> </product> Marshalling SuccessFully 1001 Laptop 45000.0 Unmarshalling Successfully

Saturday 23 February 2019

                                          Marshalling And UnMarshalling Process in java?
====================================================================================================
In this Introduction of JAXB tutorial, we are going to see about JAXB annotation and concepts. JAXB means “Java Architecture for XML Binding”. This JAXB API makes developers life easy for converting “XML Document to Java Object” (Marshalling) and “Java Object to an XML document” (Unmarshalling). Before JAXB came into picture, developers might use different parsers (like SAX Parser) to parse entire XML document by reading all the elements from top to bottom along with the xml attributes and finally form an Java Object. But when JAXB came, it really saves lot of time for parsing the XML Document.
Before going to see about JAXB annotation, we will first see the concepts behind this JAXB annotation. JAXB basically works on the principle of Marshalling and Unmarshalling.
Marshalling – The process of converting Java Object into XML document or JSON Object.
Unmarshalling – The process of reconverting the XML document or JSON object into Java Object.
Before discussing about different annotations in JAXB API in this blog we will see the basic example of JAXB – Marshalling and Unmarshalling.
==============================================================
Explanation:Marshalling
As I told u earlier, to convert Java Object into an XML Document we are going to use JAXB API. Let’s see the steps to convert Java Object to XML (Marshalling using JAXB API).
Annotate the Java class with
@XmlRootElement annotation
Create a JAXBContext instance
JAXBContext context = JAXBContext.newInstance(Employee.class);
Create a Marshaller reference with the help of JAXBContext instance by calling createMarshaller() method.
Marshaller marshaller = context.createMarshaller();
Creating XML object with the help of marshaller reference by calling marshal() method.
marshaller.marshal(employee, System.out);
Explanation:-UnMarshalling
Let’s see the steps to convert XML Object to Java (Unmarshalling using JAXB API)
Create a JAXBContext instance
JAXBContext context = JAXBContext.newInstance(Employee.class);
Create a Unmarshaller reference with the help of JAXBContext instance by calling createUnmarshaller() method.
Unmarshaller unmarshaller = context.createUnmarshaller();
Creating Java Object with the help of unmarshaller reference by calling unmarshal() method.
Employee unmarshalledEmployee =(Employee)unmarshaller.unmarshal(new File(“employee.xml”));
package govind;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private int id;
private String name;
private Float salary;
@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
}
==============================================================================================================================
package govind;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class EmployeeObjectToXml {
public static void main(String[] args) throws JAXBException, FileNotFoundException {
JAXBContext jaxbcontextobj = JAXBContext.newInstance(Employee.class);
Marshaller marshalobj = jaxbcontextobj.createMarshaller();
marshalobj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
Employee e1=new Employee();
e1.setId(1);
e1.setName("Govind Ballabh Khan");
e1.setSalary(10000.00f);
marshalobj.marshal(e1, new FileOutputStream("employee.xml"));
}
}
================================================================================================================================
package govind;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class EmployeeXmlToObject {
public static void main(String[] args) {
try
{
File f=new File("employee.xml");
JAXBContext jaxbcontext=JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshalobj = jaxbcontext.createUnmarshaller();
Employee e1 = (Employee)unmarshalobj.unmarshal(f);
System.out.println("Id="+e1.getId()+" Name"+e1.getName()+" Salary="+e1.getSalary());
}
catch (JAXBException e) {
e.printStackTrace();
}
}

}
o/p:-----------------
Marshalling
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="1">
<name>Govind Ballabh Khan</name>
<salary>10000.0</salary>
</employee>
Unmarshalling
Id=1 NameGovind Ballabh Khan Salary=10000.0

Saturday 16 February 2019


How Many Ways to create Object in java?






public class NewKeywordExample
{
    String name = "JavaTechnology";
    public static void main(String[] args)
    {
        NewKeywordExample obj = new NewKeywordExample();
        System.out.println(obj.name);
    }
}







===================================================================================








public class NewInstanceExample
{
    String name = "JavaTechnology";
    public static void main(String[] args)
    {
        try
        {
            Class cls = Class.forName("NewInstanceExample");
            NewInstanceExample obj =
                    (NewInstanceExample) cls.newInstance();
            System.out.println(obj.name);
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
       }
        catch (InstantiationException e)
        {
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
    }
}


=======================================================================================


public class CloneExample implements Cloneable
{
    @Override
    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
    String name = "JavaTechnology";
    public static void main(String[] args)
    {
        CloneExample obj1 = new CloneExample();
        try
        {
            CloneExample obj2 = (CloneExample) obj1.clone();
            System.out.println(obj2.name);
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }
    }
}


===============================================================================================


import java.lang.reflect.*;
public class ReflectionExample
{
    private String name;
    ReflectionExample()
    {
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public static void main(String[] args)
    {
        try
        {
            Constructor<ReflectionExample> constructor
                = ReflectionExample.class.getDeclaredConstructor();
            ReflectionExample r = constructor.newInstance();
            r.setName("JavaTechnology");
            System.out.println(r.name);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}



=============================================================================================================






import java.io.*;
class DeserializationExampleTest implements Serializable
{
    private String name;
    DeserializationExampleTest (String name)
    {
        this.name = name;
    }
    public static void main(String[] args)
    {
        try
        {
            DeserializationExampleTest d =
                    new DeserializationExampleTest("JavaTechnology");
            FileOutputStream f = new FileOutputStream("file.txt");
            ObjectOutputStream oos = new ObjectOutputStream(f);
            oos.writeObject(d);
            System.out.println("Data Write Successfully");
            oos.close();
            f.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    DeserializationExampleTest d=null;
        try
        {
            FileInputStream f = new FileInputStream("file.txt");
            ObjectInputStream ois = new ObjectInputStream(f);
            d = (DeserializationExampleTest)ois.readObject();
 
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        System.out.println(d.name);
    }



=======================================================================================================

Wednesday 6 February 2019


                                                 java.lang.NullPointerException


NullPointerException is a runtime exception, so we don’t need to catch it in program. NullPointerException is raised in an application when we are trying to do some operation on null where an object is required. Some of the common reasons for NullPointerException in java programs are;
  1. Invoking a method on an object instance but at runtime the object is null.
  2. Accessing variables of an object instance that is null at runtime.
  3. Throwing null in the program
  4. Accessing index or modifying value of an index of an array that is null
  5. Checking length of an array that is null at runtime.

case:-1 NullPointerException when calling instance method
public class TestNullPointer {

public static void main(String[] args) {

TestNullPointer t = marJava();

t.mitJava("nam tere kar java");

}

private static TestNullPointer marJava() {
return null;
}

public void mitJava(String s) {
System.out.println(s.toLowerCase());
}
}





===========================================================================================================================
case:-2 Java NullPointerException while accessing/modifying field of null object


public class TestNullPointer1 {

public int marjava = 10;

public static void main(String[] args) {

TestNullPointer1 t = mitJava();

int namterekarjava = t.marjava ;

}

private static TestNullPointer1 mitJava() {
return null;
}

}






===============================================================================================================================
case:-3 Java NullPointerException when null is passed in method argument



public class TestNullPointer2 {

public static void main(String[] args) {

marJava(null);

}

public static void marJava(String s) {
System.out.println(s.toLowerCase());
}
}


=================================================================================================================================
case:-4 java.lang.NullPointerException when null is thrown

public class TestNullPointer3{

public static void main(String[] args) {

throw null;
}

}




===============================================================================================================================
case:-5 java.lang.NullPointerException when getting length of null array

public class TestNullPointer4{

public static void main(String[] args) {

int[] marjava = null;

int len = marjava .length;
}

}


================================================================================================================================
case:6 NullPointerException when accessing index value of null array

public class TestNullPointer5 {

public static void main(String[] args) {

int[] marjava= null;

int len = marjava[2];
}

}

===============================================================================================================================

case:7 java.lang.NullPointerException when synchronized on null object

public class TestNullPointer6 {

public static String marjava = null;

public static void main(String[] args) {

synchronized(marjava) {
System.out.println("synchronized block");
}

}

}


================================================================================================================================



case:-8 HTTP Status 500 java.lang.NullPointerException

Sometimes we get an error page being sent as java web application response with error message as “HTTP Status 500 – Internal Server Error” and root cause as java.lang.NullPointerException.

For this I edited the Spring MVC Example project and changed the HomeController method as below.


@RequestMapping(value = "/user", method = RequestMethod.POST)
public String user(@Validated User user, Model model) {
System.out.println("User Page Requested");
System.out.println("User Name: "+user.getUserName().toLowerCase());
System.out.println("User ID: "+user.getUserId().toLowerCase());
model.addAttribute("userName", user.getUserName());
return "user";
}






o/p:-----------------------


HTTP Status 500 – Internal Server Error

Type Exception Report

Message Request processing failed; nested exception is java.lang.NullPointerException

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)


Note:----------------
Root cause is NullPointerException in statement user.getUserId().toLowerCase() because user.getUserId() is returning null.





                                            How to fix java.lang.NullPointerException



java.lang.NullPointerException is an unchecked exception, so we don’t have to catch it. Usually null pointer exceptions can be prevented using null checks and preventive coding techniques. Look at below code examples showing how to avoid java.lang.NullPointerException.
================================================================================================

if(mutex ==null) marjava =""; //preventive coding

synchronized(marjava ) {
System.out.println("synchronized block");
}


========================================================================================================


//using null checks
if(user!=null && user.getUserName() !=null) {
System.out.println("User Name: "+user.getUserName().toLowerCase());
}
if(user!=null && user.getUserName() !=null) {
System.out.println("User ID: "+user.getUserId().toLowerCase());
}

=================================================================================================================


public void mitJava(String s) {
if(s.equals("Test")) {
        System.out.println("test");
    }
}


=================================================================================================================


public void mitJava(String s) {
if ("Test".equals(s)) {
System.out.println("test");
}
}



=====================================================================================================================


public int getArrayLength(Object[] array) {

if(array == null) throw new IllegalArgumentException("array is null");

return array.length;
}



========================================================================================================================

String msg = (str == null) ? "" : str.substring(0, str.length()-1);


=========================================================================================================================

public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

============================================================================================================================


Object mutex = null;

//prints null
System.out.println(String.valueOf(mutex));

//will throw java.lang.NullPointerException
System.out.println(mutex.toString());




There are some methods defined in collection classes to avoid NullPointerException, use them. For example contains(), containsKey() and containsValue().