SOA / Web Services / Java

A Technology Blog

Posts Tagged ‘java’

ClassNotFOundException? – Command to find the required jar

Posted by Vivek on February 2, 2015

It is irritating when one gets ClassNotFoundException. One can go and find the jar and add it to the classpath to resolve the problem. Jars can be searched on sites like However, sometimes jars are within the system and only thing needed to fix the problem is to set the classpath appropriately. Here is the unix command to find the jar:
$ find . -name “*.jar” -print -exec jar -tf ‘{}’ \; | grep -E “jar$|String\.class”


Posted in SOA | Tagged: | Leave a Comment »

Java based integration framework

Posted by Vivek on July 8, 2014

We all know the capabilities of an ESB to enable seamless integration among hetrogeneous applications. But is it always a feasible to choose an ESB where integration is not a major challenge and where applications use common protocols? The answer is NO. Most of the companies are looking for open source options which allows them build an integration architecture using simple configuration. Two of the most commonly used frameworks are:

1. Spring Integration

  • Based on popular Spring application framework
  • Dependency Injection / Inversion of Control
  • Configured within Spring Container
  • XML / Annotation based DSL
  • Supports Spring expression language


2. Apache Camel

  • Apache Software Foundation project
  • Custom Container – Camel Context
  • Can be instantiated directly from Java method
  • Integration with Spring, Guice, OSGI

Posted in SOA | Tagged: , , , , | Leave a Comment »

Why Contract First Approach?

Posted by Vivek on January 13, 2013

I have been asked a lot of questions in the past about why we should use the contract-first or WSDL first approach of developing web services. This article very well answers the question:

Posted in Java/J2EE, SOA, Web Services | Tagged: , , | 1 Comment »

Some Java Best Practices

Posted by Vivek on May 23, 2010

— Only one top level class should be defined per file.

— Visibility of variables, methods and class should be kept as minimum as possible.

— Import only required classes in your program.

— Do not use unused method, variables or classes. Make sure comments are used as per the java

coding standards. 

— Avoid using finalize method as garbage collection is not predictable.

— Every method should contain Java Doc and describe input and output parameters.
         * <Method description goes here>
         * @param parameter name description
         * @return return description
         * @throws exception decription

— Use proper indentation. Make use of your IDE (eclipse, jedeveloper etc) which provides built-in features. For ex. Ctrl + Shift + F when using eclipse can help reduce checkstyle errors and improve indentations.
— Declare only one varible per line. For ex:
instead of
private int x = 10, int y = 20, int z = 30;
private int x = 10;
private int y = 20;
private int z = 30;

— All variables should be initialized before they are accessed. Use lazy initialization if you

want to initialize a variable only when it is needed.

— Declare and Use local variables within a method. Do not reuse the variable.

— Declare static variables private and provide a public/protected method for other objects to

access it. For ex:
private static int myAge;

