Monday, February 8, 2010

How to Handle Session Expire in Ajax Call (Prototype Framework)

Steps:
1. Call is made to server using XMLHttpRequest either get or post method
2. Check string token like "session expired" or "sessionexpired" the result data. If so then it indicates that session is expired.
3. If session expired then redirect it to the Session Expire Page using following code:
var sessionExpiryURL="/global/sessionExpired.jspx";
window.location=sessionExpiryURL;


Sample Codes:

Note: Sample code uses prototype framework.

Script uses handling Session Expire:
var sessionExpiryURL="/global/sessionExpired.xhtml";

/*
    The following method checks if the session has expired or not
    Pre: Applicable for Ajax call only and the ajaxResponseText must pass the responseText from the AJax call
*/
function isSessionExpired_OnResponseText(ajaxResponseText){
    if (ajaxResponseText != null ){
        var lclAjaxResponseText = ajaxResponseText.toLowerCase();
        if (lclAjaxResponseText.indexOf("session expired") >=0 || lclAjaxResponseText.indexOf("sessionexpired") >=0 ){
            return true;
        }
    }
    return false;
}
/*
    The following method checks if the session expired and redirects to session expiry  page
    Pre: Applicable for Ajax call only and the ajaxResponseText must pass the responseText from the AJax call
*/
function handleSessionExpiry_OnResponseText(ajaxResponseText){
    if(isSessionExpired_OnResponseText(ajaxResponseText) == true){
            window.location=sessionExpiryURL;
    }
}

/*
    The following method checks if the session has expired or not
    Pre: Applicable for Ajax call only and the ajaxResponseText must pass the responseText from the AJax call
*/
function isSessionExpired(ajaxResponseObj){
    if (ajaxResponseObj!= null ){
            var contentText =ajaxResponseObj.responseText;
            return isSessionExpired_OnResponseText(contentText);
    }
   
}

/*
    The following method checks if the session expired and redirects to session expiry  page
    Pre: Applicable for Ajax call only and the ajaxResponseText must pass the responseText from the AJax call
   
*/
function handleSessionExpiry(ajaxResponseObj){
    if (ajaxResponseObj!= null ){
            var contentText =ajaxResponseObj.responseText;
            return handleSessionExpiry_OnResponseText(contentText);
    }
}

Script uses to post Ajax Call:

