Saturday, May 12, 2012

Jar creation wizard configuration (creating Example.jardesc).

Configuration:


<?xml version="1.0" encoding="UTF-8"?>
<jardesc>
<jar path="D:/Personal/Study/MyStuffs/Dropbox/EclipseWorkSpace/StrutsAndCoreJavaWorkspace/SpringAopDemo/SpringAop.jar"/>
<options overwrite="false" compress="true" exportErrors="true" exportWarnings="true" saveDescription="true" descriptionLocation="/SpringAopDemo/SpringAop.jardesc" useSourceFolders="false" buildIfNeeded="true" includeDirectoryEntries="false" storeRefactorings="false"/>
<manifest manifestVersion="1.0" usesManifest="true" reuseManifest="false" saveManifest="false" generateManifest="true" manifestLocation="">
<sealing sealJar="false">
<packagesToSeal/>
<packagesToUnSeal/>
</sealing>
</manifest>
<selectedElements exportClassFiles="true" exportOutputFolder="false" exportJavaFiles="false">
<folder path="/SpringAopDemo/src"/>
</selectedElements>
</jardesc>





  Save this file as "SpringAop.jardesc" ...


  Now you can use it directly from eclipse or ant.

Friday, May 11, 2012

Using String-intern() method

String intern method


Description of the code:

As shown in the example we have created three Strings in three different ways.

Then we have used the "==" operator to determine which Strings are equal. Basically an intern string is the one that has an entry in the global string pool. And if the string is not in global string pool then it will be added. If the pool already contains a string equal to this String object as determined by the equals (Object) method then on invoking the intern() method the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It returns a canonical representation for the string object.
The String class maintains a pool of strings privately, which is empty initially.
For any two strings s1 and s2, s1.intern() == s2.intern() is true if and only if s1.equals(s2) is true.

Returns a string that has the same contents as this string, but is defiantly to be from a pool of unique strings.

Here is the code of the program:

public class InternExample {
    public static void main(String[] args){
        String str1 = "Hello Java";
        String str2 = new StringBuffer("Hello").append(" Java").toString();
        String str3 = str2.intern();
        System.out.println("str1 == str2 " + (str1 == str2));
        System.out.println("str1 == str3 " + (str1 == str3));
    }
}



Output of the program:


C:\unique>javac InternExample.java

C:\unique>java internExample
str1 == str2 false
str1 == str3 true

Thursday, May 10, 2012

Serialization-Use of readResolve() & writeReplace()

Question: What are the writeReplace() and readResolve() methods used for?
Answer:

These methods are used to allow an object to provide an alternative representation for itself within an ObjectStream. Consider for instance the common means of implementing an enumerated type:

public class Gender implements Serializable {
public final static Gender MALE = new Gender("Male");
public final static Gender FEMALE = new Gender("Female");

private String name;

private Gender(String name) {
this.name = name;
}
}

This works fine within one JVM; there will be at most two Gender objects created, no matter how often you use Gender.MALE and Gender.FEMALE in your code. However, consider what happens when an instance of this class is serialized across JVMs. The ObjectInputStream will create a new instance of Gender that has the same value as the original instance. So, if you have many thousands objects that have been de-serialized via RMI you might end up with many thousands of extra instances of Gender. The writeReplace() and readResolve() methods are the hook to solve this problem.
One way of eliminating the extra instances and some of the unnecessary heap allocation would be to do something like this:
public class Gender implements Serializable {
public final static Gender MALE = new Gender("Male");
public final static Gender FEMALE = new Gender("Female");

private String name;

private Gender(String name) {
this.name = name;
}

Object writeReplace() throws ObjectStreamException {
if (this.equals(MALE)) {
return SerializedForm.MALE_FORM;
} else {
return SerializedForm.FEMALE_FORM;
}
}

private static class SerializedForm implements Serializable {

final static SerializedForm MALE_FORM = new SerializedForm(0);
final static SerializedForm FEMALE_FORM = new SerializedForm(1);

private int value;

SerializedForm(int value) {
this.value = value;
}

Object readResolve() throws ObjectStreamException {
if (value == MALE_FORM.value) {
return Gender.MALE;
} else {
return Gender.FEMALE;
}
}
}
}
This also guarantees that in all cases where genderInstance.equals(MALE) is true, genderInstance == Gender.MALE is also true.

