Sunday, September 19, 2010

Generating Java POJO from XSD schema - JAXB and CASTOR

It is a contribution from Parthiban Rajasekaran

Generate Java Files using JAXB
1. Download latest JAXB Binary from https://jaxb.dev.java.net [latest as of now can be downloaded from https://jaxb.dev.java.net/2.2/JAXB2_20091104.jar] and execute this jar to get the JAXB package
2. Create JAXB_HOME with the jaxb extracted location, for example D:\Personal\Downloaded\Sun API\JAXB\jaxb-ri-20091104
3. Append %JAXB_HOME%\bin in the path system variable
4. Execute xjc command from the dtd or xsd location to generate java files
a. To create java from dtd – xjc -d -p -dtd
b. To create java from xsd – xjc -d -p

Hint: Convert DTD to XML - http://www.hitsw.com/xml_utilites/

Generate Java Files from XSD using Castor

set classpath=castor-1.3-codegen.jar;castor-1.3-xml.jar;castor-1.3-xml-schema.jar;castor-1.3-core.jar;commons-logging-1.1.1.jar;%CLASSPATH%;

java org.exolab.castor.builder.SourceGeneratorMain -i message.xsd -package com.bt.hqn.creditclient.buynet.integration.cbean






Wednesday, June 30, 2010

JPA @Transaction default properties

Lets examine JPA default Transaction attribute(@Transaction) and propagation

When using the @Transactional annotation by itself without any parameters, the propagation mode is set to REQUIRED, the read-only flag is set to false, the transaction isolation level is set to the database default (usually READ_COMMITTED), and the transaction will not roll back on a checked exception.


@Transactional(propagation=Propagation.REQUIRES_NEW)
The REQUIRES_NEW transaction attribute should be used only if the database action in the method being invoked needs to be saved to the database regardless of the outcome of the overlaying transaction. For example, suppose that every stock trade that was attempted had to be recorded in an audit database. This information needs to be persisted whether or not the trade failed because of validation errors, insufficient funds, or some other reason. If you did not use the REQUIRES_NEW attribute on the audit method, the audit record would be rolled back along with the attempted trade. Using the REQUIRES_NEW attribute guarantees that the audit data is saved regardless of the initial transaction's outcome. The main point here is always to use either the MANDATORY or REQUIRED attribute instead of REQUIRES_NEW unless you have a reason to use it for reasons similar those to the audit example.

Friday, May 21, 2010

Java XML Simple Read Example

To Read and extract the elements from the XML file first parse the XML file though the parser and create the Document
Document doc = builder.parse(str);

Once the document is availabe we can fetch the root and elements as follows
Node node = doc.getDocumentElement();
String root = node.getNodeName();

Example is given below

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class GetRootNode{
public static void main(String[] args) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter xml file name: ");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fact.newDocumentBuilder();
Document doc = builder.parse(str);
Node node = doc.getDocumentElement();
String root = node.getNodeName();
System.out.println("Root Node: " + root);
}
else{
System.out.println("File not found!");
}
}
catch(Exception e){}
}
}

Tuesday, May 18, 2010

Hibernate Mapping - inverse="true"

Hibernate Basic Mapping:
Just refreshing our old fried Hibernate Mapping :)

Set -> We know Set holds unique objects. Example for using Set is "Member" can hold N number of "Claim"
Member is the Parent and Claim the child. Here we can use One-To-Many relation with Set as Collection.

inverse="true" -> persistence will be taken care by the other end ie., in this case child
cascade="all" -> Example to explain cascade option.  when you are deleting an parent it will automatically delete the child.





    
    

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
session.flush();

Monday, May 17, 2010

JSF aj4 ajaxsingle=true - Examine

When ajaxsingle=true is used in the element then, while ajax submission only that particular element will be submitted instead of whole form.

Example when we have two drop down Country and state. Consider state is mandatory field and state is populated by a4jsupport of country drop down. If we are not making ajaxsingle=true in country drop down then required validation error will be thrown while selecting the country even before user selecting the state.

JSF bypassupdates - Examine

When we use bypassupdates we can able to skip the model update phase alone while all other 5 phases among 6 will be executed by JSF framework.

JSF Phases:
1. Restore View Phase
2. Apply Request Values Phase
3. Covert and Validations Phase
4. Update Model Values Phase
5. Invoke Application Phase
6. Render Response Phase

When bypassupdates is defined, then JSF will skip execution of Phase 4

JSF immediate=true - Examine

When setting immediate=true in JSF command button we can able to skip validation and model update phase. This is helpful while implementing the cancel button functionality

JSF Phases:
1. Restore View Phase
2. Apply Request Values Phase
3. Covert and Validations Phase
4. Update Model Values Phase
5. Invoke Application Phase
6. Render Response Phase

When immediate=true is defined then JSF will skip execution of Phase 3 and 4 ie., convertion, validation and model update wont happen.

Example:

Tuesday, April 27, 2010

JSF Page not submit issue

While using JSF developers may come across problem while submitting the page. Page may not be getting submitted. Following are finding for JSF not submission

1. Component in the jsf page may be seting as null. Check which component is null and fix it. Always initialize the variable in JSF backing bean.

2. Dropdown index value (SelectItem id) should be string and not integer!! So always while setting the List key value make sure it is string.

eg:
//Valid
int i = 0;
SelectItem item = new SelectItem(i+"", rvStatus.getDescription());


//Not Valid
int i = 0;
SelectItem item = new SelectItem(i, rvStatus.getDescription());

3. Rare cases - while displaying the multiple panel based on the render true or false in jsp may leads to break in submiting the button. This can be fixed by handling the render logic in backing bean by binding the panel.


There could be some more reason behind these please share it in the comment. Thanks

Friday, April 2, 2010

