Straight from the Heart

Posts Tagged ‘java


One of the interesting concepts of the java is Serialization. We all know in java we can create reusable objects in the memory as long as the JVM is in the running state. Serialization provides the flexibility of object persistence beyond JVM lifecycle.

 

In the short serialization is the process of saving state of an object in a file. For that purpose, that object should implement the Serializable interface; same we are doing in the class Sedan.

 

A simple example of serialization is as follows-

 

public class Sedan implements Serializable{

private double price=44000.0;

 

public Sedan(double price){

      this.price=price;

}

public double getPrice() {

      return price;

}

 

public void setPrice(double price) {

      this.price = price;

}

}

 

public class SerializeSedan {

      public static void main(String[] args) {

 

            Sedan sedanObject= new Sedan(55000.0);

            FileOutputStream outputStream;

            try {

                  System.out.println(sedanObject.getPrice());

                  outputStream = new FileOutputStream(“myTestFile.ser”);

                  ObjectOutputStream obystr= new ObjectOutputStream(outputStream);

                  obystr.writeObject(sedanObject);

                  obystr.close();

 

                  FileInputStream in= new FileInputStream(“myTestFile.ser”);

                  ObjectInputStream objin= new ObjectInputStream(in);

                  try {

                        sedanObject=(Sedan)objin.readObject();

                        System.out.println(sedanObject.getPrice());

                  } catch (ClassNotFoundException e) {

                        e.printStackTrace();

                  }

                  objin.close();

            } catch (FileNotFoundException e) {

                  e.printStackTrace();

            }catch (IOException exp) {

                  exp.printStackTrace();

            }

      }

}

 

 

Run the SerializeSedan Class. The output will be-

Before- 55000.0

After- 55000.0

 

 

Now change the Sedan a bit.

 

 

public class Sedan extends Car implements Serializable { private double price=44000.0;

private Gearbox gearbox=null;

 

public Sedan(double price, Gearbox gearbox){

      this.price=price;

      this.gearbox=gearbox;

}

public double getPrice() {

      return price;

}

 

public void setPrice(double price) {

      this.price = price;

}

public Gearbox getGearbox() {

      return gearbox;

}

public void setGearbox(Gearbox gearbox) {

      this.gearbox = gearbox;

}

}

 

public class Car implements Serializable{

      private int yearModel=2005;

 

      public int getModelyear() {

            return yearModel;

      }

 

      public void setModelyear(int modelyear) {

            this.yearModel = modelyear;

      }

     

}

 

public class Gearbox {

 

private int gearCaseNumber=0;

 

public int getGearCaseNumber() {

      return gearCaseNumber;

}

 

public void setGearCaseNumber(int gearCaseNumber) {

      this.gearCaseNumber = gearCaseNumber;

}

 

}

 

Now we have an instance variable of type Gearbox, now for serialization of Sedan object, Gearbox should also implement Serializable interface.

And what if the Gearbox itself had references to other objects? This gets fairly complex. If it were up to the programmer to know the internal structure of each object the Sedan referred to, so that the programmer could be sure to save all the state of all those objects…..Which is really difficult to achieve. The good thing about java is – java Serialization mechanism internally take care of the whole object graph. In the case, we are unaware of the structure of Gearbox class or Gearbox is not implementing Serializable interface and we are not able to the change code also.

We can create a sub class of Gearbox, which eventually implement Serializable interface and what if Gearbox is final class.

 

Here transient modifier comes in picture. Transient is used to skip an instance variable during serialization.

 

public class Sedan implements Serializable{

private double price=44000.0;

private transient Gearbox gearbox=null;

 

Now during serialization, variable gearbox will be skipped.  We are skipping the gearbox variable so we can not read the gearCaseNumber while reading the state of the object as it will throw a null pointer error while getting Gearbox object.

 

Java provides solution for that problem also, for that some change requires in the Sedan class.  Add these two methods in Sedan class and these methods will solve the purpose.

 

private void writeObject(ObjectOutputStream os)

