Wednesday, 13 July 2011

ResultSetExtractor in Spring


Create the entry in the database:
For this we will take flight database and flight entity as our pojo class.
See - Create flights in database and corresponding pojo class

Now using the ResultSetExtractor
First we will implement result set extractor
public class FlightResultSetExtractor implements ResultSetExtractor<List<Flight>> {

@Override
public Object extractData(ResultSet rs) throws SQLException {
List<Flight> flightList = new ArrayList<Flight>();
while(rs.next){
Flight flight = new Flight();
flight.setFlightNo(rs.getString(1));
flight.setCarrierName(rs.getString(2));
flightList.add(flight);
}
return list;
}
}

Now using the ResultSetExtractor
Initialize JdbcTemplate as jdbcTemplate first
public List<Flight> getAllTodaysFlight(){
String sql = "Get all flights where date=?";
Date today = getTodaysDate();
Object[] args = {date};
FlightResultSetExtractor extractor = new FlightResultSetExtractor();
return jdbcTemplate.query(src, args, extractor);
}

Wednesday, 6 July 2011

Eclipse : Creating and Sharing Launch Configurations

This happened again. I downloaded a Java product from sourceforge. It came with a .project, so it is easy enough to import it into the eclipse workspace. Now, comes the humdinger of the problem. How in the world should I launch the application. I can also see a tests package, how can I launch the tests?
Fortunately, eclipse solves this problem through launch configurations. If you are developing on eclipse there is no reason for not sharing the launch configurations along with the code. A launch configuration is a way to inform a fellow developer how to invoke the application. It is like providing a helping hand in during the initial stages - till he/she grows up and find how to launch the application, tests or whatever by themselves.

Temporary launch configurations

If you rightclick on a test case or a main class and used 'Run as...', eclipse creates a launch configuration and invokes the application for you. While developing an application (if you are like me) - you will accumulate a lot of launch configurations. These launch configurations are saved along with the workspace and not shared.

Creating a launch configuration

For creating a launch configuration start with a temporary launch configuration. Open the Run -> Run dialog... option from the eclipse menu, i.e. right click on the file Run As-> Run configuration:
Now select the run or launch script you want (by noting the program name )

  Change the launch configuration name. Use a name that includes atleast the project name and the type of launch it is. No one can understand what 'Main' or 'AllTests' stand for. It is easy to understand 'SampleApp - Main' or 'SampleApp - AllTests'. Here is H2Test, which says we are testing whether program can connect to H2 database.

  You can set the arguments for the VM as well as application from the (surprise!) Arguments tab.

 As far as possible parameterize the arguments. Do not ever use hard coded file names or directory names in a launch configuration that is shared. Eclipse has predefined variables 'file_prompt', 'folder_prompt' and 'string_prompt' for this purpose. When a launch configuration with such parameters is launched, Eclipse prompt the user to either select a file/folder or enter a string.
If your launch is dependent on a particular Java version (suppose you need atleast JDK 1.5 to work) - use the JRE tab to select the JRE. It is advisable to select a particular 'Execution environment' rather than an installed JRE.
The rest of the tabs are self explanatory. If you added any environment variables, remember to parameterize them wherever needed. Launch the configuration using the 'Run' option in the dialog and check everything works fine.

Sharing a launch configuration

If you want to share a launch configuration, you do it through the 'Run dialog'. For opening the run dialog use Run -> Run dialog... option from the eclipse menu. The sharing option is in the 'Common' tab of the run dialog.

 Select the 'Shared file' option. Select the project to which this launch configuration belongs. I suggest the launch configurations to be saved at the root of the project directory. You can also add the launch configuration to the favorites menu (either to Run or Debug). Just click on 'Apply' and the launch configuration is saved. From now onwards, anyone who imports your project can launch the application by just clicking on the launch configuration file and selecting Run as -> <launch name>.

Also if you want you can direct console output to some log file on the file system, under this common tab:
Now you can choose any option like workspace, filesystem or variable. Save the log file location.

Launch configuration best practices

  • Provide launch configurations for all modes of launch. For example, if your application can be launched in UI and command line mode, provide two launch configurations one for each.
  • Do not proliferate the project with temporary launch configurations. I have a separate project where I save all of my temporary launch configurations. This will be checked into the SCM, but not shared along with the project.
  • Provide a launch configuration for running all the tests (if exists).
  • Do not add optional launch configurations into the favorites. My suggestion is to add only the application and all tests into the favorite menu.
  • Parameterize the launch configurations using eclipse variables - folder_prompt, file_prompt and string_prompt.
  • Select an appropriate JRE using the JRE tab and an execution environment.
Finally, launch configurations are for fellow developers and not for end users. Keep it in mind when you create a configuration. Too much of hand-holding might not be needed.

Tuesday, 5 July 2011

Cascading Persistence in Hibernate

We have said, a number of times, that when an object is made persistent, that the objects it refers to are also made persistent. This was an oversimplification. In the mapping files for the classes, there is an attribute, cascade that lets us control how much, or how little, of a reference graph gets automatically persisted, deleted or updated. The values that it can be set to, and their meanings, are as follows:
  • none: no automatic action on the referenced object takes place.
  • save-update: automatically save or update the referenced object when the referencing object is saved or the transaction commits.
    delete: automatically delete the referenced object when delete() is called on the referencing object. Note that, if the referencing object is not deleted but merely removes its reference to the referenced object, then this option will not do anything and, potentially, a garbage (or orphan) object will be left in the database.
  • delete-orphan: automatically delete any object for whom the reference has been removed from the referencing object.
  • all: take the same actions as save-update and delete but not that of delete-orphan.
  • all-delete-orphan: take the same action as save-update, delete and delete-orphan.