var jScript = Class.create();
    jScript .prototype =  {
    initialize: function()
    {
          // Initialization Stuff, It is called before calling any mothod of jScript
    },


/* funtion defination
@ URL - URL to be submitted to server
@ params-Associative array (Hash) to carry data from client to server
@ sourceObj- Ideally onchange of source object event; it posts the ajax request
@ targetObj- Ideally  targetObj is the placeholder for the response like populating some data into it.
/*
post: function(URL, params, sourceObj, targetObj) {
        var url = strURL ;
        var responseText = "";
        new Ajax.Request(strURL, {
                parameters: parameters,
                method:'post',
                onSuccess:function(transport) {
                    try {
// Algorithm uses to extract data from response and populate to the targetObj
                        }
                     }catch(e) {
                            if(isSessionExpired(transport)==true) {
                                handleSessionExpiry(transport);
                                return;
                            }
                            alert("System Error" );
                     }
                },
                 onFailure:function(transport) {
                    alert("An  error occurred");
                    alert("Error occurred: " + transport.responseText);    //Debug purpose only
                    //TODO handle errors
                 }
        });
    },


//AJAX Function
    loadStates: function (){
   var sourceObj = $('countryName'); // country name selected in dropdown
    var targetObj = $('stateNames'); // dropdown list box to  hold state names
    var parameters = new Hash();

    var strURL="../Country/getStates.xhtml"; // Servlet to provide state names
    parameters['countryName'] = sourceObj.value;
    parameters.set('ajaxParam', '1');
    this.post(strURL, parameters,  sourceObj , targetObj );
    }
};

jScript .Initializer = function() {
        jScript = new jScript ();
}

Event.observe(window, 'load', jScript .Initializer);

Tuesday, February 2, 2010

jQuery Autocomplete Field Sample Code (Using Plugins)

1. Auto complete plugin - http://www.pengoworks.com/workshop/jquery/autocomplete.htm
2. Javascript:
<script type="text/javascript">

/** AJAX - Call back
This function will submit the form when any item is selected from the autocompleted text field
@param li - item submited from the autocomplete field
*/

function findValue(li) {
if( li == null ){
return;
}

var selectedValue;
if( !!li.extra ){
selectedValue = li.extra[0];
}
else {
selectedValue = li.selectValue;
}
j$("studentNameQS").value=j$("studentName").value;
// Action class method name
j$("testForm").action = "showStudentDetailsById.xhtml";
j$("testForm").submit();

}

/** AJAX - Call back
A JavaScript function that will be called when an item is selected. The autocompleter will specify a single argument, being the LI element selected.
This LI element will have an attribute "extra" that contains an array of all cells that the backend specified.
@param li - item submited from the autocomplete field
*/
function selectItem(li) {
findValue(li);
}


/** AJAX - Call back
A JavaScript function that will be called when item are populated in the select box.
@param row - item in string format laying inbetween line separator.
*/

function displayItem (row) {
return row[0];
}

/** AJAX - Call back
A JavaScript funcion that can provide advanced markup for an item. For each row of results, this function will be called.
The returned value will be displayed inside an LI element in the results list.
Autocompleter will provide 3 parameters:
the results row,
the position of the row in the list of results,
and the number of items in the list of results.
@param row - item in string format laying inbetween line separator.
*/

function formatItem(row) {
return row[0];
}

j$(document).ready(function() {
// Register autocomplete plugin with the given textfield id i.e. #studentNameQS once the DOM is ready.
j$("#studentNameQS").autocomplete(
"findStudentDetails.xhtml", // URL
{
delay:10,
minChars:4,
matchSubset:1,
matchContains:1,
cacheLength:10,
maxItemsToShow:10,
formatItem:formatItem,
onItemSelect:selectItem,
onFindValue:findValue,
lineSeparator:'|',
cellSeparator: '~',
autoFill:true
}
);
});
</script>

3. Form:

<s:form name="ajaxStudentForm" id="ajaxStudentForm" action="showStudentDetailsById.xhtml">
<s:hidden name="studentNameQS"/>

</s:form>

<input id="studentName" type="text" maxlength="254" size="55"/>

4. Action Class

/**
* Method to get Student Name based on the Search criteria
* It is used for the Student Name Quick search functionality i.e. to show available names during typing
*
* @return String
* @throws Exception
*/
public String findStudentNames() throws Exception{

response.setContentType("text");
response.setHeader("Cache-Control", "no-cache");
// "searchQuery" is constructed by jquery-autocomplete.js - makeUrl()
// Should be verify in makeUrl(); what is used for the parameter
studentNameWildCard = request.getParameter("searchQuery");

// There is nothing supplied for RoleName
if (studentNameWildCard == null) {
response.getWriter().write("");
return null;
}

//Get the data from DB Based on the wild card chars

StringBuilder studentNameIds = new StringBuilder();

// Going to construct (ROLENAME~ID) like "|ABC~123|BCD~234|CDE~345|"
String[] staticNames = new String[ABC~123|BCD~234|CDE~345|]
// Put pipeline (|) as a line separator
studentNameIds.append("|");
studentNameIds.append("Ram");
// Put tild (~) as a cell separator
studentNameIds.append("~");
studentNameIds.append(1);
studentNameIds.append("|");
studentNameIds.append("Shiv");
// Put tild (~) as a cell separator
studentNameIds.append("~");
studentNameIds.append(2);

response.getWriter().write(studentNameIds.toString());
return null;
}

Wednesday, January 20, 2010

How to pass jsp:param in jsp:include and access from struts 2 tag

1. Include a jsp file in the first page by passing the parameters like "text" as follows:

first.jspx:
..
..
<jsp:include page="/WEB-INF/jsp/middle.jspx">
<jsp:param name="text" value="Good Morning!!!" />
</jsp:include>
..
..

2. middle.jspx
..
..
<jsp:include page="/WEB-INF/jsp/last.jspx">
<jsp:param name="text" value="${param.text}" />
</jsp:include>
..
..

3. last.jspx

..
..
<c:set var="text" value="${param.text}"/>

Your Passed Text is == <s:property value="%{#attr.text}"/>
..
..

Note:Unfortunately you can't use JSTL in Struts 2 tags anymore. The above solution is a work around by using JSTL to set the parameter into page scope.

Thursday, January 14, 2010

How to handle Clob type in iBatis

1. Create a type handler:

package com.demo.sqlmap.typehandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Date;

import com.demo.domain.BlobBean;
import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;


public class BlobTypeHandlerCallback implements TypeHandlerCallback {

private static final int BUFFER_SIZE = 3000;

/**
* @throws
* @see com.ibatis.sqlmap.client.extensions.TypeHandlerCallback#getResult(com.ibatis.sqlmap.client.extensions.ResultGetter)
*/
public Object getResult(ResultGetter getter) throws SQLException {
Blob blob = null;
String fileName = null;
InputStream inStream = null;
FileOutputStream outStream = null;
try {
blob = getter.getBlob();
File blobFile= File.createTempFile("mytmp", ".tmp", getTmpFileDirectory());
outStream = new FileOutputStream(blobFile);
inStream = blob.getBinaryStream();

int length = -1;
byte[] buffer = new byte[BUFFER_SIZE];

// Write to file
while ((length = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, length);
outStream.flush();
}
if (inStream != null)
inStream.close();
if (outStream != null)
outStream.close();

return new BlobBean(new FileInputStream(blobFile));
}

catch (Exception ex) {
throw new SQLException("Unable to export to file: " + fileName);
} finally {
inStream = null;
outStream = null;
}

}

/**
* @see com.ibatis.sqlmap.client.extensions.TypeHandlerCallback#setParameter(com.ibatis.sqlmap.client.extensions.ParameterSetter,
* java.lang.Object)
*/
public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
try {
if (parameter != null && parameter instanceof ChobBlob) {
InputStream is = ((BlobBean) parameter).getInputStream();
File file = ((BlobBean) parameter).getUploadedFile();
if (is != null)
setter.setBinaryStream(is, (int) file.length());
}
} catch (Exception ex) {
ex.printStackTrace();
throw new SQLException("Error in passing the inputstream " + ex.getMessage());
}
}

/**
* @see com.ibatis.sqlmap.client.extensions.TypeHandlerCallback#valueOf(java.lang.String)
*/
public Object valueOf(String s) {
return s;

}

/**
* Generate a random FileName
*/
public static synchronized final String constructFileName() {
Date date = new Date();
return "BLOB_T" + date.getTime() + "T-"+DateFormat.getTimeInstance().format(date).replace(":", "-")
+ Math.random();
}

/**
* Method to get tmp file Directory.
*
* @return
*/
protected File getTmpFileDirectory() {
String tempDir = System.getProperty("java.io.tmpdir");
File fileUploadDir = new File(tempDir + File.separator + "fileupload");
if (!fileUploadDir.exists())
fileUploadDir.mkdirs();
return fileUploadDir;
}

}

