Saturday, May 12, 2012

Sending Stream To HttpResponse in struts2 instead of Writing response using getWriter().write(response).

Action Class which generates response:::


package com.action;

import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

import com.bean.AuthBean;
import com.serviceImpl.ServiceAware;
import com.utility.Utilities;


/**
 * The Class HomeAction.
 */
public class HomeAction extends Utilities{

/**
* Instantiates a new home action.
*/
public HomeAction(){
super();
logger.info("HomeAction instantiated...");
String users = "abhinav@gmail.com|" +
"bhawna@gmail.com|" +
"chikku@gmail.com|" +
"rashmi@gmail.com|" +
"vinay@gmail.com|" +
"kunal@gmail.com|" +
"rahul@gmail.com|" +
"abhishek@gmail.com|" +
"raju@gmail.com|" +
"mamu@gmail.com|" +
"dadu@gmail.com|" +
"baby@gmail.com|" +
"shikhu@gmail.com|" +
"pinku@gmail.com|" +
"sonu@gmail.com";
userList = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(users, "|");

while (st.hasMoreTokens()) {
userList.add(st.nextToken().trim());
}
Collections.sort(userList);
userMap.put("a",1);
userMap.put("c",2);
userMap.put("b",4);
userMap.put("d",3);
}

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/** The user. */
private AuthBean authBean;

/** The service aware. */
private ServiceAware service;

/** The input stream. */
private InputStream inputStream;

/** The list. */
private List<String> userList;


/**
* Gets the user list.
*
* @return the user list
*/
public List<String> getUserList() {
return userList;
}

/**
* Sets the user list.
*
* @param userList the new user list
*/
public void setUserList(List<String> userList) {
this.userList = userList;
}

/**
* Gets the input stream.
*
* @return the input stream
*/
public InputStream getInputStream() {
return inputStream;
}

/**
* Sets the input stream.
*
* @param inputStream the new input stream
*/
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}

/**
* Gets the service.
*
* @return the service
*/
public ServiceAware getService() {
return service;
}

/**
* Sets the service.
*
* @param service the new service
*/
public void setService(ServiceAware service) {
this.service = service;
}

/**
* Gets the auth bean.
*
* @return the auth bean
*/
public AuthBean getAuthBean() {
return authBean;
}

/**
* Sets the auth bean.
*
* @param authBean the new auth bean
*/
public void setAuthBean(AuthBean authBean) {
this.authBean = authBean;
}

/** The user map. */
private Map<Object, Object> userMap=new HashMap<Object, Object>();

/** The m. */
private TreeMap<Object, Object> m;

/**
* Gets the m.
*
* @return the m
*/
public TreeMap<Object, Object> getM() {
return m;
}

/**
* Sets the m.
*
* @param m the m
*/
public void setM(TreeMap<Object, Object> m) {
this.m = m;
}

/**
* Gets the user map.
*
* @return the user map
*/
public Map<Object, Object> getUserMap() {
return userMap;
}

/**
* Sets the user map.
*
* @param userMap the user map
*/
public void  setUserMap(Map<Object, Object> userMap) {
this.userMap = userMap;
}

/**
* Home page.
*
* @return the string
*/
public String homePage(){
return SUCCESS;
}

/**
* Gets the user profile .
*
* @return the user profile action
* @throws Exception the exception
*/
public String getUserProfileAction()throws Exception{
Map<String, Object> response=null;
String responseStr="";
String userName=getSession().get("username").toString();
response = getService().getUserMgmtService().getUserProfile(userName);
responseStr=response.get("username").toString()+"|"+response.get("firstname").toString()+"|"+response.get("lastname").toString()+"|"+response.get("emailid")+"|"+response.get("role");
getAuthBean().setResponse(responseStr);
getSession().putAll(response);
inputStream = new StringBufferInputStream(responseStr);
inputStream.close();
return SUCCESS;
}

