Saturday, December 11, 2010

OptimisticLockingFailureException Attempt to update step execution id=1 with wrong version (n), where current version is n+1

My Spring batch application was intended to run in Single thread env and concurrent updates were not in its scope.But one of the Jobs ,kept encountering OptimisticLockingFailureException:Attempt to update step execution id=1 with wrong version (1), where current version is 2
On analyzing the Spring Logs found that this was generated by the MapStepExecutionDao.I am using MapJobRepositoryFactoryBean with ResourcelessTransactionManager which is NOT suppose to persist the data .
After testing with few scenarioes found that the exception was thrown only when the batch operation tries to insert duplicate records to the table with constraints.After removing the duplicate data the batch execution was successful.
In this case OptimisticLockingFailureException was misleading ,a more appropriate DB Exception would have be helpful identify the cause.

Friday, October 22, 2010

Constant Specific methods in Enumeration

Using Java 5 Enums,it is possible to define different behaviours for a method based on the value.This is known as Constant Specific Methods.The methods that requires different behavior to be declared as abstract and it should be overriden in each Enum Value.

public enum Game {
CHESS {
@Override
boolean isIndoor() {
return true;
}
},BADMINTON {
@Override
boolean isIndoor() {
return false;
}
},CHINESE_CHECKER {
@Override
boolean isIndoor() {
return true;
}
};

public abstract boolean isIndoor();
}

Thursday, July 22, 2010

Element 'bean' cannot have character [children], because the type's content type is element-only

Encountered this error yesterday and spend some time on figuring out what could be wrong with the config and later on comparision with the previous version found the bean definition had an additional '-' character.In the Spring context file ,if the bean definition needs any special characters ,it must be enclosed with the escape character else the forementioned exception is thrown.

Monday, July 19, 2010

Vaadin

Vaadin is framework for developing web applications in Java . The application can be deployed on any Java server (Tomcat, WebSphere,etc). Ajax and other web related stuff are automatically handled by the framework.Vaadin renders its UI using GWT but all the logic and data are on the server-side.For the Server Client communication Vaadin uses JSON since JSON has better performance when compared with XML.

Vaadin provides plugin for Eclipse.The documentation mentions this could be used in Eclipse version Galileo and Ganymede.But could not install the plugin with Ganymede .Tried with Galileo and it works like charm!

When trying to use csvalidation.jar for Client Side Validations ran into Run Time Exceptions later from the Vaadin team came to know it was due the Java version I was using.Upgrading to csvalidation-0.3.4.jar works for JRE 1.5 .More details on this on
http://vaadin.com/forum/-/message_boards/message/178918

The http://vaadin.com/tutorial/-/page/skeleton.html#skeleton.application is a good place to start a simple sample application.

Friday, July 2, 2010

Spring Web Services

Web services is the technology that integrates Web-based applications using the XML, SOAP, WSDL and UDDI open standards over the Internet . XML is used to define the data structure, SOAP is used to transfer the data, WSDL is used for describing the services available and UDDI is used for listing what services are available. Web services allow organizations to communicate data without the knowledge of each other's IT systems behind the firewall.

Web services do not provide the user with a GUI instead the services are shared through a programmatic interface across a network.

Web services allow different applications from different platforms to communicate with each other since all communication is in XML.

A detailed tutorial about implementing Spring Web Service which I found very useful is at
http://webcache.googleusercontent.com/search?q=cache:K3fszlCL9JQJ:www.lulu.com/content/content_download_redirect.php%3FmetaId%3D1090073+maven+dependecies+for+Spring+web+service&cd=2&hl=en&ct=clnk&gl=sg

Hibernate Criteria Sample Implementation

The Criteria interface in Hibernate is used to create and execute object-oriented queries.
The following are some commonly used criterion.
(i) To query based on simple search criteria like Employee Type Permanent and Confirmation Date less than Request Date
Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.eq( "empType", 'P' ),
Restrictions.and( Restrictions.isNotNull( "confirmationDate" ),
Restrictions.le( "confirmationDate",
requestDate ) )
};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
List result=criteria.list( );

(ii) To Retrieve values between

Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.between( "joiningDate", startDate,endDate )};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
List result=criteria.list( );

(iii) Using In Clause
Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.in( "empType",new Object[]{'P','C','R' )};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
List result=criteria.list( );

(iv) To find Record Count.
Criteria criteria = session.createCriteria( Emp.class );
criteria.setProjection(Projections.rowCount());
result=criteria.list( );
if ((null != result) && (!result.isEmpty())) {
Integer rowCount = (Integer) result.get(0);
}

(v) Returning 'n' columns from the Entity List based on Search Criteria
Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.in( "empType",new Object[]{'P','C','R' )};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
criteria.setProjection( Projections.projectionList( )
.add( Projections.property( fieldName1 )) .add( Projections.property( fieldName2 ) ) );
List result=criteria.list( );

(vi) Return Result based on descending order
Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.in( "empType",new Object[]{'P','C','R' )};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
crietrai.addOrder( Order.desc("empName") )
List result=criteria.list( );

Tuesday, May 18, 2010

Named Queries