2. Create a Blob Class to hold the binary data:
package com.demo.domain;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class BlobBean{

/** Reference to the underlying Input stream. */
private InputStream inputStream;

/** Reference to the file */
private File uploadedFile;

/**
* @return the uploadedFile
*/
public File getUploadedFile() {
return uploadedFile;
}

/**
* @param uploadedFile
* the uploadedFile to set
*/
public void setUploadedFile(File uploadedFile) {
this.uploadedFile = uploadedFile;
}

/** No Args Constructor. */
public BlobBean() {

}

/**
* Constructor.
*
* @param inputStream
*/
public BlobBean(InputStream inputStream) {
this.inputStream = inputStream;
}

/**
* Constructor. Initialize inputStream instance variable from the given
* Path.
*
* @param inputStream
*/
public BlobBean(String path) throws IOException {
File f = new File(path);
initalize(f);

}

/**
* Constructor. Initialize inputStream instance variable from the given
* Path.
*
* @param inputStream
*/
public BlobBean(File file) throws IOException {
initalize(file);

}

/**
* Initlalize file to contents
*
* @param f
* @throws IOException
*/
private void initalize(File f) throws IOException {
this.uploadedFile = f;
InputStream is = null;
is = new FileInputStream(f);
this.inputStream = is;
}

/**
* @return the inputStream
*/
public final InputStream getInputStream() {
return inputStream;
}

/**
* @param inputStream
* the inputStream to set
*/
public final void setInputStream(final InputStream inputStream) {
this.inputStream = inputStream;
}
}