/**
* Update user profile action.
*
* @return the string
* @throws Exception the exception
*/
public String updateUserProfileAction()throws Exception{
String response="";
response = getService().getUserMgmtService().updateUser(getAuthBean().getUserName(),
getAuthBean().getFirstName(),
getAuthBean().getLastName(),
getAuthBean().getEmailId(),
getAuthBean().getRole()
);
getAuthBean().setResponse(response);
inputStream = new StringBufferInputStream(response);
inputStream.close();
return SUCCESS;
}

/**
* Change password action.
*
* @return the string
* @throws Exception the exception
*/
public String changePasswordAction()throws Exception{
String response="";
response = getService().getUserMgmtService().changePasword(getAuthBean().getUserName(),Utilities.getPassword(getAuthBean().getNewPassword()),
Utilities.getPassword(getAuthBean().getOldPassword()));
getAuthBean().setResponse(response);
inputStream = new StringBufferInputStream(response);
inputStream.close();
return SUCCESS;
}

/**
* Creates the user action.
*
* @return the string
* @throws Exception the exception
*/
public String createUserAction()throws Exception{
String response="";
response=getService().getUserMgmtService().createNewUser(
getAuthBean().getUserName(),
getAuthBean().getFirstName(),
getAuthBean().getLastName(),
getAuthBean().getEmailId(),
getAuthBean().getRole()
);
getAuthBean().setResponse(response);
inputStream = new StringBufferInputStream(response);
inputStream.close();
return SUCCESS;
}

/**
* Sort on key.
*
* @return the string
* @throws Exception the exception
*/
public String sortOnKey()throws Exception{
m= new TreeMap<Object, Object>();
m.putAll(userMap);
return SUCCESS;
}

/**
* Sort on value.
*
* @return the string
* @throws Exception the exception
*/
public String sortOnValue()throws Exception{
m= new TreeMap<Object, Object>(new HashMapValueComparator(userMap));
m.putAll(userMap);
return SUCCESS;
}
}


/**
 * The Class HashMapValueComparator.
 */
class HashMapValueComparator implements Comparator<Object>{

/** The map. */
Map<Object, Object> map;

/**
* Instantiates a new hash map value comparator.
*
* @param m the m
*/
public HashMapValueComparator(Map<Object, Object> m){
super();
this.map = m;
}

/**
* Instantiates a new hash map value comparator.
*/
public HashMapValueComparator() {
super();
}

/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object o1, Object o2) {
int retType;
Object v1=map.get(o1);
Object v2=map.get(o2);
if(v1.hashCode()>v2.hashCode()){
retType=1;
}else if(v1.hashCode()<v2.hashCode()){
retType=-1;
}else{
retType=0;
}
return retType;
}
}


###############################################################################
Struts.xml CONFIGURATION:::::::


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="userMgmt" extends="strutsSpringDemo">
<!-- USER MGMT ACTIONS AND MAPPINGS START-->
<action name="homeAction" class="com.action.HomeAction" method="homePage">
<result name="success" type="tiles">/homePage.tiles</result>
</action>
           

  <!-- getUserProfileAction sending >>>> Input stream -->

<action name="userProfile" class="com.action.HomeAction"
method="getUserProfileAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>


<action name="changePassword" class="com.action.HomeAction"
method="changePasswordAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
<action name="updateProfile" class="com.action.HomeAction"
method="updateUserProfileAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
<action name="createUser" class="com.action.HomeAction" method="createUserAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
<action name="sortOnKey" class="com.action.HomeAction" method="sortOnKey">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="execAndWait">
<param name="delay">50</param>
<param name="delaySleepInterval">150</param>
</interceptor-ref>
<result name="wait">jsp/waitProcess.jsp</result>
<result name="success" type="tiles">/homePage.tiles</result>
</action>
<action name="sortOnVal" class="com.action.HomeAction" method="sortOnValue">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="execAndWait">
<param name="delay">50</param>
<param name="delaySleepInterval">150</param>
</interceptor-ref>
<result name="wait">jsp/waitProcess.jsp</result>
<result name="success" type="tiles">/homePage.tiles</result>
</action>
<!-- USER MGMT ACTIONS AND MAPPINGS END-->
</package>
</struts>

Struts2.0 sample "struts.xml" configuration..