      {                          

            try {

                  os.defaultWriteObject();                         

                  os.writeInt(gearbox.getGearCaseNumber());           

            } catch (Exception e) { e.printStackTrace(); }

      }

 

 

      private void readObject(ObjectInputStream is) {

            try {

                  is.defaultReadObject();                            

                  gearbox = new Gearbox(is.readInt());             

            } catch (Exception e) {

                  e.printStackTrace();

            }

      }

 

Now output is-

68686After- 55000.0

68686After- 55000.0

Here, when you invoke defaultWriteobject() from within writeObject() you’re telling the JVM to do the normal serialization process for this object. When implementing writeObject(), you will typically request the normal serialization process, and do some custom writing and reading too. Please read sun java doc for the clear understanding of methods related to ObjectOutputStream class.

This was just an introduction of the Serialization, Lots more to follow. Hope it helps.

Cheers,

Manu

Tags:

How to Use EMMA-

 

ANT and Emma can be used together to automate the generation of code coverage report. Following Steps are solving the same purpose-

 

First define properties-          

            <!– EMMA BEGIN –>

            <property name=”emma.dir” location=”bin/emma” />

            <property name=”emma.thresholds” value=”class:100,method:100,block:100,line:100″ />

            <path id=”emma.libraryclasspath”>

                        <pathelement location=”lib/emma.jar” />

                        <pathelement location=”lib/emma_ant.jar” />

            </path>

            <taskdef resource=”emma_ant.properties” classpathref=”emma.libraryclasspath” />

            <!– EMMA END –>

 

 

1) Create ant target for the instrumentation of java classes-

 

      <!– ============================================ –>

      <!– Instrument the classes –>

      <!– ============================================ –>

      <target name=”emma.instrument”>

      <!– Instrument the class files. –>

      <emma enabled=”true”>

      <instr instrpath=”bin” destdir=”bin” metadatafile=”${emma.dir}/metadata.emma” merge=”true” mode=”overwrite”>

      <filter excludes=”com.XXX.somefolder.SomeJavaFile” />            

      </instr>

      </emma>

   </target>

 

 

2) Create ant target for the generation of code coverage report.

 

<!– ============================================ –>

      <!– Create coverage report –>

      <!– ============================================ –>

      <target name=”emma.report”>

      <emma enabled=”true”>

      <report sourcepath=”src” sort=”+name” metrics=”${emma.thresholds}”>

      <fileset dir=”${emma.dir}”>

      <include name=”*.emma” />

      <include name=”*.ec” />

      </fileset>

 

      <xml outfile=”${emma.dir}/coverage.xml” depth=”method” />

      <html outfile=”${emma.dir}/index.html” depth=”method” columns=”name,class,method,block,line” />

      </report>

      </emma>

      </target>

 

3) Create ant target for the generation of Junit report.

      <target name=”junitreport”>

        <junitreport todir=”${junit.output.dir}”>

            <fileset dir=”${junit.output.dir}”>

                <include name=”TEST-*.xml”/>

            </fileset>

            <report format=”frames” todir=”${junit.output.dir}”/>

        </junitreport>

    </target>

 

After the creation of above ant targets, first of all run emma.instrument target, it will create metadata file of instrumented classes at PROJECT_HOME/bin/emma folder and all classes will get instrumented.

Now there are two ways to create converage.ec file, depend on the nature of project-

 

I) If project is a simple java project, run your junit test cases and coverage.ec file will create in your PROJECT_HOME folder. Copy this file into the PROJECT_HOME/bin/emma folder and run emma.report ant target. This will generate code coverage report in the PROJECT_HOME/bin/emma folder.

 

II) If project is an enterprise application project, export the .EAR file of your project into the concern folder of your application server. For example if you are using JBOSS, export .EAR into the JBOSS_HOME\server\default\deploy folder. This .EAR file should contain metadata.emma file. Now put the URL into the browser and play with your (read as launch/run) application. This will create coverage.ec in the JBOSS_HOME\bin folder. Now Copy this file into the PROJECT_HOME/bin/emma folder and run emma.report ANT target. This will generate code coverage report in the PROJECT_HOME/bin/emma folder.

 