3. Create a Bean to hold the binary data:

package com.demo.domain;

import java.util.Date;

import com.demo.domain.BlobBean;

public class FileUpload {

private Long id = ApprovableExtendedBusinessObject.UNSAVED_VALUE;

private BlobBean binaryData;

private Date fileUploadDate;

/**
* @return the fileUploadDate
*/
public Date getFileUploadDate() {
return fileUploadDate;
}


/**
* @param fileUploadDate the fileUploadDate to set
*/
public void setFileUploadDate(Date fileUploadDate) {
this.fileUploadDate = fileUploadDate;
}

/**
* @return the id
*/
public Long getId() {
return id;
}

/**
* @param id
* the id to set
*/
public void setId(Long id) {
this.id = id;
}

/**
* @return the binaryData
*/
public BlobBean getBinaryData() {
return binaryData;
}

/**
* @param binaryData
* the binaryData to set
*/
public void setBinaryData(BlobBean binaryData) {
this.binaryData = binaryData;
}
}

4. Create a DAO implementation class to deal with database


package com.demo.fileupload.dao.impl;


import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.demo.domain.FileUpload;
import com.demo.fileupload.dao.FileUploadDao;

// Note FileUploadDao must be defined with the necessary methods

public class FileUploadDaoImpl extends SqlMapClientDaoSupport implements FileUploadDao {

public FileUpload download(Long id) throws PersistenceLayerException {
FileUpload fileUpload = (FileUpload) getSqlMapClientTemplate().queryForObject(
"commons.fileupload.download", id.longValue());
return fileUpload;

}

public Long upload(FileUpload fileUpload) throws PersistenceLayerException {
getSqlMapClientTemplate().insert("commons.fileupload.upload", fileUpload);
return fileUpload.getId();

}
}

5. Create a SQL-MAP file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="commons.fileupload">

<typeAlias alias="blobTypeHandlerCallback" type="com.demo.sqlmap.typehandler.BlobTypeHandlerCallback"/>

<resultMap class="com.demo.domain.FileUpload" id="FileUploadMap">
<result property="id" column="ID"/>
<result property="binaryData" column="FILECONTENT"
typeHandler="blobTypeHandlerCallback"/>
<result property="fileUploadDate" column="FILEUPLOADDATE"/>
</resultMap>