Main ::::::::::::::::::::::::::::::::::::::

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<!-- STRUTS CONSTANTS START -->
<!--
STRUTS CONSTANT FOR LOADING CONFIGURATIONS AND PROPERTIES DURING
DEVELOPMENT PHASE, WHICH IS BY DEFAULT TRUE.WE WILL MAKE IT FALSE IN
PRODUCTION ENVIRONMENT.
-->
<constant name="struts.devMode" value="false" />
<!--
STRUTS CONSTANT FOR LOADING APPLICATION LEVEL PROPERTIES,USED FOR
GLOBALIZATION & LOCALIZATION.
We can provide multiple application resource files using comma seperated.
-->
<constant name="struts.custom.i18n.resources" value="com.resources.ApplicationResources,com.resources.ApplicationResourcesException" />
<!--
STRUTS CONSTANT FOR MAKING DYNAMICMETHODINVOCATION PROPERTY OF
FRAMEWORK FALSE, BY DEFAULT IT IS TRUE.IT IS DONE FOR SECURITY
REASONS,SO THAT AN ACTION CAN NOT BE ACCESSED WITH WILDCARDS.
-->
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<!--
STRUTS CONSTANT FOR MENTIONING THAT STRUTS2 FRAMEWORK IS INTEGERATING
WITH SPRING 3
-->
<constant name="struts.objectFactory"
value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<!--
STRUTS CONSTANTS FOR ALLOWING STATIC METHODS TO BE ACCESSED USING OGNL
EXPRESSION DIRECTLY IN JSP. SYNTAX FOR ACCESSING A STATIC METHOD IS:
<s:property value="@com.utility.Utilities@getSessionCount()"/> I.E,
<s:property value="@CLASSNAME@STATIC-METHOD-NAME"/>
-->
<constant name="struts.ognl.allowStaticMethodAccess" value="true" />
<!-- STRUTS CONSTANTS END -->

<!--APPLICATION LEVEL DECLARATIONS START-->
<package name="strutsSpringDemo" extends="struts-default">
<result-types>
<result-type name="tiles"
class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<!-- INTERCEPTORS AND MAPPINGS START -->
<interceptors>
<interceptor name="sessionInterceptor" class="com.interceptor.SessionInterceptor" />
<interceptor name="appCommonInterceptor" class="com.interceptor.AppCommonInterceptor" />
<interceptor-stack name="sessionCheckStack">
   <interceptor-ref name="exception"/>
               <interceptor-ref name="alias"/>
               <interceptor-ref name="servletConfig"/>
       <!-- LOGGER INTERCEPTOR, GIVES THE INFORMATION OF EXECUTED ACTION -->
   <interceptor-ref name="logger"/>
   <!-- TIMER INTERCEPTOR, GIVES THE INFORMATION OF EXECUTED ACTION AND METHOD AND ITS EXECUTION TIME -->
   <interceptor-ref name="timer"/>
             
               <interceptor-ref name="sessionInterceptor"/>
               <interceptor-ref name="i18n"/>
               <interceptor-ref name="prepare"/>
               <interceptor-ref name="chain"/>
               <interceptor-ref name="debugging"/>
               <interceptor-ref name="profiling"/>
               <interceptor-ref name="scopedModelDriven"/>
               <interceptor-ref name="modelDriven"/>
               <interceptor-ref name="fileUpload"/>
               <interceptor-ref name="checkbox"/>
               <interceptor-ref name="staticParams"/>
               <interceptor-ref name="actionMappingParams"/>
               <interceptor-ref name="params">
                 <param name="excludeParams">dojo\..*,^struts\..*</param>
               </interceptor-ref>
               <interceptor-ref name="conversionError"/>
               <interceptor-ref name="validation">
                   <param name="excludeMethods">input,back,cancel,browse</param>
               </interceptor-ref>
               <interceptor-ref name="workflow">
                   <param name="excludeMethods">input,back,cancel,browse</param>
               </interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="sessionCheckStack" />