Wednesday, May 2, 2012

Calculate and compare execution time for Map keyset,Map entryset,Poolable String,String Object and String array to List

package oopsConcept;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class ExecutionTimeCalculation{

public static void main(String[] args) {
methodWithObjStr();
methodWithPoolableStr();
methodWithStrArray();
extractDataFromMapUsingEntryset();
extractDataFromMapUsingKeyset();
}


/**
* Extract data from map using entryset.
*/
public static void extractDataFromMapUsingEntryset(){
long startTime = System.nanoTime();
Map map=new HashMap();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "d");
map.put("5", "e");
map.put("6", "f");
for (Iterator> iterator = map.entrySet().iterator(); iterator.hasNext();) {
Entry key = iterator.next();
System.out.println(key.getKey());
System.out.println(key.getValue());
}
long endTime = System.nanoTime();
System.out.println("Total elapsed time in nanoseconds for extractDataFromMapUsingEntryset:"+ (endTime-startTime));
}


/**
* Extract data from map using keyset.
*/
public static void extractDataFromMapUsingKeyset(){
long startTime = System.nanoTime();
Map map=new HashMap();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "d");
map.put("5", "e");
map.put("6", "f");
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();
System.out.println(key);
System.out.println(map.get(key));
}
long endTime = System.nanoTime();
System.out.println("Total elapsed time in nanoseconds for extractDataFromMapUsingKeyset:"+ (endTime-startTime));
}


/**
* Method with obj str.
*/
public static void methodWithObjStr(){
long startTime = System.nanoTime();
ArrayList logoList =new ArrayList();
for (int i = 0; i < 10; i++) { logoList.add(new String()); } System.out.println("methodWithObjStr: "+logoList); long endTime = System.nanoTime(); System.out.println("Total elapsed time in nanoseconds:"+ (endTime-startTime)); } /** * Method with poolable str. */ public static void methodWithPoolableStr(){ long startTime = System.nanoTime(); ArrayList logoList =new ArrayList();
for (int i = 0; i < 10; i++) { logoList.add(""); } System.out.println("methodWithPoolableStr: "+logoList); long endTime = System.nanoTime(); System.out.println("Total elapsed time in nanoseconds:"+ (endTime-startTime)); } /** * Method with str array. */ public static void methodWithStrArray(){ long startTime = System.nanoTime(); String s[]=new String[10]; List l=Arrays.asList(s);
System.out.println("methodWithStrArray: "+l);
long endTime = System.nanoTime();
System.out.println("Total elapsed time in nanoseconds:"+ (endTime-startTime));
}
}

Saturday, April 21, 2012

JAVA.IO.SERIALIZATION: Custom Serialization Process (writeObject,readObject,writeReplace,readResolve)

JAVA.IO.SERIALIZATION:
>>>> USE OF "private void writeObject(ObjectOutputStream objOut)throws IOException{}",

>>>> USE OF "private void readObject(ObjectInputStream objIn)throws IOException{}",

>>>> USE OF "ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException{}";

>>>> USE OF "ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException{}";

Note: when we use writeReplace(..) method to replace the serializing object and serialize some other object then we must implement the readResolve(..) method in other object.
See example below, writeReplace() in Employee class, and readResolve() in Organization class.
################################################################################################

package io_serialization;

import java.io.Serializable;

public class Employee implements Serializable{

private static final long serialVersionUID = 1L;
int empId;
public Employee() {
super();
System.out.println("Employee instantialted..");
}

}

***********************************************************************
package io_serialization;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;