Solution for Connectionpool Timeout Exception

Exception: Cannot get a connection, pool error Timeout

Timeout error will be raised when the DB connection is unavailable from the pool due to the reason of not properly closed connection. So in web application connection need to be closed explicitly. Also following configuration in resource (Context.xml) changes will fix the issue also helps in debugging the code.

To configure a DBCP DataSource so that abandoned dB connections are removed and recycled add the following attribute to the Resource configuration for your DBCP DataSource:
            removeAbandoned="true"

When available db connections run low DBCP will recover and recycle any abandoned dB connections it finds. The default is false.
Use the removeAbandonedTimeout attribute to set the number of seconds a dB connection has been idle before it is considered abandoned.
            removeAbandonedTimeout="60"

The default timeout for removing abandoned connections is 300 seconds.
The logAbandoned attribute can be set to true if you want DBCP to log a stack trace of the code which abandoned the dB connection resources.
            logAbandoned="true"
The default is false.

Reference:
http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html

Thursday, March 25, 2010

Firebug - Improve your website performance

To improve the performance of our website we can use Firebug. It is Mozilla plugin which clearly says what is broken, what can be fixed to improve our website performance. It is pretty cool feature enabled for analyzing our website. It clearly says what elements in the page can be cached, broken links, hints to improve the performance by analyzing our website.


Try this tool you will like it :)


Steps to use it is available in google code base.
http://code.google.com/speed/page-speed/docs/using.html#Running

Wednesday, March 24, 2010

Solution for unique values for the 'webAppRootKey'

Exception while server startup - Choose unique values for the 'webAppRootKey' context-param in your web.xml files

Solution:

This exception is used to be raised when multiple application is  installed in the server. It is better practice to include  webAppRootKey parameter in your web.xml to uniquely identify the application.


Example:

 < context-param >

< param-name >webAppRootKey< /param-name >

< param-value > Unique ID < /param-value >

< / context-param >


Wednesday, March 17, 2010

RichFaces - Freeze the Datatable Header - ExtendedDataTable

RichFaces is a component library for easily integrating AJAX capabilities into business applications. Richfaces 3.3.1 release has provided a feature to freeze the datatable header. This feature enable user to see the header constantly while scrolling the navigation bar. This feature is feature is provided in the component called rich:extendedDataTable. By using extendedDataTable we can also able to sort and filter the data. 




Please refer official website for its demo - Live Demo Richfaces









Tuesday, March 16, 2010

WAS 7.0 - Workspace Migration Tool


Websphere Application Server 7.0 - Workspace Migration Tool

To migrate the workspace from existing WAS version to next version please use the Websphere workspace migration tool for initial steps. Migration tool will update some of the essential changes in classpath file.

For initial migration please follow the below steps:

1. Install WAS 7.0
2. Setup the datasource and JMS queue using admin console
3. Import the project from source control.
4. Websphere automatically launch workspace migration tool
5. Select the project and follow the steps. This leads to automatic update of .classpath to suits the WAS 7.0 configuration.
6. After this process upgrade the required jar files like Spring 2.5.4, JSF 1.2, Richfaces 3.3.1


WAS Migration from 6.1 to 7.0 - Steps

Websphere Application Server Migration from 6.1 to 7.0

I faced lot of issues while migrating our application from Application Server 6.1 to websphere Application Server 7.0. Our Application is build on Spring 2.5.4, JSF 1.1, Richfaces, JPA. I was finally able to fix the issues and make the application up and running in WAS 7.0.

Basically we need to do is Jar file need to be used appropriately to migrate from 6.1 to 7.0.
WAS 7.0 support JSF 1.2 in default. So if you are pointing to 1.1 jar please remove it.

Following are core steps taken to migrate
1. Use Websphere 7.0 runtime server configuration and JRE.
2. Use ojdbc6.jar instead of ojdbc14.jar
3. Remove JSF 1.2 from lib and use the default JSF 1.2 from WAS 7.0
4. Upgrade Fecelets for JSF 1.2 (facelets-1.1.15-jsf1.2)
5. Upgrade Richfaces to
        > richfaces-ui-3.3.1.GA.jar
        > richfaces-impl-3.3.1.GA.jar
        > richfaces-api-3.3.1.GA.jar
6. Add all the spring 2.5.6 dependent jars in your workspace including jar files  given in step 7
7. Add following Jar files
        > spring-agent.jar
        > spring-aspects.jar

If you are coming across below exception please follow above steps to resolve it. Basically issue is in jar file conflict in your working environment. Once dependency jars are fixed you are good go.


org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor': Initialization of bean failed; nested exception is java.lang.NullPointerException

WAS - Datasource connection failed

Solution For - Websphere Application Server - Datasource test connection operation failed
The test connection operation failed for data source opstar on server server1 at node LHX00CND84324PVNode02 with the following exception: java.sql.SQLException: invalid arguments in callDSRA0010E: SQL State = null, Error Code = 17,433. View JVM logs for further details.

Solution::
1. Go to websphere admin console
2. Under Security >> Secure administration, applications, and infrastructure >> JAAS >> J2C authentication data
3. Click New
4. Enter alias name
5. Enter Data base user id and password for connecting to database.
6. Click OK.

WAS - Thin drive ClassNotFoundException

Websphere Application Server  - Thin drive ClassNotFoundException - Solution

The test connection operation failed for data source opstar on server server1 at node LHX00CND84324PVNode02 with the following exception: java.lang.ClassNotFoundException: DSRA8000E: No jar or zip files found in /ojdbc14.jar

    Solution: While creating the JDBC Provider give complete class path for the thin drive (ojdbc14.jar) jar file explicitly.

Note that for WAS 6.1 we need to use ojdbc14.jar where as for WAS 7.0 we need to use ojdbc6.jar