<default-action-ref name="homeAction" />
<!-- INTERCEPTORS AND MAPPINGS END-->
<!-- GLOBAL RESULTS AND MAPPINGS START-->
<global-results>
<result name="sessionExpired">/login.jsp?sess=expired</result>
<result name="login">/login.jsp</result>
<result name="Exception" type="chain">demoExceptionHandler</result>
<result name="securityError">/jsp/securityError.jsp</result>
</global-results>
<!-- GLOBAL RESULTS AND MAPPINGS END-->
<!-- GLOBAL EXCEPTIONS AND MAPPINGS START-->
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception"
result="Exception" />
</global-exception-mappings>
<!-- GLOBAL EXCEPTIONS ACTION -->
<action name="demoExceptionHandler" class="com.exception.GlobalException">
<result name="demoException">/jsp/error.jsp</result>
</action>
<!-- GLOBAL EXCEPTIONS AND MAPPINGS START-->
</package>
<!--APPLICATION LEVEL DECLARATIONS END-->

<!-- INCLUDING OTHER STRUTS CONFIG XMLs MODULE BASED -->
<include file="struts-auth.xml" />
<include file="struts-userMgmt.xml" />
<include file="struts-utility.xml" />
<!-- INCLUDING OTHER STRUTS CONFIG XMLs MODULE BASED -->
</struts>
##################################################################################

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="auth" extends="strutsSpringDemo">
<!-- AUTHENTICATION ACTIONS AND MAPPINGS START-->
<action name="loginAction" class="com.action.LoginAction"
method="doLogin">
<exception-mapping exception="java.lang.SecurityException"
result="securityError"></exception-mapping>
<result name="input">/login.jsp</result>
<result name="success" type="redirect">${redirectUrl}</result>
</action>
<action name="logOut" class="com.action.LogoutAction" method="logOut">
<result name="success">/login.jsp</result>
</action>
<!-- AUTHENTICATION ACTIONS AND MAPPINGS END-->
</package>
</struts>
##################################################################################

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="userMgmt" extends="strutsSpringDemo">
<!-- USER MGMT ACTIONS AND MAPPINGS START-->
<action name="homeAction" class="com.action.HomeAction" method="homePage">
<result name="success" type="tiles">/homePage.tiles</result>
</action>
<action name="userProfile" class="com.action.HomeAction"
method="getUserProfileAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
<action name="changePassword" class="com.action.HomeAction"
method="changePasswordAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
<action name="updateProfile" class="com.action.HomeAction"
method="updateUserProfileAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
<action name="createUser" class="com.action.HomeAction" method="createUserAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
<action name="sortOnKey" class="com.action.HomeAction" method="sortOnKey">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="execAndWait">
<param name="delay">50</param>
<param name="delaySleepInterval">150</param>
</interceptor-ref>
<result name="wait">jsp/waitProcess.jsp</result>
<result name="success" type="tiles">/homePage.tiles</result>
</action>
<action name="sortOnVal" class="com.action.HomeAction" method="sortOnValue">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="execAndWait">
<param name="delay">50</param>
<param name="delaySleepInterval">150</param>
</interceptor-ref>
<result name="wait">jsp/waitProcess.jsp</result>
<result name="success" type="tiles">/homePage.tiles</result>
</action>
<!-- USER MGMT ACTIONS AND MAPPINGS END-->
</package>
</struts>
##################################################################################
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="util" extends="strutsSpringDemo">
<!-- UTILITIES ACTIONS AND MAPPINGS START-->
<action name="uploadFile" class="com.action.FileUploaderAction"
method="uploadFile">
<result name="success" type="tiles">/fileUpload.tiles</result>
</action>
<action name="uploadImage" class="com.action.FileUploaderAction"
method="uploadImageFile">
<interceptor-ref name="sessionCheckStack"/>
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/bmp
                </param>
</interceptor-ref>
<result name="input" type="tiles">/fileUpload.tiles</result>
<result name="success" type="tiles">/fileUploadSuccess.tiles</result>
</action>
<!-- UTILITIES ACTIONS AND MAPPINGS END-->
</package>
</struts>
********************************************************************************

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"