public class Engineer extends Employee{
private static final long serialVersionUID = 1L;
int age;
String name;
String address;
transient int salary=0;
//Organization org=null;

public Engineer(int age, String name, String address,String orgName,int orgId) {
super();
this.age = age;
this.name = name;
this.address = address;
this.salary=22000;
empId=101;
//org=new Organization(orgId,orgName);
System.out.println("Engineer object instantiated_param-constructor");
}

public Engineer(Organization o) {
System.out.println("Engineer object instantiated_param-constructor_org");
System.out.println("OrgData: "+o.orgId+" | "+o.orgName);
}

public String toString(){
return "Emp: "+name+" | "+age+" | "+address+" |transientVar "+salary+" |empId "+empId;
}

Engineer() {
super();
System.out.println("Engineer object instantiated_def-constructor");
}

/*private void writeObject(ObjectOutputStream objOut)throws IOException{
objOut.defaultWriteObject();
objOut.writeInt(salary);
}

private void readObject (ObjectInputStream objIn)throws IOException, ClassNotFoundException{
objIn.defaultReadObject();
salary=objIn.readInt();
}*/

public Object writeReplace()throws ObjectStreamException{
Organization org=new Organization(102,"abcd");
return org;
}

/*public Object readResolve()throws ObjectStreamException{
return new Employee();
}*/
}
**************************************************************************************

package io_serialization;

import java.io.Serializable;