Thursday, 30 June 2011

Books for CXF web service

Apache CXF web service Development

Do you use Apache CXF? If so, you might take an interest in "Apache CXF Web Service Development".

The book does a good job of covering CXF use cases, going beyond the usual trivial Jax-WS examples. It also covers Jax-RS (RESTful) web services, and covers each in enough detail that you're likely to find what you need when working with CXF.

Jax-WS has largely demystified basic web service development, so there's a great amount of content on the web that will show you how to quickly annotate a POJO to get a web service up and running. But what if you need to do contract-first (top down) development? Lightweight resources often conveniently bypass this more difficult trail, but this book does a good job of handling it. (This is no great accomplishment for a book on web service development, but it does set the tone for the types of things this book will show.)

It also covers restful web services. I'd say a Java developer either currently using or wanting to use Apache CXF. The book isn't a complete reference for CXF, but it does introduce all the important topics. Once introduced, there's enough content to either solve your problem or at least educate you enough to effectively research what remains.

This book can be found here.

Creating a web service using apache Axis 2

http://blog.sencide.com/2011/06/create-web-service-using-apache-axis2.html
http://www.ibm.com/developerworks/webservices/library/ws-devaxis2part1/index.html?ca=drs-

Wednesday, 29 June 2011

Writing method interceptors using Spring AOP

Spring is a great Java technology that has become a very popular application framework during the past few years. My intention is not to go through the whole concepts and architectural details of the framework, because that kind of information can be easily looked up starting at http://www.springframework.org. As the article title indicates, I intend to provide hands-on examples showing the minimal requirements to bundle certain Spring functionalities in your Java applications. So, because I will not go into the “what’s under the hood” approach unless absolutely necessary, most of the examples might require the knowledge of basic Spring concepts. Anyway, the basic idea is that you must RTFM before deciding if Spring is right for your application.
The first example is a short look at a simple method intercepting strategy. You can read all about this and the whole Spring AOP API here.The source code for this example can be found here. In the project directory run ant compile run to launch the application.
For the beginning let’s consider that we have the service MyService that that has a method doSomething() performing an operation which takes a long time to execute. Below you can see the (pretty dumb) code of this method.
public class MyService {
public void doSomething() {
for (int i = 1; i < 10000; i++) {
System.out.println("i=" + i);
}
}
}

In order to print out the performance statistics on the method call, we must first implement the interceptor that actually calculates the execution time for this method. To do this we need to implement the org.aopalliance.intercept.MethodInterceptor interface shipped with Spring. This is actually a callback providing access to the actual call of the methods of our service. The JavaDoc for this interface is here.

public class ServiceMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = methodInvocation.proceed();
long duration = System.currentTimeMillis() - startTime;
Method method = methodInvocation.getMethod();
String methodName = method.getDeclaringClass().getName()  
                                   + "." + method.getName();
System.out.println("Method '" + methodName  
                         + "' took " + duration + " milliseconds to run");
return null;
}
}

Next we need to proxy our service in order to obtain an instance whose methods are being intercepted by our ServiceMethodInterceptor. To achieve this, all it takes is a little magic in Spring’s bean configuration file, as you can see below.

<beans>
<bean id="myService" class="com.test.MyService">
</bean>

<bean id="interceptor" class="com.test.ServiceMethodInterceptor">
</bean>

<bean id="interceptedService" class="org.springframework
                      .aop.framework.ProxyFactoryBean">
<property name="target">
<ref bean="myService"/>
</property>
<property name="interceptorNames">
<list>
<value>interceptor</value>
</list>
</property>
</bean>
</beans>

The key in this XML snippet is Spring’s built-in class org.springframework.aop.framework.ProxyFactoryBean which provides the actual proxying of our service. In order to obtain the desired effect we must set the target and interceptorNames properties for this bean. The target property represents the name of the bean that we want to proxy, which in our case is the myService bean. The interceptorNames property holds a list of bean names that will be used as interceptors for the proxied bean. So, yes, you can define more than one interceptor for your bean.
As everything seems to be packed pretty nice, all we need to do now is to have our service instantiated using Spring and call itâs doSomething method.

public class Test {
public static void main(String[] args) {
ApplicationContext ctx =  
           new ClassPathXmlApplicationContext("com/test/applicationContext.xml");
MyService myService = (MyService)ctx.getBean("interceptedService");
myService.doSomething();
}
}

So we need to look up the interceptedService bean in order to get the proxied service, but if we choose to remove the performance monitor we can simply lookup the initial myService bean.
Normally, after the method doSomething has run, you should see, as the last output line, something like this:
Method 'com.test.MyService.doSomething' took 281 milliseconds to run

Except from the MethodInterceptor Spring also offers other method interception strategies. For example you can choose to handle a method execution right before or immediately after the actual call, or when an exception is thrown during the execution of your method. The reference documentation about these types of interceptors that Spring offers is available here.

Please note that basic performance monitoring can also be achieved by using Spring’s built-in PerformanceMonitorInterceptor. We used this logic just as a sample for method intercepting, but as your intuition might tell you, this is just one of the many things you can do with this feature of Spring. For example, if you need to implement a fine-grained security module, you might choose not to allow the method call to execute if the user does not have rights on the business method. So, basically, you will have to see for yourself how you can use this functionality in your application.
I hope you find this article useful.