NamedQuery feature in Hibernate allows Queries to added in Entity or Mapping Documents.The Queries can be of HQL or SQL type.NamedQuery structure has a name and query part.The name identifies the Query and should be unique in the context.If there are multiple named queries for an Entity,it can be specified within a NamedQueries construct.
@NamedQueries({

@NamedQuery(
name = "findEmpByAge",
query = "from emp e where e.age>?"
),

@NamedQuery(
name = "findEmpByRole",
query = "from emp e where e.role=?"
)
})

Adding additional fields in @Entity Class

In the Entity class, the persistent fields are mapped with @Column construct.But there could be some computed or other fields which are not in the table but are required in the Entity class.Adding these additional fields in the entity would give rise to Invalid Identifier Exception.To avoid this,these additional fields can be used with @Transient construct.When the fields are marked as Transient ,they are not associated with the Session Factory and their instances would be destroyed by the GC.

Friday, May 14, 2010

Cloud Computing

Cloud computing is a technology that uses the Internet and central remote servers to deliver hosted services over the Internet. It allows consumers and businesses to use applications without any installation on the computer .This technology enhances the efficiency of computing by centralizing storage, memory, processing and bandwidth. Typical examples of Cloud Services is Email Services like Yahoo,G Mail etc.

The distinct characteristics that differentiate Cloud Services from traditional hosting are
(1) It is sold on demand, the consumer pays based on the usage similar to any other utilities like water ,electricity.
(2) It is fully managed by the provider (the consumer needs nothing but a personal computer and Internet access).

The Cloud are of 3 types
-A public cloud that sells services to anyone on the Internet
-A private cloud is a proprietary network or data center that has hosted services to limited audience.
-A virtual private cloud that uses public cloud resources but is available for limited audience.

Cloud Computing Services are broadly divided into three categories:
Infrastructure-as-a-Service ,in which the Cloud Service provides virtual server instances with unique IP addresses and blocks of storage on demand. Customers use the provider's application program interface (API) to start, stop, access and configure their virtual servers and storage.

Platform-as-a-service ,is a set of software and product development tools hosted on the provider's infrastructure. Developers create applications on the provider's platform over the Internet.

Software-as-a-service ,where the vendor supplies the hardware infrastructure, the software product and interacts with the user through a front-end portal. Services can be anything from Web-based email to inventory control and database processing. Because the service provider hosts both the application and the data, the end user can avail the services from any computer.

Monday, March 15, 2010

Step [null] has neither a element nor a 'ref' attribute referencing a Tasklet

In the course of developing an Application with Spring Batch was once stumbled upon 'Step [null] has neither a element nor a 'ref' attribute referencing a Tasklet' exception.There was no documentation on the cause or work around for this Exception.Later identified the cause of the problem was the error in configuring the Job.In the Job Context the value for Job name was given by ref but it should have been by value.

Steps Execution in Spring Batch

In the real world scenario a batch task may need more than one step to complete the processing. The steps may or may not be independent of each other. Spring batch provides provision to define multiple steps for a Job.Each Step has a StepExecutionContext which provides the Information about the status of the step.The order of the steps execution can be made conditional

When a job consists of multiple steps ,it may be necessary to pass information between the steps. Each Step has a StepExecutionContext but this exists only for the span of the step. To make the data available to future Steps, it will have to be passed to the Job ExecutionContext after the step has finished. Spring Batch provides the ExecutionContextPromotionListener for this purpose. The listener must be configured with the keys related to the data in the ExecutionContext that must be promoted and must be registered with the Step.

The sample of Job with multiple steps

Spring Batch

Batch applications are used to process high volume business critical transactional data.

Spring Batch is the first Java based framework catered for batch process .For more information refer to http://static.springsource.org/spring-batch/reference/html-single/index.html#springBatchBackground

Building a batch application using Spring Batch Framework is relatively simple. The operation to be accomplished as a Batch task should be defined as a Job Bean. A typical batch program comprises of 3 logical steps which

1. reads a large number of records from a database, file, or queue
2. processes the data in some fashion, and
3. then writes back data in a modified form

The Spring batch framework provides interfaces to read(ItemReader),process(ItemProcessor) and write(ItemWriter) to achieve the same.

It provides better performance by using a chunk-oriented approach. For each Job a commit size can be provided,the Job would read and process the data and the actual writing into Database or File system is done only when the commit size is reached.

The following is sample of a simple Job Config with one step.


Thursday, February 18, 2010

Hibernate Sequence Generator

Hibernate generator element generates the primary key for new record. This is used in conjunction with the Id element. Hibernate provides about 11 types of generator .Among these the Sequence generator uses the Sequence from the Database and returns identifier value of type long,short or int.

To use the Sequence from the database,need to map the field for Id, and specify the Generation Type as Sequence. By default the sequence generator provides values that are incremented in counts of 50,this can be overridden by specifying the allocationSize

@Entity( name = "EmployeeEntity" )
@SequenceGenerator( name = "id_sequence", allocationSize = 1, sequenceName = "SEQ_EMP_ID" )
@Table( name = "T_EMP_MASTER" )
public class EmployeeEntity implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "id_sequence" )
@Column( name = "emp_id" )
private Long empId;
@Column(name="firstName")
private String firstName;
@Column(name="lastName")
private String lastName;
//Getters and Setters
}