public static int getMyAge() {
   return myAge;

— Use paranthesis to indicate operator precedence.

— Do not use hardcoded values in the program. Use constants files instead.

— Use null pointer checks wherever applicable.

— keep methods short. If possible, it should contain 25 statements or less. Try not to exceed 80 characters when coding a line of code.

— Always use curly braces for blocks of code especially if-else.

— Nesting should not be more than 3 levels if possible.

— Boolean values should be implicit in an if statement. For ex:
instead of
if(myFlag == true){…}

— use values on left side during comparisons to avoid any null pointer exception. For ex:
instead of
if getMyFirstName() returns null in first expression, it will throw a NPE. This is avoided in

the second statement.

— Do not access a method through another method.For ex:
avoid this.getMyName().getMyFirstName();

— Use System.arraycopy( ) to copy an array.

— Always, set the size of collection objects. Use Set, List etc instead of HashSet, ArrayList etc.

— Class names must start with an Capital letter. Method and variable names should begin with lowercase. Exception classes must end with the word Exception. Use uppercase for all constant names and use underscore to seperate words (For ex: static final int MY_DATE_OF_BIRTH = 26;).

— A method should be declared abstract in a class which will not be instantiated. 

— Present exceptions to the user in a proper manner. Do not just catch and log exception, if

applicable. Do not use empty catch blocks or catch or throw the classes Throwable or Exception.
Use finally block for clean up activities and do not throw any exception from a finally block.
Try to classify exceptions as Business Exception and System Exception and deal accordingly.

— Avoid using multiple return statements in a method.

— Use synchronized method only if it is applicable. For example: Use StringBuilder if only one

thread is going to use it at a time instead of StringBuffer, which is synchronized.

— Avoid using StringTokenizer. Avoid methods like String.toUpperCase() and String.toLowercase( )

that copy the characters of the string.

— Use log4j or apache commons logging framework instead of System.out.print() statements.

— Logging at entry and exit methods must be at TRACE level.

— Use ThreadLocal to allow accessing states from a thread.

— Clone() method can be used to avoid invocation of constructors.

— Create objects early in the application and do not destroy until they are utilized completely.
— Avoid method calls from loops. Use inline statements even if it causes redundant code.

— Use short circuit operators instead of bit wise operators. For ex: && is better than &

— Use ? for an unknown object type. For ex:
instead of Collection<object> use Collection<?>

— Use annotations wherever applicable. For ex: @override to indicate that this method overrides a method, @SuppressWarnings to suppress warnings from compiler.

— Use caching if repeatedly accessing a constant piece of code or performing IO operation on a

constant file.

— Encourage use of Writing Junit test cases.

— Improve coverage of code. Use tools like EMMA, cobertura.

— Use checkstyle and PMD for improving layout of code.

Posted in Java/J2EE | Tagged: , , | Leave a Comment »

Access User-Defined SOAP Header Elements in Service

Posted by Vivek on February 13, 2010

There could always be a requirement that some data be sent only in SOAP Header. Usually SOAP Header contains data that is system specific and is dissimilar to the message payload that is contained in the SOAP Body. The information that a SOAP Header carries could be user-defined and generally used for tracking and logging. This data could be required by your service but is lost when a SOAP engine unmarshals the SOAP Request and provides just payload to the service i.e., applies the binding mechanism to convert an XML into a VO for the service to access elements using accessors and mutators.  To make this user-defined data available to the service, use of ThreadLocal can be advocated.

ThreadLocal allows you to have copy of variable per thread, which are subject to garbage collection when the thread goes away. Before the binding framework of SOAP engine performs any logic, a SOAP Handler can be placed to access the original SOAP request message and let the handler set the data in a threadlocal variable and use this data, which remains alive till the thread is active.

Here is the sample code which allows a bean injection and makes it available for setting values in the handler class.

<bean id=”myUserDefinedInfoBean”
<property name=”targetSource” ref=”threadLocalUserInfo” />

<bean id=”threadLocalUserInfo”
<property name=”targetBeanName” value=”userInfoVO” />
<bean id=”userInfoVO”
class=”mypackage.vo.UserInfoVO” scope=”prototype” />

UserInfoVO defines setters and getters for the user defined elements . The values can be set in the handler class and can be obtained anytime till the thread remains active.

For ex, the following code snippet will set the values in SOAP Handler

private UserInfoVO userInfoBean;


public UserInfoVO getUserInfoBean() {
return userInfoBean;

public void setUserInfoBean(UserInfoVO userInfoBean) {
this.userInfoBean = userInfoBean;




Once the above code is executed, value set in myVal can be accessed anywhere using getUserInfoBean()

Posted in SOA, Web Services | Tagged: , , , , | 2 Comments »

Some J2EE Best Practices

Posted by Vivek on January 12, 2009


–Use the MVC, or Model 2, architecture pattern to isolate and modularize screen logic, control logic, and business logic. A generic MVC implementation is a key component of the reference architecture as it provides a flexible and reusable foundation for rapid Web application development.

–A large session size can quickly degrade the scalability and performance of an application. It is recommended that the size of the session be kept fairly small. How small is small enough? Well, remember that the session size multiplied by a number of users gives an amount of memory that will be consumed on the Web tier. Taking into consideration that this amount is only a portion of the memory needed to run the application, you can get a rough idea of the number of concurrent users that will be supported by a single instance of a JSP container. Multiply this number by the number of JSP container instances in your production cluster, and this gives you a rough limit on the total number of concurrent users your application can support.

–The delete operation of a business object should also encapsulate the deletion of any aggregated objects in order to ensure data integrity.

–The create operation of a business object should also encapsulate the creation of any required aggregated objects such as a Customer and the corresponding Address. Other aggregated objects are created later in the parent lifecycle by corresponding business methods, such as the aggregated Transaction object that is created by the deposit method on an Account object.

–Do not use Entity Bean finder methods to iterate through a result set of business objects unless you can enforce either a read-only caching strategy or an aggressive-loading approach by the container. For a result set of n objects using lazy loading, this can actually cause (n + 1) database interactions. Use a JDBC wrapper component to run the database query and either hold the result set for iteration or return a set of value objects. This limits the operation to one database interaction.

–Perform some amount of load testing early on in your projects to determine if Entity Beans provide an acceptable level of performance in your application environment. As a general rule, you may want to consider using Java business objects instead of Entity Beans for extremely high throughput application components. If performance is acceptable, use Entity Beans to take advantage of a standard component model that provides services such as object persistence and transaction concurrency. Also, use Entity Beans if you want to distribute business objects directly to remote clients. When using either implementation model, consider planning for a migration path between the two. Application requirements or transaction volumes may change. Robust EJB 2.0 container implementations will likely provide a much increased boost from earlier versions; however, test in your environment before making a decision to commit to the Entity Bean model.

–For a lightweight optimistic locking solution, use an integer property with a standardized name on business objects as an optimistic lock column to handle transaction concurrency. The data access objects can generically increment the property’s value and include it in the WHERE clause on UPDATE and DELETE statements. If no rows are found from the SQL statement, an Optimistic Lock exception is thrown. Many J2EE containers and object-relational mapping vendors provide support to make implementing optimistic locking quite easy by allowing the developer to designate an optimistic locking column.

–It is a good practice always to use the getter and setter methods of a given property, even within other methods in that business object. This is the strictest form of encapsulation, in which only the getter and setter methods actually refer to the member variable. The member variables are declared as private to help enforce this concept, although use within the class itself requires discipline by the programmer. This technique can be beneficial in many ways. One example of when this comes in handy is the case in which a property does not have an assigned value. If you referred directly to the member variable, your code would get a NullPointerException in this case. However, use of the getter method can protect you from this condition by checking for this and initializing the value. This logic can then be implemented and encapsulated in one place, and other methods do not need to worry about this condition. This concept becomes even more powerful when the concept of lazy instantiation is used in getter methods for aggregated objects.

–Use of a standard interface for business objects is a good technique that can ensure consistency across business objects. In addition to making code more maintainable, this standard interface enables you to automate a number of business object functions and services because you can implement them generically, referring only to the Java BusinessObject interface.

–Use an error utility class to consistently and effectively manage business errors in your application

–Use exceptions whenever processing should halt immediately in a given method. Business errors should then be used wherever processing may continue in the case of an error occurring

–Map system-level exceptions to defined business errors that have more meaningful messages that can be presented to the users.

–Isolate the JDBC logic to execute a SQL statement in a common utility class. This prevents every application developer from having to write this common logic and ensures that all resources are closed properly.

–Whether you are using Entity Beans or regular Java business objects, use a factory method (Erich Gamma et al. 1995) abstraction to create and discover instances of business objects. This simplifies the client code and provides a hook for potential future optimizations such as caching EJB Home interfaces. You can create a BusinessObjectFactory utility class to do this. In the case of EJBs, the BusinessObjectFactory can use the EJB Home interface to look up the Entity Bean. In the case of Java business objects, you can instantiate and populate the proper business object within the BusinessObjectFactory.

–Managing a list of objects for data retrieval or for selective updates is a common operation in business applications. Consider the use of a utility class that consistently and effectively manages collections of objects for you. If Entity Beans are used as the business object implementation, you can also use the collection utility to get a list of value objects and have it instantiate corresponding Entity Beans for any transactional updates.

–Always use business objects for transactional updates to ensure data integrity and avoid redundant business logic validation code. Straight database queries can be used for read-only operations if they are more effective at traversing large table structures. However, this should be done only if you can mitigate the risk of having database names permeate throughout the application code.

–Use the Template Method pattern to implement common behaviors in the business object base class. A primary example of this is the save method, which can call a hook method to perform data validation, specific object validation, and any presave logic implemented in the subclass.

–Use a metadata format that allows your design models to be the original source of the metadata. Either build your metadata parser to read the XMI format or use a conversion utility to create your own XML format from XMI, which is generated by development tools from the design models.

–Cache frequently used data that is fairly static to speed application performance. Use a consistent, extensible cache mechanism that can be implemented either as a Stateless Session Bean or as a Java singleton class. If the cached data can be updated and the application needs the latest data, consider the use of a JMS solution for notifying caches across a cluster to refresh their data

–Implement service-based components as stateless Session Beans to take advantage of Enterprise Java services such as distribution and transaction management while maximizing scalability and performance

–Put the actual workflow and transaction logic of the service in a Java class. This implementation of the service can then be wrapped by the Session Bean to engage the container-managed services of transaction management, distribution, and so on. This allows services to be reused within other services more efficiently because you have the option of avoiding another EJB method invocation. Optionally, you can use a local interface of the Session Bean, which is slightly less efficient but avoids the RMI and serialization overhead.

–Service components with specific interfaces for different functions work well in many software architectures. Use a standard interface for service-based components in order to enable highly automated front-end components. Choose the generic data structure that best fits your needs for this interface. XML data is the most flexible choice for automated components. However, it performs the worst, especially for large amounts of data. For many cases, a collection of value objects that implement a standard value object interface works well. For simpler architectures that do not involve many hierarchies or collections of objects, an argument list containing name and value pairs can also work quite well.

–Consider the use of a standard interface for service components. This approach enables the reference architecture to automate the invocation of services to a large extent. Services can be generically invoked through their interface, and standard data structures allow for the automated creation of input data. A standard service data structure can be used to store arguments and object data as input as well as the corresponding output data and error information from the service.

–Wrap service components with a stateless Session Bean to manage the transaction and distribute the service. Use a common base class to standardize the service error handling and integration with EJB transaction management. Command pattern logic can be used to easily invoke services implemented as regular Java objects while subclasses using the Template Method pattern can be used in order to have specific EJB deployments of a service.

–If you are going to use straight database queries in your application for performance reasons, mitigate the development risk by externalizing the SQL from the application, isolating the JDBC code in a reusable utility to ensure that resources are properly managed, and mapping the database column names to properties as soon as possible to ease code maintenance.

–Build and use generic, reusable services whenever appropriate to realize the benefits of automation, rapid application development, and increased code quality and maintainability.

–Use a generic MVC, or Model 2, implementation as the foundation for the User Interaction Architecture. The Jakarta Struts project provides an excellent, readily available implementation that you can use for this purpose. This approach automates much of the front-end processing while providing a flexible and extensible foundation to meet all types of application requirements. This also adheres to a key design principle that permeates the reference architecture. This principle is to make the normal case as simple as possible through automation and configuration but give the application the ability to override automated, configurable elements when necessary for complex cases.

–Abstract the HTTP request as a user event to isolate the specific protocol being used from as much of the front-end logic as possible. The user event can then be used to drive the other key abstractions in the controller architecture. These include the action, the service, and the next Web page. By abstracting these key elements of user interaction, a good portion of the front-end processing can be automated and defined through metadata.

–Abstract physical URLs out of the application into metadata in order to enable automation, avoid broken links, and have more maintainable pages.

–Keep the session size fairly small, especially for applications that need to scale to large numbers of users.

–Minimize the amount of actual Java code in a JSP. Large amounts of Java code interspersed with HTML in a JSP can quickly become unreadable and unmanageable. Instead, use custom tags wherever possible to encapsulate presentation logic and integrate with the controller architecture. You can also move logic out to action classes that perform setup work for the page or JavaBeans that are referenced by the page. If you do have scriptlets within the JSP, try to use a few large scriptlets as opposed to interspersing Java code throughout the entire HTML content

–Use a JSP template mechanism to apply a common look and feel to your application Web pages. This approach makes it easy to globally change common aspects of pages and reduces the amount of duplicated code

–Use the Struts template tag library or an analogous mechanism to simplify the development and maintenance of the common aspects of application Web pages. A standard naming scheme can be used to distinguish between JSP components that implement template instances and page content.

–Use the same Template Method pattern within form beans to implement a validate template. This mechanism can reuse much of the property validation and handling logic implemented for use with the business objects. This prevents a duplication of code and effort.

–Consider the use of asynchronous processing to alleviate performance concerns in applications with semi-real-time updates, multiple external applications that can be invoked in parallel, or work that can be partitioned into segments. Use Message-Driven Beans and JMS to implement parallel processing in a J2EE container. Asynchronous processing can also be used to increase the perceived performance of an application.

–Make sure that your software components have easy to use APIs and are well documented. A little JavaDoc can go a long way toward helping someone understand an existing component and feel comfortable reusing it.

–For large, strategically important development projects, use a combination of industry and organizational reuse along with the creativity and innovation of the development team. Each of these sources brings unique value to the table. An approach that combines these aspects will help to alleviate the “not-invented-here” syndrome while at the same time providing a jumpstart to the development effort.

–Add refactoring as an explicit task in iterative software development. This helps not only to increase the overall quality of the software, but it often leads to more robust code that can be harvested into reusable assets.

–Choose a reference architecture and view it as a “reuse” architecture. Use it consistently throughout J2EE development projects. Incorporate standard interaction points for components with known interfaces. Use extensible, configurable components, such as the Jakarta Struts project, as a foundation. Take advantage of standard J2EE implementation models such as JSP custom tags and Session Bean EJB components.

Make sure you are abiding by all the design patterns also. Here are those:

Basic Patterns:
        Abstract Parent Class
        Private Methods
        Accessor Methods
        Constant Data Manager
         Immutable Object
Creational Patterns
        Factory Method
        Abstract Factory

Collectional Patterns

Structural Patterns
       Chain of Responsibility
       Virtual Proxy
       Counting Proxy
       Aggregate Enforcer
       Explicit Object Release
       Object Cache

Behavioral Patterns
       Null Object
       Template Method
       Object Authenticator
       Common Attribute Registry

Concurrency Patterns
       Critical Section
       Consistent Lock Order
       Guarded Suspension
       Read-Write Lock

Posted in Java/J2EE | Tagged: , , , | Comments Off on Some J2EE Best Practices


Posted by Vivek on July 27, 2008

Came across a very good post on Oracle forum. Worth mentioning as there are lot of people experiencing problems with oracle products.

Oracle BPEL + Oc4j + Jdeveloper = brain damage

We have been using Oracle BPEL and now upgraded to (oc4j, bpel and jdeveloper) when I came into contact with it.

Since then, we ran into loads of bugs that didn’t accelerate our development as Oracle promises, but slows us down by a factor of 3 at least.

Just to name a few issues:
– is not 100% stable in cluster mode. Deployment of processes fails randomly, they have to be redeployed several times. Before deployment, you have to undeploy old version to minimize risk of this problem.
– XSDs, XSLTs in BPEL process are sometimes not refreshed after deployment, resulting in reporting bugs that shouldnt exist.
– Oracle parser V2 cannot parse XML correctly, in certain cases when elements are separated by line feeds, it reports “null” elements.
– the whole oc4j uses old JAXB, leading to insurmountable problems if you try to use anything that requires newer version
– if you hope that you can fix problems with Oracle support, forget it, they will want an Oracle web conference with you for every bug. The process takes several days, and in most cases you will solve the issue before them.
– oc4j/opmn binding to multiple IP addresses is not functional, although according to manual it should work
– JDeveloper randomly deletes source code from other projects when deleting web service proxies
– JDeveloper can’t refactor java if the code is in SVN, it leads to corrupt project
– JDeveloper cant delete web service proxies correctly, it leaves old files on disk
– JDeveloper sometimes cant import java code, java sources dont appear in JDeveloper
– JDeveloper generated deserializing code for web service proxies is buggy, cant deserialize null Double, Integer etc. Sometimes it generates code that first uses obejct, and then checks for null …
– if JDeveloper is run from directory containing a space, it doesnt work correctly, unexpected bugs can occur. For example after adding email activity to BPEL project it becomes uncompilable. According to Oracle support this is ok, its mentioned in installation guide and is fully standard nowadays.
– JDeveloper BPEL designer is known to give errors like “Error: null” or ‘Reason: “” ‘ during compilation, meaning its impossible to fix probleme easily.
– in BPEL designer, xpath expression checking is not done, if something is wrong, project compiles but then leads to weird exceptions when deployed.
– when using switch activity, and string xpath in it like xp20:ends-with(), the content must be explicitly converted to string() or you get FOTY001 type error during runtime.
– when using transform activity in bpel designer, if you do not assign certain output nodes, they are deleted from the XML, so no further assign activities work on it.
– as we use custom bpel security module, we found out the BPEL runtime incorrectly passes information about domains when calling process from other domain from another process – leading to weird error that called process doesnt exist.
– when using transformations, bpel designer often says transformation is ok, but then in runtime you get FOTY001 type error, with no hint where the problem might be…
– correlation sets are not working under certain circumstances
– no refactoring in bpel designer, you cant even copy certain activities and paste them elsewhere. So you have to click, click, click everything again or copy in source code
– assign and transform activies are particularly touchy on whether there is element with some data, whether there is no element, or nil element. If the element is missing in input and you use assign copy on it, you are in trouble.
– icons in bpel designer are too big, if zooming is used, activity editing dialogs cannot be used
– when using JDeveloper generated web service proxies to invoke bpel processes, virtually only strings can be passed, if you pass anything else back, you will get various deserialization errors due to badly generated jdeveloper code
– if Oracle support on metalink cant replicate the problem, the problem “doesnt exist”.
– if you tell Oracle support you are going to use another product, they ask whether you still want to continue working on fixing reported bug. Obviously if you dont use oc4j, bugs in it dont need to be fixed.

I can’t imagine any serious company using JDeveloper and oc4j as these 2 are a deadly combination resulting in brain damage.

If you are considering buying BPEL or using Oc4j, think carefully, better take my warning seriously and look for other solutions until Oracle gets its problems sorted out.

Posted in jdeveloper, oracle | Tagged: , , , , , , | Leave a Comment »