<insert id="upload" parameterClass="com.demo.domain.FileUpload">
<![CDATA[
insert into FILEUPLOAD (ID, FILECONTENT, FILEUPLOADDATE)
values(#id#, #binaryData,handler=blobTypeHandlerCallback#,sysdate)
]]>
</insert>

<select id="download" resultMap="FileUploadMap">
<![CDATA[
select ID, FILECONTENT, FILEUPLOADDATE
from FILEUPLOAD
where ID = #id#
]]>
</select>

</sqlMap>


6. Table Structure
Column Name ID Pk Null? Data Type

ID 1 1 N NUMBER (19)
FILECONTENT 2 Y BLOB
FILEUPLOADDATE3 Y TIMESTAMP(6)

Tuesday, December 15, 2009

How to configure Global/Default Interceptor in Struts 2

Global/Default interceptor means to me like the interceptor would be applied to the entire action classes may span accross mutiple packages.

Step 1: Create an interceptor
Step 2: Register the interceptor in interceptors tag.
Step 3: Create an interceptor stack having all the necessary references to the interceptors
Step 4: If there are multiple packages are involved then put the interceptor in the common package and
all other packages would extend it.

For Example:

<struts>
<package name="base-package" extends="struts-default">

<interceptors>
<!-- interceptor used to initialize resource used through out the application-->
<interceptor name="ResourceInit" class="com.test.ResourceInitInterceptor"/>

<!-- interceptor stack composes struts provided interceptors and custody related-->
<interceptor-stack name="base-default-stack">
<interceptor-ref name="ResourceInit"/>
<!-- "defaultStack" defined in struts in struts-default.xml-->
<interceptor-ref name="defaultStack"/>
</interceptor-stack>

</interceptors>

<!-- Default interceptor executed for the entire actions -->
<default-interceptor-ref name="base-default-stack"/>
</package>

<include file="/com/struts_config/struts_module_1.xml" />
<include file="/com/struts_config/struts_module_2.xml" />

</struts>

Note: struts_module_1 and struts_module_2 must extends "base-package"

Sunday, December 13, 2009

XA-DataSource and Non-XA Datasource in Global Transaction

Datasource - XA datasource is a data source that can participate in an XA global transaction.

Non-XA Datasource - Non-XA datasource generally can't participate in a global transaction.

An XA transaction, in the most general terms, is a "global transaction" that may span multiple resources. A non-XA transaction always involves just one resource.

An XA transaction involves a coordinating transaction manager, with one or more databases (or other resources, like JMS) all involved in a single global transaction. Non-XA transactions have no transaction coordinator, and a single resource is doing all its transaction work itself (this is sometimes called local transactions).

When the implementation code surrounded/enclosed by the global (XA) transaction then the entire code must be treated as unit irrespective of number of datasource(s) are involved in the unit. Therefore when you say "commit", the results are committed across all of the resources and when you say "rollback", _everything_ is rolled back across all resources (XA-Enabled Datasource).

If there are non-xa enabled datasource surrounded by global transaction (XA transaction) then it does not participate in the transaction therefore operation associated to the non-xa datasource has to be committed or rollback manually. As
J2EE Specification says that transaction can not be nested here there must not be opened separate transaction for non-xa datasource inside the global transaction. Non-XA datasource is a local datasource which can be commit/rollback without using any transaction boundary for it.

How to configure Global Transaction using Spring AOP:

Add the following configuration in the applicationContext.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<bean id="txManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName" value="javax.transaction.TransactionManager" />
</bean>


<!-- the transactional advice -->
<tx:advice id="defaultTxAdvice" transaction-manager="txManager">
<!--the transactional semantics...-->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true" />
<!-- other methods use the default transaction settings -->
<tx:method name="*" rollback-for="List Checked Business Exception separated by comma" />
</tx:attributes>
</tx:advice>

<aop:config>
<aop:pointcut id="com.test.operations"
expression="execution(* com.test.service.ServiceImpl.*(..))" />
<aop:advisor advice-ref="defaultTxAdvice" pointcut-ref="com.test.operations" />
</aop:config>

</beans>

Note: If applicaton server Transaction manager specific selected then just change JtaTransactionManager to their respective classes for example for weblogic it's "org.springframework.transaction.jta.WeblogicJtaTransactionManager"

Special configuration for JTA having more that 30 Seconds timeout:
i. Set Timeout to 180 seconds (if plans ) during DataSource Configuration
ii. Goto JTA > Set 180 seconds timeout and restart the app server to be effective.

Friday, September 25, 2009

Notes About Inner Class - Core Java

1. Innerclass nested with other class i.e. enclosing class. They are four types:
i. Static
ii. Member class
iii. Local class
iv. Anonymous Class

N.B - Inner class is a member of enclosing class like method or field.

2. Static Member Class/Interface:
i. Static class is a static member of class like static method/field.
ii. Interfaces can be defined as static member class.
iii. A static member class is not associated with any instance of the containing class (i.e., there is no this object).
iv. A static member class has access to all static members of its containing class, including private members. The reverse is true as well: the methods of the containing class have access to all members of a static member class, including the private members. A static member class even has access to all the members of any other static member classes, including the private members of those classes.
v. A static member class cannot have the same name as any of its enclosing classes. In addition, static member classes and interfaces can be defined only within top-level classes and other static member classes and interfaces.

5. Member Class

i.Member class is a member (instance) of the enclosing class and has access to any and all methods or variables of enclosing one and even the parent's this reference.
ii. A member class cannot have the same name as any containing class or package.
iii. Member classes cannot contain any static fields, methods, or classes (with the exception of constant fields declared both static and final). The reason of it as static fields, methods, and classes are top-level constructs not associated with any particular object, while every member class is associated with an instance of its enclosing class. Defining a static top-level member within a non-top-level member
class simply promotes confusion and bad programming style, so you are required to define all static members within a top-level or static member class or interface.
iv. Interfaces cannot be defined as member classes. An interface cannot be instantiated, so there is no object to associate with an instance of the enclosing class. If you declare an interface as a member of a class, the interface is implicitly static, making it a static member class.
v. To access the this reference of the containing class use classname.this

6. Local classes are declared within a block of code and are visible only within that block, just as any other method variable.

7. An anonymous class is a local class that has no name.

8. Advantages of inner classes can be an object-oriented advantage, an organizational advantage, and a call-back advantage.

i. Lets prove the above three advantages:

Object-Oriented
---------------
Let's look at the member class. Since its instance is a member of its parent instance, it has access to every member and method in the parent. At first glance, this might not seem like much; we already have that sort of access from within a method in the parent class. However, the member class allows us to take logic out of the parent and objectify it.

Organizational
--------------

Inner classes allow us to further organize our package structure through the use of namespaces. Instead of dumping everything in a flat package, classes can be further nested within classes. Explicitly, without inner classes, we were limited to the following hierarchy structure

Callback
--------

Inner member classes and anonymous classes both provide a convenient method for defining callbacks. The most obvious example relates to GUI code.

As with anything else, you have to take the good with the bad. Inner classes have their disadvantages. From a maintenance point of view, inexperienced Java developers may find the inner class difficult to understand. The use of inner classes will also increase the total number of classes in your code. Moreover, from a development point of view, most Java tools come up a bit short on their support of inner classes.

Ref: http://docstore.mik.ua/orelly/java-ent/jnut/ch03_10.htm

Notes about Inheritance - CoreJava

1. All the classes implecitly extends from Object class as it defines and implements common behaviour to the all classes.
2. You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
3. You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
4. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
5. You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. Remember Constructors are not inheritable.
6. private member is accesible from the subclass indirectly. i.e. superclass is having public/protected method which access the private variables in generally its setter/getter method.
7. Remember a nested class has access to private members i.e. field/method of its enclosing class. Seems to be violated the encapsulation principles. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
8. Do the casting after checking with instanceof operator.

9. Method overriding (hiding)

The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type. Remember the access specifier has to be same or widen/higher scope not lesser if so compile time error.

It is recommended that use @override, as it instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error.

Another point to remember that the distinction between hiding (static) and overriding (instance) has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass.

************************Summary*********************************
------------------------| Super Instance Method -----| Super Static Method
------------------------|-----------------------------|-----------------------------
Sub Instance Method ----| Overrides ------------------| compile-time error
------------------------|-----------------------------|-----------------------------
Subclass Static Method -| compile-time error ---------| Hides


Remember Static method calls on type whereas instance method calls on instance.

10. Java does not support (i.e. intensinally eliminated to make simple) multiple inheritance implementation (i.e. class). There is a well known problem in multiple inheritance i.e. diamond problem. like consider the following example

Animal class is having method called talk().

Two classes i.e. Frog and Dinosaur each extends (error in java) Animal and implements talk().

Another class Frogosaur extends both Dinosaur and Frog and trying to call talk on type Animal. Here is the problem like ambiguity arises.

11. Interfaces give you more polymorphism than singly inherited families of classes, because with interfaces you don't have to make everything fit into one family of classes

12. Advantage of composition over inheritance (composition is quite better one to go with if it fits for the requirement)

i. It's easier to change classes involved in a composition relationship than it is to change classes involved in an inheritance relationship
ii. Composition allows you to delay the creation of back-end objects until (and unless) they're needed. It also allows you to change the back-end objects dynamically throughout the lifetime of the front-end object. With inheritance, you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass.
iii. It's easier to add new subclasses (inheritance) than it is to add new front-end classes (composition), because inheritance comes with polymorphism. If you have a bit of code that relies only on a superclass interface, that code can work with a new subclass without change. This isn't true of composition, unless you use composition with interfaces.

13. Remember that inheritance refers to "is-a" relationship (permanent) therefore easy to understand. Whereas Composition refers to "has-a" relationship and gives more flexibility.

14. Interface provides great extend for polymerphism

Wednesday, June 10, 2009

Java Performance Tunning - Compiled




Core Java:

1. StringBuilder is better than StringBuffer, though both are usually better than using string concatenation to build strings (when performing extensive String manipulation, replacing + with StringBuilder.append is likely recommended)

2. Declare method arguments final if they are not modified in the method. In general declare all variables final if they are not modified after being initialized or set to some value.

3. Declare methods private and/or final whenever that makes sense.

4. Use static final when creating constants

5. Use zero-length arrays instead of null

6. HashMap has slightly better performance than LinkedHashMap

7. HashSet has slightly better performance than LinkedHashSet

8. Replace strings and other objects with integer constants. Compare these integers by identity.

9. Use primitive data types instead of objects as instance variables.

10. Overwrite compareTo() method for object comparision rather comparing in the loop. ( Implementing compareTo/hashCode
http://www.javapractices.com/topic/TopicAction.do?Id=10
http://www.javapractices.com/topic/TopicAction.do?Id=28 )

11. Logging the contents of a Collection is simple (JDK 1.5 onwards)

Arrays.toString(myArray);
Arrays.deepToString(myObjectArray); //recursive
Arrays.asList(myArray).toString();

12. To determine if two String objects match exactly, you should almost always use the equals method, and not the == operator

13.Follow naming convention for distinguishing between local variables, arguments, and fields strictly. (Code review would be very productivity)

14. Good example on ArrayList vs Linked List

14.1 Appending elements to the end of a list has a fixed averaged cost for both ArrayList and LinkedList. For ArrayList, appending typically involves setting an internal array location to the element reference, but occasionally results in the array being reallocated. For LinkedList, the cost is uniform and involves allocating an internal Entry object.

14.2 Inserting or deleting elements in the middle of an ArrayList implies that the rest of the list must be moved. Inserting or deleting elements in the middle of a LinkedList has fixed cost.

14.3 A LinkedList does not support efficient random access

14.4 An ArrayList has space overhead in the form of reserve capacity at the end of the list. A LinkedList has significant space overhead per element.

14.5 Sometimes a Map structure is a better choice than a List.

Get some more good stuff in the following URL: http://java.sun.com/developer/JDCTechTips/2002/tt0910.html
http://www.pankaj-k.net/archives/2004/06/arraylist_versu.html http://www.informit.com/guides/content.aspx?g=java&seqNum=95
http://www.javapractices.com/topic/TopicAction.do?Id=65

Database:

1. Stay away from the database as much as possible.

2. Cache as much as feasible - an in-memory cache is better than an on-disk one, which in turn is better than a remote or a relational database.

3. Caching coarse-grained objects is better than caching fine-grained ones.


Project Health:

1. Load testing can provide the basis for: Comparing varying architectural approaches; Performance tuning; Capacity planning. (TBS)

2. Initially you should identify the probable performance and scalability based on the requirements. You should be asking about: numbers of users/components; component interactions; throughput and transaction rates; performance requirements. (TBS)

3.Performance measurements should be from presentation start to presentation completion, i.e. user clicks button (start) and information is displayed (completion). (TBS)

4. Select performance benchmarks and use them to quantify the scalability and determine performance targets and future performance improvements or degradations. Include all user types such as "information-gathering" visitors or "transaction" visitors in your benchmarks.

5. Technical Problem - Different Source For Tooling, Build Solution, RAD Solution, Framework Lib, Server and more important No One owns the whole productivity Experience if project is developed using many open source project / lib.

Java Web Tech:

1. Excessive use of custom tags may create unnecessary processing overhead.

2. Use the include directive where possible, as this is a compile-time directive as it is faster than the include action

3. Logging is more important than the performance saved by not logging.

4. There is little performance penalty to using an MVC architecture.

5. To ensure good performance use experienced J2EE builders and use proven design patterns.


Thursday, May 28, 2009

Pointer To Spring Stuff





Wednesday, May 27, 2009

How to fill VARRAY/TABLETYPE object in iBatis



Sample:

Step 1: Create DEMO_TABLE_TYPE as the following structure:
create or replace TYPE DEMO_TABLE_TYPE AS OBJECT
(
id NUMBER, name NVARCHAR2(35)
);

Step 2: Write demoProcedure as the following structure:
demoProcedure(
demoTType
) IS
BEGIN
INSERT INTO DEMOTABLE( ID, NAME) VALUES ( demoTType.ID,demoTType.NAME); END demoProcudre;

Step 3: create a sql map id in sql-map-xxx.xml like as follows:

<procedure id="demoProc" parameterClass="map">
<![CDATA[{call
DECLARE
demoTType DEMO_TABLE_TYPE := DEMO_TABLE_TYPE();
idx BINARY_INTEGER := 1;
BEGIN
]]>
<iterate property="list">
<![CDATA[
demoTType .extend(1);
demoTType (idxLF) := DEMO_TABLE_TYPE(
#demoTType[].id:NUMERIC#,
#demoTType[].name:VARCHAR#
);
idx := idx + 1;
]]>
</iterate>
<![CDATA[
demoProcedure(
demoTType
);
END}
]]>
</procedure>

Generic iBatis Error in Huge Volume Cetric Data

Error
com.ibatis.common.jdbc.exception.NestedSQLException:
--- The error occurred while applying a parameter map.
--- Check the BillIe.insertBillIssuingEntityOnEditCycle-InlineParameterMap.
--- Check the statement (update procedure failed).
--- Cause: java.sql.SQLException: ORA-06550: line 1, column 1:
PLS-00123: program too large (Diana nodes)

Solution:

Step 1: Create a store procedure which would insert/delete record from table

Step 2: Define some threshold value (Note: you must be ensure that threshold value won't encounter Diana nodes kind of problem) in java.

Step 3: Push records in batch mode

Pseudo Code Snippet


getSqlMapClient().startTransaction()
getSqlMapClient().startBatch()

//Check out how many records are there in the modelMap or List

totalRecord = modelList.size

toIndex = modelList.size

fromIndex =0

numberOfLoops = new Double(Math.ceil(totalRecord / THRESHOLD_VALUE)).intValue()

if(THRESHOLD_VALUE <= toIndex){
toIndex = new Double(THRESHOLD_VALUE).intValue()
}

for(int i = 0; i <>

modelSubList = modelList.subList(fromIndex , toIndex)

getSqlMapClient().insert("sql-map-id", modelSubList )

modelList.subList(fromIndex, toIndex).clear()

if(modelList.size() < THRESHOLD_VALUE){
toIndex = modelList.size();
}

}

getSqlMapClient().executeBatch()
getSqlMapClient().commitTransaction()

Quotation



  • FAIL FORWARD - FAILURE IS THE ONLY OPPORTUNITY TO BEGIN AGAIN MORE INTELLIGENTLY.



How to use Lucene Search in Struts 2.0

In Progress...