public class Organization implements Serializable {
private static final long serialVersionUID = 1L;
int orgId;
String orgName="India pvt.ltd.";
public Organization() {
super();
System.out.println("Org instantiated.._default");
}

public Organization(int orgId, String orgName) {
super();
this.orgId = orgId;
this.orgName = orgName;
System.out.println("Org instantiated.._param");

}

public String toString(){
return "OrgData: "+orgId+" | "+orgName;
}

public Object readResolve(){
return new Engineer(this);
}
}
**************************************************************************************
package io_serialization;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeObject {
public static void main(String[] args) {
ObjectOutputStream objOut=null;
try{
Engineer e=new Engineer(25,"abhinav","noida","BCDS",102);
System.out.println("Emp obj before serialization: "+e);
objOut=new ObjectOutputStream(new FileOutputStream("emp.txt"));
objOut.writeObject(e);
objOut.flush();
System.out.println("Emp object serialized..");
}catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(objOut!=null){
objOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
**************************************************************************************
package io_serialization;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeObject {
public static void main(String[] args) {
ObjectInputStream objIn=null;
try{
Engineer e=null;
objIn=new ObjectInputStream(new FileInputStream("emp.txt"));
e=(Engineer)objIn.readObject();
System.out.println("Deserialized emp obj: "+e);
}catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
if(objIn!=null){
try {
objIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
*********************************************************************************
OUTPUT SERIALIZATION>>>


Employee instantiated..
Engineer object instantiated_param-constructor
Emp obj before serialization: Emp: abhinav | 25 | noida |transientVar 22000 |empId 101
Org instantiated.._param
Emp object serialized..

OUTPUT DE-SERIALIZATION>>>


Employee instantiated..
Engineer object instantiated_param-constructor_org
OrgData: 102 | abcd
Deserialized emp obj: Emp: null | 0 | null |transientVar 0 |empId 0

Saturday, April 14, 2012

Does return type matters in case or overriding ???? Yes OR No?

Ques: Does return type matters in case or overriding ???? Yes OR No?
Ans: It matters ,but not in case of Inheritance

/**
* The Class NatureOfReturnTypeWhileOverriding.
*
* @author Abhinav kr.mishra
*/
public class NatureOfReturnTypeWhileOverriding {

/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {

Super superObj=new Super();
superObj.noReturn();
superObj.returnInt(12);
superObj.returnInteger();
superObj.returnNumber();
superObj.returnObject();
Sub subObj=new Sub();
subObj.noReturn();
subObj.returnInt(12);
subObj.returnInteger();
subObj.returnNumber();
subObj.returnObject();

}

}

class Super{

public Super() {
super();
System.out.println("Super instantiated..");
}

public void noReturn(){
System.out.println("super.noReturn");
}

public int returnInt(int x){
System.out.println("super.returnInt(..) : "+x);
return x;
}

public Integer returnInteger(){
System.out.println("super.returnInteger(..)");
return new Integer(1);
}

public Number returnNumber(){
System.out.println("super.returnNumber(..)");
return new Integer(1);
}

public Super returnObject(){
System.out.println("super.returnObject");
return new Super();
}

}

class Sub extends Super{

public Sub() {
super();
System.out.println("Sub instantiated..");
}


//this method is of no return type so we can not return any thing from this method.
public void noReturn(){
System.out.println("sub.noReturn");
}


/*
* This is also allowed,because primitive types can be returned as per Boxing rule provided my Java 5
*/
public Integer returnInteger(){
System.out.println("sub.returnInteger(..)");
return 1;
}

public int returnInt(int x){
System.out.println("sub.returnInt(..) : "+x);
return x;
}

/* This is not allowed.even 'int' and 'char' both are primitive type.
* public char returnInt(int x){
System.out.println("sub.returnInt(..)");
return x;
}*/

/*
* Return types during overriding does not matters only in this case,
* i.e when return type is subclass or superclass
*
*/
public Sub returnObject(){
System.out.println("sub.returnObject>> RETURN TYPE DOES NOT MATTERS IF INHERITENCE.");
return new Sub();
}

/*
*This is allowed because Integer is the Subclass of Number.
*
*/
public Integer returnNumber(){
System.out.println("sub.returnNumber(..)>> RETURN TYPE DOES NOT MATTERS IF INHERITENCE.");
return new Integer(1);

}

}

OUTPUT>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Super instantiated..
super.noReturn
super.returnInt(..) : 12
super.returnInteger(..)
super.returnNumber(..)
super.returnObject
Super instantiated..
Super instantiated..
Sub instantiated..
sub.noReturn
sub.returnInt(..) : 12
sub.returnInteger(..)
sub.returnNumber(..)>> RETURN TYPE DOES NOT MATTERS IF INHERITENCE.
sub.returnObject>> RETURN TYPE DOES NOT MATTERS IF INHERITENCE.
Super instantiated..
Sub instantiated..
***************************************************************************

Conclusion: "So we can say return type does not matters when it is in inheritance relation"

Tuesday, March 13, 2012

Override Super claass or interface Without Implements Or Extends


package oopsConcept;

public class OverrideSuperWithoutImplementsOrExtends {

public static void main(String[] args) {

MyClass myCls = new MyClass(){
//Overrided using anynomus class
public void doSomething() {
System.out.println("Doing something in the Super class modified ..");
}
};
myCls.doSomething();

MyInterface myintrface = new MyInterface(){
//Overrided using anynomus class
public void doSomething() {
System.out.println("Doing something in the Super class modified ..");
}
};
myintrface.doSomething();
}
}


interface MyInterface {
public void doSomething();
}

class MyClass{
public void doSomething(){
System.out.println("Doing something in the Super class..");
}
}


Sunday, February 26, 2012

Sample StrutsPrepareAndExecuteFilter - struts2 framework


package org.apache.struts2.dispatcher.ng.filter;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.ng.*;

// Referenced classes of package org.apache.struts2.dispatcher.ng.filter:
//            FilterHostConfig

public class StrutsPrepareAndExecuteFilter
    implements StrutsStatics, Filter
{

    private PrepareOperations prepare;
    private ExecuteOperations execute;

    public StrutsPrepareAndExecuteFilter()
    {
    }

    public void init(FilterConfig filterConfig)
        throws ServletException
    {
        InitOperations init = new InitOperations();
        FilterHostConfig config = new FilterHostConfig(filterConfig);
        init.initLogging(config);
        org.apache.struts2.dispatcher.Dispatcher dispatcher = init.initDispatcher(config);
        init.initStaticContentLoader(config, dispatcher);
        prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);
        execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
        init.cleanup();
        break MISSING_BLOCK_LABEL_91;
        Exception exception;
        exception;
        init.cleanup();
        throw exception;
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException
    {
        HttpServletRequest request;
        HttpServletResponse response;
        request = (HttpServletRequest)req;
        response = (HttpServletResponse)res;
        prepare.createActionContext(request, response);
        prepare.assignDispatcherToThread();
        prepare.setEncodingAndLocale(request, response);
        request = prepare.wrapRequest(request);
        org.apache.struts2.dispatcher.mapper.ActionMapping mapping = prepare.findActionMapping(request, response);
        if(mapping == null)
        {
            boolean handled = execute.executeStaticResourceRequest(request, response);
            if(!handled)
            {
                chain.doFilter(request, response);
            }
        } else
        {
            execute.executeAction(request, response, mapping);
        }
        prepare.cleanupRequest(request);
        break MISSING_BLOCK_LABEL_141;
        Exception exception;
        exception;
        prepare.cleanupRequest(request);
        throw exception;
    }

    public void destroy()
    {
        prepare.cleanupDispatcher();
    }
}