Finally Run jnitreport ANT target for junit report. So this is a simple way to generate code coverage and junit report through ant, Hope it helps. Good luck and please contact me if you have any difficulties or leave a comment below to help out other users.

 

Thanks,

Manu

Tags:

 

Today, while creating a xml entity resolver, i have got struck in a trifling situation. I was using the throws keyword for handling exception instead of try catch block at InputStream instance creation method for a particular url path-getInputStreamFromDB(String urlString), and due to that, in case of error, control was going to the ValidatingErrorHandler class (a error handler used by the parser), which was again pushing it to the ExternalEntityresolver class (an Entity Resolver) and this whole thing was going into a recursion.

 

code snippets to give an idea-

ExternalEntityResolver externalEntitityResolver = new ExternalEntityResolver();

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            factory.setAttribute(http://java.sun.com/xml/jaxp/properties/schemaLanguage&#8221;, http://www.w3.org/2001/XMLSchema&#8221;);

 

            factory.setNamespaceAware(true);

            factory.setValidating(true);

           

            ValidatingErrorHandler validator = new ValidatingErrorHandler();

           

            DocumentBuilder documentBuilder = factory.newDocumentBuilder();

            documentBuilder.setErrorHandler(validator);

            documentBuilder.setEntityResolver(externalEntitityResolver);

 

 

 

privateInputStream getInputStreamFromDB(String urlString) throwsMalformedURLException, IOException {

            InputStream inputStream = null;

            String xmlPath=   “D:\\eclipse workspace\\PIF_VALIDATION\\resource\\AddressBook-ZipToCityEPD.xsd”;

            //xmlPath=new File(xmlPath).toURI().toString();

            URL url = newURL(xmlPath);          Origin of exception

            URLConnection con = url.openConnection();

           

            if(con != null){

                  inputStream = con.getInputStream();

            }

            returninputStream;

      }

 

Later, when I have used try-catch block to check the stacktrace, encountered the real culprit- a fresh exception. This exception originates at the time of URL instance creation for a given path String.

 

try{

path= “D:\\eclipseworkspace

String \\PIF_VALIDATION\\resource\\AddressBook-ZipToCityEPD.xsd”;

URL url = new URL(path);           

            URLConnection con = url.openConnection();

           

            if(con != null){

                  inputStream = con.getInputStream();

            }

            }catch (MalformedURLException e) {

                  e.printStackTrace();// TODO: handle exception

 

java.net.MalformedURLException: unknown protocol: d

      at java.net.URL.<init>(Unknown Source)

      at java.net.URL.<init>(Unknown Source)

      at java.net.URL.<init>(Unknown Source)

      at com.XXX.xml.ExternalEntityResolver.getInputStreamFromDB(ExternalEntityResolver.java:80)

 

It seems as if String path is not interpreted as a file reference and because of this, it is throwing MalformedURLException with this “unkown protocol d” message. Preferably I feel it should be handled by URL class code by checking the format of the path String. For solving this problem, we need to create a valid URL in code itself.

 

Like-

Just put this line of code before the creation of URL instance-

 

path=new File(path).toURI().toString();

URL url = new URL(path);

 

There is one more way, more simpler one to achieve the purpose

Simply append “file:///” at the beginning of path String and it would solve the purpose.

 

Path=”file:/// “+path;

URL url = new URL(path);

 

Tags: ,

Translator

a

The Calendar..तारीख

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

गुफ्तुगू ….

Sindhu on How to integrate Sonar with…
Naga Anji on EMMA: a free Java code coverag…
Manu on Hiring
jarvarm on Hiring
Manu on Hiring

पन्ना

हिसाब-किताब

  • 40,681 hits

Tashveerein.......तसवीरें

Thanks for the Visit…आने का शुक्रिया

website statistics

Aaate-Jaate..आते-जाते

Top Clicks..पसंदीदा

  • None

The Selected One’s..चुनिन्दा

U come from..