Wednesday, March 24, 2010

Job Scheduling in Java

http://oreilly.com/lpt/a/4637
On some projects, you find you need to execute certain jobs and tasks at an exactly specified time or at regular time intervals. In this article we will see how Java developers can implement such a requirement using the standard Java Timer API, and then we will focus on Quartz, an open source library for those who need some extra features in their scheduling system.
Let's, for a start, go through few common use cases that will help you recognize situations when you could need this kind of behavior. Then we will see how to find the best solution according to your functional request.
Almost every business application has some reports and statistics that are needed by its users. You can hardly imagine such a system without these reports, because the common purpose for someone to invest in such a system is the ability to collect a large amount of data and see it in a manner that can help with further business planning. A problem that can exist in creating these reports is the large amount of data that needs to be processed, which would generally put a heavy load on the database system. This heavy load decreases overall application performance and affects users that only use the system for data collecting, making it practically useless while it's generating the reports. Also, if we think about being user-friendly, a report that takes ten minutes to generate is not an example of a good response time.
We will now focus on the type of reports that can be cached, meaning those that are not needed in real time. The good news is that most reports fall into this category -- statistics on some product sales in last June, or company income in January. For these cacheable reports, a simple solution is possible: schedule report creation for times when the system is idle, or at least when the load on the database system is minimal. Let's say that you are creating an application for a local book reseller that has many offices (all in the same time zone) and that you need to generate a (possibly large) report for weekly income. You could schedule this task of generating necessary data for a time when the system isn't being used, such as every Sunday at midnight, and cache it in the database. This way, no sale operators will notice any performance problem in your application and company management will have all necessary data in a moment.
A second example that I will mention here is sending all kinds of notifications to application users, such as account expirations. This could be done using date fields in the user's data row, and creating a thread to check users on that condition, but using a scheduler in this case is surely a more elegant solution, and better from the aspect of overall system architecture (and that's important, right?). In a complex system you would have a lot of these notifications, and could find that you need a scheduler-like behavior in many other cases, so building a specific solution for every case makes a system harder to change and maintain. Instead, you should use one API to handle all of your application scheduling. That is the topic of the rest of this article.

In-House Solution

To implement a basic scheduler in your Java application, you don't need any external library. As of J2SE 1.3, Java contains the java.util.Timer and java.util.TimerTask classes that can be used for this purpose. Let's first make a little example that will help us describe all of the possibilities of this API.
package net.nighttale.scheduling;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ReportGenerator extends TimerTask {

  public void run() {
    System.out.println("Generating report");
    //TODO generate report
  }

}

class MainApplication {

  public static void main(String[] args) {
    Timer timer  new Timer();
    Calendar date = Calendar.getInstance();
    date.set(
      Calendar.DAY_OF_WEEK,
      Calendar.SUNDAY
    );
    date.set(Calendar.HOUR, 0);
    date.set(Calendar.MINUTE, 0);
    date.set(Calendar.SECOND, 0);
    date.set(Calendar.MILLISECOND, 0);
    // Schedule to run every Sunday in midnight
    timer.schedule(
      new ReportGenerator(),
      date.getTime(),
      1000 * 60 * 60 * 24 * 7
    );
  }
}
All example code for this article can be downloaded from links at the end of the article.
The code above implements the example from the introduction, scheduling report generation for a time when the system is idle (in this case, Sunday at midnight).
First, we should implement a "worker" class that will actually do the scheduled job. In our example this is ReportGenerator. This class must extend from java.util.TimerTask, which implements java.lang.Runnable. All that you need to do is to override run() method with the report generation code.
Then, we schedule this object's execution using one of the Timer's scheduling methods. In this case, we use the schedule() method that accepts the date of the first execution and the period of subsequent executions in milliseconds (since we repeat this report generation every week).
As we use the scheduling features, we must be aware of the real-time guarantees that the scheduling API provides. Unfortunately, because of the nature of Java and its implementations on various platforms, thread scheduling implementations in various JVMs are inconsistent. Thus, the Timer cannot guarantee that our Task will be executed at exactly the specified moment. Our Tasks are implemented as Runnable objects and are put to sleep (with wait) for some time. Timer then wakes them up at a specified moment, but the exact moment of execution depends on the JVM's scheduling policy and how many threads are currently waiting for the processor. There are two common cases that can cause our tasks to be executed with a delay. First, a large number of threads might be waiting to be executed; second, a delay could be caused by garbage collection activity. All of these influences could be minimized using different techniques (such as running a scheduler within a different JVM or tuning some options for the garbage collector) but that is beyond the topic of this article.
In this new light, we can explain the existence of two different scheduling method groups in the Timer class: scheduling with fixed delay (schedule()) and scheduling with fixed rate (scheduleAtFixedRate()). When you are using methods from the first group, every delay in the task execution will be propagated to the subsequent task executions. In the latter case, all subsequent executions are scheduled according the time of the initial task execution, hopefully minimizing this delay. Which methods you use depends on which parameter is more important in your system.
One more thing is very important to say here: every Timer object starts a thread in the background. This behavior is not desirable in a managed environment, such as a J2EE application server, because these threads are not in the scope of the container.

Beyond the Ordinary

So far, we saw how we can schedule tasks in an application, and for simple requirements that is quite enough. But for more advanced users and complex requirements, a lot more features are needed to support fully useful scheduling. In such cases, there are two common solutions that one could choose. The first is to build your own scheduler with the desired functionality; the second is to locate a project that can fulfill your specific needs. The second solution is more appropriate in most cases, because you can save time and resources and won't have to duplicate someone else's effort.
This brings us to Quartz, an open source job-scheduling system with significant advantages over the simple Timer API.
The first advantage is persistence. If your jobs are "static," as in our introductory example, then maybe you don't need to persist jobs. But we often find tasks need to be "dynamically" triggered when a certain condition is met, and you have to be sure that those tasks won't be lost between system restarts (or crashes). Quartz offers both non-persistent and persistent jobs, in which state is saved in a database, so you can be sure that those jobs won't be lost. Persistent jobs introduce additional performance overhead in the system, so you have to use them pragmatically.
The Timer API also lacks methods to simplify setting the desired execution time. As we saw in the example above, the most you can do is to set a start date and a repeat interval. Surely, everyone who has used the Unix cron tool would like to see similar configuration possibilities within their scheduler. Quartz defines org.quartz.CronTrigger, which lets you set a desired firing date in a flexible manner.
Developers often need one more feature: managing and organizing jobs and tasks by their names. In Quartz, you can get jobs by their names or presence in a group, which can be a real help in environments with a large number of scheduled jobs and triggers.
Now, let's implement our report generation example using Quartz and explain basic features of the library.
package net.nighttale.scheduling;

import org.quartz.*;

public class QuartzReport implements Job {

  public void execute(JobExecutionContext cntxt)
    throws JobExecutionException {
      System.out.println(
        "Generating report - " +
cntxt.getJobDetail().getJobDataMap().get("type")
      );
      //TODO Generate report
  }

  public static void main(String[] args) {
    try {
      SchedulerFactory schedFact 
       new org.quartz.impl.StdSchedulerFactory();
      Scheduler sched  schedFact.getScheduler();
      sched.start();
      JobDetail jobDetail 
        new JobDetail(
          "Income Report",
          "Report Generation",
          QuartzReport.class
        );
      jobDetail.getJobDataMap().put(
                                "type",
                                "FULL"
                               );
      CronTrigger trigger  new CronTrigger(
        "Income Report",
        "Report Generation"
      );
      trigger.setCronExpression(
        "0 0 12 ? * SUN"
      );
      sched.scheduleJob(jobDetail, trigger);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Quartz defines two basic abstractions, Jobs and Triggers. A Job is the abstraction of the work that should be done, and Trigger represents time when the action should occur.
Job is an interface, so all we have to do is to make our class implement the org.quartz.Job interface (or org.quartz.StatefulJob, as we will see in a moment) and override the execute() method. In the example, we saw how one can pass parameters to the Job through the jobDataMap attribute, which is a modified implementation of java.util.Map. Deciding whether you are going to implement stateful or non-stateful jobs is a matter of deciding whether you want to change these parameters during execution. If you implement Job, all of the parameters are saved at the moment the job is scheduled for the first time, and all changes made later are discarded. If you change the StatefulJob's parameters in the execute() method, this new value will be passed when the job triggers another time. One important implication to consider: StatefulJobs can't be executed concurrently, because the parameters might change during the execution.
There are two basic kinds of Triggers: SimpleTrigger and CronTrigger. SimpleTrigger provides basically the same functionality you get from the Timer API. It should be used if the Job should be triggered once, followed possibly by repeats at a specific interval. You can specify start date, end date, repeat count, and repeat interval for this kind of trigger.
In the example above, we used CronTrigger because of its flexibility to schedule jobs on a more realistic basis. CronTriggers allow us to express schedules such as "every weekday at 7:00 p.m." or "every five minutes on Saturday and Sunday." We will not go further into explaining cron expressions in this article, so you are advised to find all of the details about its possibilities in the class' Javadoc.
In order to run the above example, you'll need a file named quartz.properties in the classpath, with basic Quartz configuration. If you want to use a different name for the file, you should pass it as a parameter to the StdSchedulerFactory constructor. Here is an excerpt of the file with minimal properties:
#
# Configure Main Scheduler Properties 
#
org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = one

#
# Configure ThreadPool 
#
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount =  5
org.quartz.threadPool.threadPriority = 4

#
# Configure JobStore 
#
org.quartz.jobStore.misfireThreshold = 5000

org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
Another advantage of Quartz versus the standard Timer API is its usage of a thread pool. Quartz uses this thread pool to get threads for job execution. The size you choose for the thread pool affects the number of jobs that can be executed concurrently. If the job needs to be fired and there is no free thread in the pool, it will sleep until a thread becomes available. How many threads to use in the system is a tough decision, and it is best to determine it experimentally. The default value is five, which is quite enough if you are not dealing with thousands of Jobs. There is one thread pool implementation in Quartz itself, but you are not limited on its usage.
Now we come to the JobStores. JobStores keep all the data about Jobs and Triggers. So, this is where we need to decide if we are going to keep our Jobs persistent or not. In the example, we used org.quartz.simpl.RAMJobStore, which means that all of the data will be kept in memory and thus will not be persistent. As a result, if the application crashes, all the data about scheduled Jobs will be lost. In some situations, this is the desired behavior, but when you want to make the data persistent, you should configure your application to use org.quartz.simpl.JDBCJobStoreTX (or org.quartz.simpl.JDBCJobStoreCMP). JDBCJobStoreTX requires some more configuration parameters that will be explained by example.

org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
org.quartz.jobStore.dataSource = myDS
org.quartz.jobStore.tablePrefix = QRTZ_

#
# Configure Datasources 
#
org.quartz.dataSource.myDS.driver = org.postgresql.Driver
org.quartz.dataSource.myDS.URL = jdbc:postgresql:dev
org.quartz.dataSource.myDS.user = dejanb
org.quartz.dataSource.myDS.password =
org.quartz.dataSource.myDS.maxConnections = 5
 
In order to successfully use a relational database with Quartz, first we need to create the tables it needs. You can use any available database server that has an appropriate JDBC driver. In the docs/dbTables folder, you'll find initialization scripts to generate the necessary tables.
After that, we should declare the delegate class that adapts standard SQL queries to the specific RDBMS SQL dialect. In our example, we have chosen PostgreSQL as the database server so the appropriate org.quartz.impl.jdbcjobstore.PostgreSQLDelegate class is submitted. For information what delegate to use with your specific server, you should consult the Quartz documentation.
The tablePrefix parameter defines what prefix is used for Quartz tables in the database (the default is QRTZ_). This way, you can distinguish these tables from the rest of the database.
For every JDBC store, we need to define datasource to be used. This is part of the common JDBC configuration and will not be further explained here.
The beauty of Quartz is that after these configuration changes are made, our report-generation example would persist the data in the database without changing a single line of code.

Advanced Quartz

So far we have described basic Quartz features that can be a good foundation to start using it in your projects. Besides that, this library has great architecture that can fully leverage your effort.
Besides the basics provided by Quartz, the library has a great architecture that will help solve problems in your application. One of its key features is listeners: objects that are called when some event in the system occurs. There are three types of listeners: JobListeners, TriggerListeners, and SchedulerListeners.
Listeners can be particularly useful when you want a notification if something goes wrong in the system. For example, if an error occurs during report generation, an elegant way to notify the development team about it is to make a JobListener that will send an email or SMS.
A JobListener can provide more interesting functionality. Imagine a Job that has to deal with a task that is highly dependent on some system resource availability (such as a network that is not stable enough). In this case, you can make a listener that will re-trigger that job if the resource is not available when the job is executed.
Quartz can also deal with situations when some Trigger has misfired, or didn't fire because the scheduler was down. You can set a misfire instruction by using the setMisfireInstruction() method of the Trigger class. It takes the misfire instruction type for a parameter, which can have one of the following values:
  • Trigger.INSTRUCTION_NOOP: does nothing.
  • Trigger.INSTRUCTION_RE_EXECUTE_JOB: executes the job immediately.
  • Trigger.INSTRUCTION_DELETE_TRIGGER: deletes the misfired trigger.
  • Trigger.INSTRUCTION_SET_TRIGGER_COMPLETE: declares the trigger completed.
  • Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_COMPLETE: declares all triggers for that job completed.
  • Trigger.MISFIRE_INSTRUCTION_SMART_POLICY: chooses the best fit misfire instruction for a particular Trigger implementation.
Trigger implementations (such as CronTrigger) can define new types of misfire instructions that can be useful. You should check out the Javadocs for these classes for more information on this topic. Using the TriggerListener, you can gain more control on actions that should be used if a misfire occurs. Also, you can use it to react to trigger events, such as a trigger's firing and completion.
SchedulerListener deals with global system events, such as scheduler shutdown or the addition or removal of jobs and triggers.
Here, we will just demonstrate a simple JobListener for our report generation example. First we have to write a class to implement the JobListener interface.
package net.nighttale.scheduling;

import org.quartz.*;


public class MyJobFailedListener implements JobListener {

  public String getName() {
    return "FAILED JOB";
  }

  public void jobToBeExecuted
    (JobExecutionContext arg0) {
  }


  public void jobWasExecuted(
    JobExecutionContext context,
    JobExecutionException exception) {

    if (exception != null) {
      System.out.println(
        "Report generation error"
      );
      // TODO notify development team
    } 
  }
}
and then add the following line to the main method of our example:
sched.addGlobalJobListener(new MyJobFailedListener());
By adding this listener to the global list of scheduler job listeners, it will be called for all of the jobs. Of course, there is a way to set listeners only for a particular job. To do this, you should use Scheduler's addJobListeners() method to register the listener with the scheduler. Then add the registered listener to the job's list of listeners with JobDetail's addJobListener() method, with the listener name as a parameter (the value returned from getName() method of the listener).
sched.addJobListener(new MyJobFailedListener());
jobDetail.addJobListener("FAILED JOB");
To test if this listener really works, simply put
throw new JobExecutionException();
in the execute() method of the report generation job. After the job has been executed, the jobWasExecuted() method of our listener is executed, and the thrown exception is passed as the argument. Because the exception is not null in our case, you should expect to see the message "Report generation error" on the screen.
One final note about listeners is that one should be careful about number of listeners that is used in the system, because it could down the performance of the application.
There is one more way you can extend Quartz's features, and that is through plug-ins. Plug-ins can do practically any work you need; all you have to is to write the class implementing the org.quartz.spi.SchedulerPlugin interface. This interface defines two methods that need to be implemented -- one for initialization (which takes a Scheduler object as a parameter) and one for shutdown. Everything else is up to you. In order to make SchedulerFactory use a certain plug-in, all you have to do is to add a line in the properties file (quartz.properties) with the plug-in class and a few optional configuration parameters (which depend on the particular plug-in). There are a few plug-ins already in Quartz itself. One is the shutdownHook, which can be used to cleanly shut down the scheduler in case the JVM terminates. To use this plug-in, just add the following lines in the configuration file:
org.quartz.plugin.shutdownHook.class = 
   org.quartz.plugins.management.ShutdownHookPlugin
org.quartz.plugin.shutdownHook.cleanShutdown = true

Adaptable in Every Environment

All of the above applies to using Quartz in a standalone application. Now, we will see how we can use its interface in some of the most common environments for Java developer.

RMI

With a distributed application using RMI, Quartz is simple, as we've seen above. The differences are in the configuration.
There are two necessary steps: first we have to set Quartz as an RMI server that will handle our requests, and then we just use it in the standard manner.
The source code of this example is practically the same as in our first example, but here we will divide it in two parts: scheduler initialization and scheduler usage.
package net.nighttale.scheduling.rmi;

import org.quartz.*;

public class QuartzServer {

  public static void main(String[] args) {
 
    if(System.getSecurityManager() != null) {
      System.setSecurityManager(
        new java.rmi.RMISecurityManager()
      );
    }
    
    try {
      SchedulerFactory schedFact =
       new org.quartz.impl.StdSchedulerFactory();
      Scheduler sched = schedFact.getScheduler();
      sched.start(); 
    } catch (SchedulerException se) {
      se.printStackTrace();
    }
  }
}
As you can see, the code for scheduler initialization is standard except that contains a part that sets the security manager. The key is in the configuration file (quartzServer.properties), which now looks like this:

#
# Configure Main Scheduler Properties 
#
org.quartz.scheduler.instanceName = Sched1org.quartz.scheduler.rmi.export = true
org.quartz.scheduler.rmi.registryHost = localhost
org.quartz.scheduler.rmi.registryPort = 1099
org.quartz.scheduler.rmi.createRegistry = true

#
# Configure ThreadPool 
#
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5
org.quartz.threadPool.threadPriority = 4

#
# Configure JobStore 
#
org.quartz.jobStore.misfireThreshold = 5000

org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
 
Notice the highlighted lines, which indicate that this scheduler should export its interface through RMI and provide parameters for running the RMI registry.
We have do a few more things to successfully deploy our server, all of which are typical tasks for exporting objects through RMI. First, we need to start rmiregistry on the server (if it is not already up). This is done by calling:
   rmiregistry &
on Unix systems, or
   start rmiregistry
on Windows platforms.
Next, start the QuartzServer class with the following options (all on one line):
java  -Djava.rmi.server.codebase
   file:/home/dejanb/quartz/lib/quartz.jar
   -Djava.security.policyrmi.policy
   -Dorg.quartz.propertiesquartzServer.properties
   net.nighttale.scheduling.rmi.QuartzServer
Now, let's clarify these parameters a little bit. Quartz's Ant build tasks include an rmic call to create the necessary RMI classes, so to point clients to the codebase with these classes, you have to start it with the -Djava.rmi.server.codebase parameter set to file: plus the full path to the location of quartz.jar (of course, this could also be a URL to the library).
An important issue in a distributed system is security; thus, RMI enforces that you use security policy. In this example, we used the basic policy file (rmi.policy) that grants all privileges.
grant {
  permission java.security.AllPermission;
};
In practice, you should adapt this policy to your system security needs.
OK, now the Scheduler is ready to accept your Jobs via RMI. Let's write the client that will do that.
package net.nighttale.scheduling.rmi;

import org.quartz.*;
import net.nighttale.scheduling.*;

public class QuartzClient {

  public static void main(String[] args) {
    try {
      SchedulerFactory schedFact =
       new org.quartz.impl.StdSchedulerFactory();
      Scheduler sched = schedFact.getScheduler();
      JobDetail jobDetail = new JobDetail(
        "Income Report",
        "Report Generation",
        QuartzReport.class
      );
  
      CronTrigger trigger = new CronTrigger(
        "Income Report",
        "Report Generation"
      );
      trigger.setCronExpression(
        "0 0 12 ? * SUN"
      );
      sched.scheduleJob(jobDetail, trigger);
    } catch (Exception e) {
      e.printStackTrace();
    }
   }
}
As you can see, the source for the client is literally the same as before. Of course, there are different settings for quartzClient.properties here, too. All you have to do is to specify that this scheduler is the RMI client (proxy) and the location of the registry where it should look for the server.
 
# Configure Main Scheduler Properties  
org.quartz.scheduler.instanceName = Sched1
org.quartz.scheduler.rmi.proxy = true
org.quartz.scheduler.rmi.registryHost = localhost
org.quartz.scheduler.rmi.registryPort = 1099

No other settings are necessary, because all the work is done on the server side. In fact, if other settings are present, they will be ignored. The important thing is that the names of the schedulers must match in the client and server configurations (Sched1 in this case). And that's all there is, for a start. Just run the client with redirected properties file (again, all on one line):
 
java -Dorg.quartz.properties
       quartzClient.properties
       net.nighttale.scheduling.rmi.QuartzClient

and you should expect the same behavior in the server console as in the first example.

Web and Enterprise

If you are developing a web or enterprise solution, one question that may come up is the right place to start the scheduler. For that, Quartz provides org.quartz.ee.servlet.QuartzInitializerServlet. All we need to do is to make the following configuration in the web.xml file:

<servlet>
  <servlet-name>QuartzInitializer</servlet-name>
  <display-name>Quartz Initializer Servlet</display-name>
  <servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>   
 
If you want to call the EJB method as a Job, you should pass the org.quartz.ee.ejb.EJBInvokerJob class to your JobDetail. To demonstrate this technique, we will implement ReportGenerator as a session bean and call its generateReport() method from the servlet.
package net.nighttale.scheduling.ee;

import java.io.IOException;

import javax.servlet.*;
import net.nighttale.scheduling.Listener;
import org.quartz.*;
import org.quartz.ee.ejb.EJBInvokerJob;
import org.quartz.impl.StdSchedulerFactory;

public class ReportServlet implements Servlet {

  public void init(ServletConfig conf)
    throws ServletException {
    JobDetail jobDetail = new JobDetail(
      "Income Report",
      "Report Generation",
      EJBInvokerJob.class
    );
    jobDetail.getJobDataMap().put(
      "ejb",
      "java:comp/env/ejb/Report"
    );
    jobDetail.getJobDataMap().put(
      "method",
      "generateReport"
    );
    Object[] args = new Object[0];
    jobDetail.getJobDataMap().put("args", args);
    CronTrigger trigger = new CronTrigger(
      "Income Report",
      "Report Generation"
    );
    try {
      trigger.setCronExpression(
        "0 0 12 ? * SUN"
      );
      Scheduler sched =
       StdSchedulerFactory.getDefaultScheduler();
      sched.addGlobalJobListener(new Listener());
      sched.scheduleJob(jobDetail, trigger);
      System.out.println(
        trigger.getNextFireTime()
      );
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public ServletConfig getServletConfig() {
    return null;
  }

  public void service(ServletRequest request,
                      ServletResponse response)
    throws ServletException, IOException {
  }

  public String getServletInfo() {
    return null;
  }

  public void destroy() {
  }
}
As you can see, there are three parameters that needs to be passed to the job.
  • ejb: The JNDI name of the enterprise bean.
  • method: The actual method to be called.
  • args: An array of objects to be passed as a method arguments.
Everything else remains the same from the Quartz usage perspective. I have put this example in the servlet initialization method for simplicity, but of course, it could be done from any convenient place in your application. In order to successfully run such a job you'll need to register this EJB with your web application. This is usually done by putting the following lines in the web.xml file.

<ejb-ref>
  <ejb-ref-name>ejb/Report</ejb-ref-name>
  <ejb-ref-type>Session</ejb-ref-type>
  <home>net.nighttale.scheduling.ee.ReportHome</home>
  <remote>net.nighttale.scheduling.ee.Report</remote>
  <ejb-link>ReportEJB</ejb-link>
</ejb-ref>
 
Some application servers (such as Orion) need to be instructed to allow creation of user threads, and thus would need to be started with the -userThread switch.
These are by no means all the enterprise features of Quartz, but it's a good start and you should look at Quartz's Javadocs for further questions.

Web Services

Quartz currently has no built-in support for being used as a web service, but you can find a plug-in that enables you to export the Scheduler interface through XML-RPC. Building an installation procedure is simple. To start, you have to extract the plug-in source into the Quartz source folder and rebuild it. Plug-ins rely on the Jakarta XML-RPC library, so you have to be sure that it is in the classpath. Next, add the following lines in the properties file.
org.quartz.plugin.xmlrpc.class = org.quartz.plugins.xmlrpc.XmlRpcPlugin
org.quartz.plugin.xmlrpc.port = 8080
Now the Scheduler is ready to be used through XML-RPC. This way you can use some of the Quartz features from different languages such as PHP or Perl, or in a distributed environment where RMI might not be the right solution.

Summary

We've looked at two ways to do scheduling in Java. Quartz is indeed a powerful library, but for simple requirements the Timer API can save the day, keeping you from putting unnecessary complexity into the system. You should think of using the Timer API in cases where you don't have a lot of tasks that need to be scheduled, and when their execution times are well-known (and unchangeable) in the design process. In these situations, you don't have to worry whether some tasks are lost because of a shutdown or crash. For more sophisticated needs, Quartz is an elegant scheduling solution. Of course, you can always make your own framework, based on the Timer, but why to bother when all that (and much more) already exist?
One event worth noting is IBM and BEA's submission of JSR 236 titled "Timer for Application Servers". This specification is focused on creating an API for timers in managed environments where using the standard API is insufficient. You can find more details about the specification on IBM's developerWorks site, and the specification should be available for public review in spring.

Using the Quartz Enterprise Scheduler in J2EE

http://www.theserverside.com/news/1377023/Using-the-Quartz-Enterprise-Scheduler-in-J2EE

Before we dive down the details let's assume that you have a business use case that requires a Job to run every 30 minutes. In this article we will discuss how can you achieve this using the Cron Triggers functionality of Quartz.

Define Your Job as an EJB Method

The first step in scheduling a job in J2EE application is to create the EJB and implement the business logic as an EJB Method. For example, I have created a stateless EJB named TestEJB and I've a method named yourMethod that I want to schedule as a job. For clarity, following is the code snippet of my EJB bean implementation class and EJB deployment descriptor:

package howto.quartz.ejb;
import java.rmi.*;
import javax.ejb.*;
public class TestEJBBean implements SessionBean {
  public TestEJBBean() {
  }
  // EJB life cycle methods are omitted for brevity
  ........
  public void yourMethod() throws RemoteException {
    System.out.println("TestEJB Job");
  }
}


Use Quartz API to Schedule Your Job from a Generic Servlet

Quartz uses its own thread pool and these threads are not container threads. Servlet API allows user threads and hence you have to create a Servlet and use Quartz API to schedule your Job. Quartz provides the QuartzInitializerServlet to be used as the entry point for the Quartz job scheduling service. We want to submit the yourMethod of TestEJB as the job in this example. So we will have to create a GenericServlet named howto.quartz.servlet.QuartzServlet and implement the init() method that submits EJB method as a Cron Trigger. In this example, I'm setting the cron expression as an initialization parameter instead of hard coding in the Servlet. The following is the code for the Servlet:

public class QuartzServlet extends GenericServlet {
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    System.out.println("Scheduling Job ..");
    JobDetail jd = new JobDetail("Test Quartz","My Test Job",EJBInvokerJob.class);
    jd.getJobDataMap().put("ejb", "java:comp/env/ejb/TestEJB");
    jd.getJobDataMap().put("method", "yourMethod");
    Object[] jdArgs = new Object[0];
    jd.getJobDataMap().put("args", jdArgs);
    CronTrigger cronTrigger = new CronTrigger("Test Quartz", "Test Quartz");

    try {
      String cronExpr = null;
      // Get the cron Expression as an Init parameter
      cronExpr = getInitParameter("cronExpr");
      System.out.println(cronExpr);
      cronTrigger.setCronExpression(cronExpr);
      Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
      sched.scheduleJob(jd, cronTrigger);
      System.out.println("Job scheduled now ..");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
  }
  public String getServletInfo() {
    return null;
  }
}


Auto starting the Servlets

We want the job to be submitted as soon the application is deployed or the container is started. We have to initialize the QuartzInitializerServlet and howto.quartz.servlet.QuartzServlet that we implemented whenever the web module is restarted. In order to achieve that we need to create the following entry in the deployment descriptor for the web module (web.xml):

<servlet>
 <servlet-name>QuartzInitializer</servlet-name>
 <display-name>Quartz Initializer Servlet</display-name>
 <servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>
<servlet>
 <servlet-name>QuartzServlet</servlet-name>
 <display-name>Quartz Servlet</display-name>
 <servlet-class>howto.quartz.servlet.QuartzServlet</servlet-class>
 <init-param>
  <param-name>cronExpr</param-name>
  <param-value>0 0/30 * * * ?</param-value>
 </init-param>
 <load-on-startup>2</load-on-startup>
</servlet>

The Servlet accesses the TestEJB so we need to create the ejb-ref entry in the web.xml as follows:

<ejb-ref>
 <ejb-ref-name>ejb/TestEJB</ejb-ref-name>
 <ejb-ref-type>Session</ejb-ref-type>
 <home>howto.quartz.ejb.TestEJBHome</home>
 <remote>howto.quartz.ejb.TestEJB</remote>
</ejb-ref>


Assembling/Packaging the Application

The web module accesses the Quartz API so we need to package the Quartz libraries in the WAR module. We need to put these libraries e.g. quartz.jar, commons-logging.jar, commons-pool-1.1.jar, etc. in the WEB-INF/lib of the WAR module. The quartz settings that you need for your environment must be specified in the quartz.properties and this file must be put in the WEB-INF/classes directory of the WAR module.

The ejb-jar that contains the TestEJB and the WAR containing the Quartz libraries and QuartzServlet needs to be packaged as an EAR and deployed to the J2EE container.

Note:
For OC4J, you need to configure it to allow User Threads.
Configure your J2EE container to allow user threads to be created by your application as Quartz scheduler creates threads those are treated as user threads. For example, you need to start OC4J as follows to allow user threads:

java -jar oc4j.jar -userThreads


Deploy Your J2EE Application

Then deploy your application in your J2EE container. Make sure that your application is set automatically started when your application server is started. For example, if you are using OC4J make sure that you set the auto-start for your application and load-on-startup for the web module to true. To be sure make sure that you have the following entries in the server configuration files:

server.xml:

<application name="quartz" path="../applications/quartz-app.ear" auto-start="true" />

http-web-site.xml:

<web-app application="quartz" name="quartz-web" load-on-startup="true" root="/quartz" />

Now you are ready to go!

Your EJB method now is scheduled as a recurring Job that occurs in every 30 minutes.

Sunday, March 21, 2010

Workaround for WebLogic Workshop update error.

If you had installed WebLogic Portal 10.3 and are trying to install a couple of plug ins to Workshop/Eclipse, but whenever you select any item to install, you will get this error:

WebLogic Portal (10.3.0) requires feature "com.m7.nitrox (1.0.20)", or compatible.

This is a bug, CR379999. that will be fixed WLP 10.4. In the meantime, here's the workaround from the bug report:

Download the plugin manually, and either 1) create an extension location on the file system from it and add that via Help|Software Updates|Manage Configuration, or 2) extract it to one of the workshop eclipse folders (i.e. tools/eclipse_pkgs/2.0/eclipse_3.3.2, tools/eclipse_pkgs/2.0/pkgs/eclipse, workshop_10.3/workshop4WP/eclipse, wlportal_10.3/eclipse).

Additionally, you can comment out the com.* import lines in your %BEA_HOME%\wlportal_10.3\eclipse\features\com.bea.wlp_10.3.0\feature.xml, like this:





Thursday, March 18, 2010

How to get the invocation hierarchy in Java?

In Java, we can see the invocation hierarchy sometimes in Java. Especially, the log4j can log the class into log file with package name, method and line even. How can we implement the similar functionality?

First, how can we get the invocation class and method? Stack trace.

StackTraceElment[] ste = new Throwable().getStackSTrace();

In the array of StackTraceElement, we can find the hierarchy of current stack. By this, we can get the invocation map of whole stack.

StackTraceElment APIs:
String getClassName()
Returns the fully qualified name of the class containing the execution point represented by this stack trace element.
String getFileName()
Returns the name of the source file containing the execution point represented by this stack trace element.
int getLineNumber()
Returns the line number of the source line containing the execution point represented by this stack trace element.
String getMethodName()
Returns the name of the method containing the execution point represented by this stack trace element.

In Java 5, The Thread introduced two new methods: getStackTrace() and getAllStackTraces(). Now we don't need to use (new Throwable()).getStackTrace() and by using Thread.getCurrentThread().getStackTrace() to get the stack trace info. Not only doing so, but also we can get stack trace of other threads if we have the enough permission.

Stub caching and concurrent reuse problems in Axis

Reference Stub caching and concurrent reuse problems

Somebody tried to cache the generated stubs for reusing by concurrent clients
because instantiating of them takes too long. But every time he started 4+ concurrent clients for the same web-service, he would receive some weird exceptions from the core of Axis. This happened only in case of caching the stubs and not issue for creating new stub for every client but the performance.

Some people replied the question and mentioned the cache of stub was not hoped and the internals of the stubs may screw up if cached! If you are using the usual no
args constructor of the stub, the stub may need to create its own configuration context and that may take significant time. You can cache the config context and create the stub passing in your config context, instead of caching stub.

In the mail list, also somebody mentioned they had found two important factors to keep in mind when reusing stubs:

  1. The stubs are not thread safe, so you cannot use the same stub in
    two concurrent threads

  2. Recently discovered that even the stub constructor is not thread safe! So two concurrent threads cannot call the constructor at the same time.



If you have a typical architecture that reuses client processing threads, then each needs their own stub but once it creates a stub it can continue to use that indefinitely.

Another useful thing to do is:

options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, new Boolean(true));

Thursday, March 11, 2010

Spring Batch vs Quartz

A. What is Spring Batch?
It is a generalized (lightweight) Enterprise Batch processor. So it is a system that is designed to autonomously preform a set of operations data. For example, say that at the end of the month you are required to generate a survey on all claims processed by an insurance agency. The process to do this requires going though each claim (across multiple departments) and pulling various pieces of metadata -- combine the data into a summary. -- This is the kind of thing you design a batch program for -- especially if the requirements may change over time (like as laws change) so you need flexibility.

B. Why go for Spring Batch?
Well it is lightweight and pretty easy to work with however this is really an architecture question and without knowing much about the existing system you are working with I don't know if I can answer that.

C.How can we use Quartz for scheduling Spring Batch?
Quartz is an excellent concurrent scheduler. It is really not difficult to setup and configure. However -- before using Quartz you may wish to see if these features are already included in your infrastructure. For example many application servers provide scheduling.

Saturday, February 27, 2010

Yahoo! YSlow

Yahoo! YSlow
YSlow analyzes web pages and suggests ways to improve their performance based on a set of rules for high performance web pages. YSlow is a Firefox add-on integrated with the Firebug web development tool. YSlow grades web page based on one of three predefined ruleset or a user-defined ruleset. It offers suggestions for improving the page's performance, summarizes the page's components, displays statistics about the page, and provides tools for performance analysis, including Smush.it™ and JSLint.

Tuesday, February 02, 2010

JSF 2.0 with Spring 3 and Spring Security 3 on Google Application Engine

JSF 2.0 with Spring 3 and Spring Security 3 on Google Application Engine

In this post I'm going to show a simple fully integrated CRUD style application working on Google Application Engine.

Credit Card Mod10 Validation

The follow code was got from WikiPedia and did a little modification. It is very neat and elegant.

public static boolean isValidCC(String num) {
  final int[][] sumTable = {{0,1,2,3,4,5,6,7,8,9},{0,2,4,6,8,1,3,5,7,9}};
  int sum = 0, flip = 0;
  for (int i = num.length() - 1; i >= 0; i--, flip++){
    int n = num.charAt(i) - '0';
    if (n < 0 || n > 9)
      return false;
    sum += sumTable[flip & 0x1][n];
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}


The follow code used a variable as a switch to double the value.

public static boolean isValidCC(String number) {
  int sum = 0;
  int mul = 1;
  for (int i = number.length() - 1; i >= 0; i--) {
    int n = number.charAt(i) - '0';
    if (n < 0 || n > 9)
      return false;
    n *= (mul == 1) ? mul++ : mul--;
    sum += (n>9 ? n-9 : n);
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}


The follow code used the position to double the value.

public static boolean isValidCC(String number) {
  int sum = 0;
  for (int i = number.length() - 1; i >= 0; i--) {
    int n = number.charAt(i) - '0';
    if (n < 0 || n > 9)
      return false;
    if ((number.length()-i)%2 == 0)
      n *= 2;
    sum += (n>9 ? n-9 : n);
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}


The follow code used any way to double the value.

protected boolean isValidCC(String number) {
  int digits = number.length();
  int oddOrEven = digits & 1;
  long sum = 0;
  for (int i= 0; i < digits; i++) {
    int n = number.charAt(count) -'0';
    if (n < 0 || n > 9)
      return false;
    if (((i& 1) ^ oddOrEven) == 0)
      n *= 2;
    sum += (n>9 ? n-9 : n);
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}


The follow code much easier to understand.

public static boolean isValidCC(String number) {
  int sum = 0;
  boolean alternate = false;
  for (int i = number.length() - 1; i >= 0; i--) {
    int n = Integer.parseInt(number.substring(i, i + 1)); //May throw out a runtime exception
    if (alternate) {
      n *= 2;
    sum += (n>9 ? (n%10)+1 : n);
    alternate = !alternate;
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}

Friday, January 29, 2010

URL rewriting

Both of these methods revolve around the concept of URL rewriting. Basically it involves suffixing the URL with a HTTP_QUERY_STRING, which mostly is a session id used to keep track of a particular users context.

URL re-writing is used get over the usage of cookies which are dependent on browser configuration, thus not reliable at all.

The difference between the methods is in their usage and not their functionality. Both perform the same task of re-writing a URL.

encodeRedirectURL
When you send a redirect header to the browser using response.sendRedirect(string URL)

Example, you want to redirect to different page.

if (name == null){
  response.sendRedirect(response(encodeRedirectURL("errorPage.jsp"))
}


encodeURL
On the other hand, you provide a link to shopping cart page to a user.

printWriter.println("A HREF=" + response.encodeURL("shoppingCart.jasp") + ">")


Essentially they do same thing of re-writing the URl for non-cookie compliant browser.

encodeURL() is used for all URLs in a servlet's output. It helps session ids to be encoded with the URL.

encodeRedirectURL() is used with res.sendRedirect only.It is also used for encoding session ids with URL but only while redirecting.

Monday, January 25, 2010

Xerces

Xerces is a collection of software libraries for parsing, validating, serializing and manipulating XML. The library implements a number of standard APIs for XML parsing, including DOM, SAX and SAX2.

XML Data Binding

XML data binding refers to the process of representing the information in an XML document as an object in computer memory. This allows applications to access the data in the XML from the object rather than using the DOM or SAX to retrieve the data from a direct representation of the XML itself.

Java Architecture for XML Binding (JAXB)
JABX allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. In other words, JAXB allows storing and retrieving data in memory in any XML format, without the need to implement a specific set of XML loading and saving routines for the program's class structure.

Usage of JAXB
The tool "xjc" can be used to convert XML Schema and other schema file types (as of Java 1.6, RELAX NG, XML DTD, and WSDL are supported experimentally) to class representations. Classes are marked up using annotations from javax.xml.bind.annotation.* namespace, for example, @XmlRootElement and @XmlElement. XML list sequences are represented by attributes of type java.util.List. Marshallers and Unmarshallers are created through an instance of JAXBContext.
In addition, JAXB includes a "schemagen" tool which can essentially perform the inverse of "xjc", creating an XML Schema from a set of annotated classes.

XMLBeans
It is a tool that allows access to the full power of XML in a Java friendly way. The idea is to take advantage of the richness and features of XML and XML Schema and have these features mapped as naturally as possible to the equivalent Java language and typing constructs. XMLBeans uses XML Schema to compile Java interfaces and classes that can then be used to access and modify XML instance data. Using XMLBeans is similar to using any other Java interface/class: with methods like getFoo or setFoo, just as when working with Java. While a major use of XMLBeans is to access XML instance data with strongly typed Java classes there are also APIs that allow access to the full XML infoset (XMLBeans keeps XML Infoset fidelity) as well as to allow reflection into the XML schema itself through an XML Schema Object model.

Usage of XMLBean
To accomplish the above objectives, XMLBeans provides three major APIs:
  • XmlObject
  • XmlCursor
  • SchemaType
    XmlObject: The java classes that are generated from an XML Schema are all derived from XmlObject. These provide strongly typed getters and setters for each of the elements within the defined XML. Complex types are in turn XmlObjects. For example getCustomer might return a CustomerType (which is an XmlObject). Simple types turn into simple getters and setters with the correct java type. For example getName might return a String.
    XmlCursor: From any XmlObject the developer can get an XmlCursor. This provides efficient, low level access to the XML Infoset. A cursor represents a position in the XML instance. The cursor can be moved around the XML instance at any level of granularity needed from individual characters to Tokens.
    SchemaType: XMLBeans provides a full XML Schema object model that can be used to reflect on the underlying schema meta information. For example, the developer might generate a sample XML instance for an XML schema or perhaps find the enumerations for an element so that they may be displayed.
  • XML Parser

    Java API for XML Processing - JAXP
    is one of the Java XML programming APIs. It provides the capability of validating and parsing XML documents. The three basic parsing interfaces are:
  • the Document Object Model parsing interface or DOM interface
  • the Simple API for XML parsing interface or SAX interface
  • the Streaming API for XML or StAX interface (added in JDK 6; separate jar available for JDK 5)

    XML Parsing
    Traditionally, XML APIs are either:
  • tree based - the entire document is read into memory as a tree structure for random access by the calling application
  • event based - the application registers to receive events as entities are encountered within the source document.
    Both have advantages; the former (for example, DOM) allows for random access to the document, the latter (e.g. SAX) requires a small memory footprint and is typically much faster.

    These two access metaphors can be thought of as polar opposites. A tree based API allows unlimited, random, access and manipulation, while an event based API is a 'one shot' pass through the source document.

    Event-based XML Parsing Libs
    SAX is the Simple API for XML, originally a Java-only API. SAX was the first widely adopted API for XML in Java, and is a "de facto" standard.

    A parser which implements SAX (ie, a SAX Parser) functions as a stream parser, with an event-driven API. The user defines a number of callback methods that will be called when events occur during parsing. The SAX events include:
  • XML Text nodes
  • XML Element nodes
  • XML Processing Instructions
  • XML Comments

    Events are fired when each of these XML features are encountered, and again when the end of them is encountered. XML attributes are provided as part of the data passed to element events. SAX parsing is unidirectional; previously parsed data cannot be re-read without starting the parsing operation again.

    DOM-based XML Parsing Libs
    JDOM
    An open source Java-based document object model for XML that was designed specifically for the Java platform so that it can take advantage of its language features. JDOM integrates with Document Object Model (DOM) and Simple API for XML (SAX), supports XPath and XSLT. It uses external parsers to build documents.

    DOM4J
    An open source Java library for working with XML, XPath and XSLT. It is compatible with DOM, SAX and JAXP standards.

    Streaming API for XML (StAX)
    An application programming interface (API) to read and write XML documents, originating from the Java programming language community.

    StAX was designed as a median between these two opposites. In the StAX metaphor, the programmatic entry point is a cursor that represents a point within the document. The application moves the cursor forward - 'pulling' the information from the parser as it needs. This is different from an event based API - such as SAX - which 'pushes' data to the application - requiring the application to maintain state between events as necessary to keep track of location within the document.

    StAX XML Parsing Libs
    Apache Axiom
    A a light weight XML object model based on top of Stax and also provides lazy object building.
  • Friday, January 22, 2010

    Contexts and Dependency Injection for Java EE (CDI) - Part 2


    Custom Object Factories with CDI Producers/Disposers
    In a majority of cases, @Inject and @Qualifier annotations gives the container static control over object creation. However, there are cases where it makes a lot of sense for you to control object creation and destruction yourself in Java code. Good examples are complex object creation/destruction, legacy/third-party API integration, objects that need to be constructed dynamically at runtime and creating injectable strings, collections, numeric values and so on. Along the same lines as the traditional object factory pattern, this is what CDI producers and disposers allow you to do. Another way of looking at this is that the container allows you to step in and take manual control over creating/destroying objects when it makes sense.

    In the following code, we'll show you how to create a simple abstraction over the low-level JMS API using CDI producers and disposers. As you might already know, plain JMS code can be pretty verbose because the API is so general purpose. Using CDI, we can create a custom JMS object factory that hides most of the verbose code to handle the JMS connection and session, keeping the actual JMS API client code pretty clean.
    @Stateless
    public class OrderService {
    @Inject @OrderSession private Session session;
    @Inject @OrderMessageProducer private MessageProducer producer;

    public void sendOrder(Order order) {
    try {
    ObjectMessage message = session.createObjectMessage();
    message.setObject(order);
    producer.send(message);
    } catch (JMSException e) {
    e.printStackTrace();
    }
    }
    }

    Rather than injecting the JMS connection factory and queue, we are instead actually injecting the JMS session and message producer, using qualifiers specific to messaging for orders (@OrderSession, @MessageProducer). The session and message producer is being injected from a shared object factory with a set of CDI producers and disposers handling the JMS session, connection and message producer life-cycle behind the scenes.

    Here is the code for the custom object factory:
    public class OrderJmsResourceFactory {
    @Resource(name="jms/ConnectionFactory")
    private ConnectionFactory connectionFactory;

    @Resource(name="jms/OrderQueue")
    private Queue orderQueue;

    @Produces @OrderConnection
    public Connection createOrderConnection() throws JMSException {
    return connectionFactory.createConnection();
    }

    public void closeOrderConnection (
    @Disposes @OrderConnection Connection connection)
    throws JMSException {
    connection.close();
    }

    @Produces @OrderSession
    public Session createOrderSession (
    @OrderConnection Connection connection) throws JMSException {
    return connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    }

    public void closeOrderSession(
    @Disposes @OrderSession Session session) throws JMSException {
    session.close();
    }

    @Produces @OrderMessageProducer
    public MessageProducer createOrderMessageProducer(
    @OrderSession Session session) throws JMSException {
    return session.createProducer(orderQueue);
    }

    public void closeOrderMessageProducer(
    @Disposes @OrderMessageProducer MessageProducer producer)
    throws JMSException {
    producer.close();
    }
    }

    The underlying order queue and connection factory is being injected into the JMS object factory via the Java EE 5 @Resource annotation. The methods annotated with @Produces are producer methods. The return values of these methods are made available for injection. When needed, you can apply qualifiers, scopes, names and stereotypes to these return values by applying annotations to the producer methods. In our example, we are applying the @OrderConnection, @OrderSession and @OrderMessageProducer qualifiers to the injectable JMS connections, sessions and message producers we are programmatically constructing. The produced objects belong to the default dependent scope.

    Very interestingly, you should note that producer methods can request injected objects themselves through their method parameters. For example, when the container creates an order session by invoking the createOrderSession method, it sees that the method needs a JMS connection qualified with the @OrderConnection qualifier. It then resolves this dependency by invoking the createOrderConnection producer method. The createOrderMessageProducer producer method is similarly dependent on the createOrderSession producer.

    On the other side of the equation any method with a parameter decorated with the @Disposes annotation signifies a disposer. In the example, we have three disposers disposing of JMS connections, sessions and message producers qualified with the @OrderConnection, @OrderSession and @OrderMessageProducer qualifiers. Just as producer methods are called into action as the objects they produce are needed, the disposer associated with an object is called when the object goes out of scope. For the interest of readability, all disposers must belong in the same bean as their matching producer methods.

    Having covered some of the mechanical syntax details, let's now take a step back and look at the example from a functional standpoint. When the order service needs the injected order session and message producer, the associated producer methods are invoked by CDI. In the course of creating the session and message producer, CDI also creates the JMS connection, since it is a declared dependency for the producer methods. The producer methods utilize the underlying queue and connection factory injected into our JMS object factory as needed. All these injected objects are then cleaned up properly when they go out of scope.

    This example should demonstrate to you how the relatively simple concept of producers and disposers can be combined in innovative and powerful ways when you need it.

    Custom Scopes and Resource Factories
    Think about the implications of the example above. Because the JMS resources are in the dependent scope, they are tied to the life-cycle of the order service EJB. The service is a stateless session bean that is discarded from the object pool when not in use, along with the injected JMS resources. Now imagine that the service is a singleton or application scoped managed bean instead and is thus very long lived. This means that this code would cause the container to create and inject open connections/sessions that are not released for a while, potentially causing performance problems. Can you think of a way to solve this problem?

    Hint: one way to solve this is to use a custom @TransactionScoped or @ThreadScoped for the JMS resources. This is being considered for addition to the Resin container (as such, it is probably a good optimization even for the EJB case). Also under consideration: Adding generic JMS/JDBC abstractions based on CDI similar to the example as part of Resin that you can simply use out-of-the-box. Can you imagine how the JDBC abstraction might look like? Would it be useful to you?

    CDI producers and disposers support even more powerful constructs such as utilizing injection point meta-data, using producer fields, or using producers with Java EE resources and so on - you should check out the CDI specification for details (alternatively, feel free to check out the Weld reference guide that's a little more reader-friendly). Utilizing producers and scoped beans with JSF is particularly interesting and we will look at this in a later article focusing on CDI's interaction with JSF.

    To give you a taste of some of the more advanced features, let's look at a producer example using injection point meta-data. By using injection point meta-data in producers, you can get runtime information about where the object you are programmatically creating will be getting injected into. You can use this data in very interesting ways in your code. Here is an example that constructs and injects a custom logger into a service:

    @Stateless
    public class BidService {
    @Inject private Logger logger;
    ...
    }

    public class LoggerFactory {
    @Produces
    public Logger getLogger(InjectionPoint injectionPoint) {
    return Logger.getLogger(
    injectionPoint.getMember().getDeclaringClass().getSimpleName());
    }
    }

    As you can see from the example above, all you need to do to get access to injection point meta-data is include the InjectionPoint interface as a producer method parameter. When CDI invokes your producer, it will collect meta-data at the injection point (the logger instance variable in this case) and pass it to your producer. The injection point interface can tell you about the bean being injected, the member being injected, qualifiers applied at the injection point, the Java type at the injection point, any annotations applied and so on. In the example, we are creating a logger specific to the class that holds the logger using the name of the class that is the injection target.

    The injection point interface is actually part of the CDI SPI geared toward portable extensions, which we will discuss in a later article.

    OpenWebBeans Portable Extensions
    One of the goals of the Apache CDI implementation, OpenWebBeans, is to expose various popular Apache projects as CDI portable extensions. It's very likely you will see something similar to the logger example above as a CDI portable extension for Log4J (CDI portable extensions for Apache commons is probably very likely too).

    Naming Objects
    As we discussed, one of the primary characteristics of CDI is that dependency injection is completely type-safe and not dependent on character-based names that are prone to mistyping and cannot be checked via an IDE, for example. While this is great in Java code, beans would not be resolvable without a character-based name outside Java such as in JSP or Facelet markup. CDI bean name resolution in JSP or Facelets is done via EL. By default, CDI beans are not assigned any names and so are not resolvable via EL binding. To assign a bean a name, it must be annotated with @Named like so:

    @RequestScoped @Named
    public class Bid {
    ...
    }

    The default name of the bean is assigned to be "bid" - CamelCase with the first letter lower-cased. The bean would now be resolvable via EL binding as below:

    <h:inputText id="amount" value="#{bid.amount}"/>

    Similarly, objects created by producer methods are assigned the name of the method or the Java property name by default when the producer is annotated via @Named. The list of products produced in the example below is named "products", for instance:
    @Produces @ApplicationScoped @Named
    public List getProducts() { ... }
    You can most certainly override default names as needed as shown below:
    @Produces @ApplicationScoped @Catalog @Named("catalog")
    public List getProducts() { ... }

    @ConversationScoped @Named("cart")
    public class ShoppingCart {

    In most cases, you would likely not override bean names, unless overriding names improves readability in the context of JSP/Facelet EL binding.

    Names in Dependency Injection
    Technically, @Named is defined to be a qualifier by JSR 330. This means that you can use character-based names to resolve dependencies in JSR 299 if you really, really want to. However, this is discouraged in CDI and there are few good reasons to do it instead of using more type-safe Java based qualifiers (can you think of what the reasons might be?).

    Looking up CDI Beans
    While dependency injection is the way to go most of the time, there are some cases where you cannot rely on it. For example, you may not know the bean type/qualifier until runtime, it may be that there are simply are no beans that match a given bean type/qualifier or you may want to iterate over the beans which match a certain bean type/qualifier. The powerful CDI Instance construct allows for programmatic bean look-up in such cases. Let's see how this works via a few examples.

    In the simplest case, you may want to know about the existence of a bean with a certain type (let's say a Discount) because you are not certain if it was deployed given a particular system configuration. Here is how you can do it:
    @Inject private Instance discount;
    ...
    if (!discount.isUnsatisfied()) {
    Discount currentDiscount = discount.get();
    }

    In the example above, we are injecting the typed Instance for the discount bean. Note, this does not mean that the discount itself is injected, just that you can look-up discounts as needed via the typed Instance. When you need to query for the discount, you can check if it exists via the isUnsatisfied method. You can also check for ambiguous dependencies if you need to. If the discount was deployed, you can then actually get the resolved bean and use it. If you need to, you can apply qualifiers to an Instance. For example, you can look for a holiday discount as below:
    @Inject @Holiday private Instance discount;
    Now let's assume that there might be multiple matches for a particular bean type/qualifier - there is likely more than one discount, for example. You can handle this case by placing the @Any annotation on an Instance as below and iterating over all the matches:
    @Inject @Any private Instance anyDiscount;
    ...
    for (Discount discount: anyDiscount) {
    // Use the discount...
    }

    Note that Instance is an Iterable as a convenience, which is why the abbreviated foreach loop syntax above works. If needed, you can narrow down the matches by qualifier and/or sub-type at runtime. This is how you could filter by qualifier:
    @Inject @Any private Instance anyDiscount;
    ...
    Annotation qualifier = holiday ? new Holiday() : new Standard();
    Discount discount = anyDiscount.select(qualifier).get();


    The select method allows you to narrow down the potential discount matches by taking one or more qualifiers as arguments. If it's a holiday, you would be interested in holiday discounts instead of standard discounts in the example code. You can also pass a bean sub-type to the select method as below:
    Instance sellerDiscount =
    anyDiscount.select(SellerDiscount.class, new Standard());

    There is much more to the Instance construct that you should definitely check out by taking a look at the CDI specification itself (or the Weld reference guide). You can also use the CDI SPI intended for creating portable extensions to look up beans in a more generic fashion. We will cover portable extensions in a future article in the series.

    Tuesday, January 19, 2010

    JAX-WS Implementations

    There are multiple APIs for the Java platform, e.g. for database access or web applications. The developer has to code against a standard not against a product. The particular tools and servers stay replaceable. For example a web application can be operated with both the Application Server IBM Web Sphere and the Web Container Apache Tomcat. Due to the standardization by the Java Enterprise Edition the exchange of a server can be done with little effort.

    Unfortunately, Web Services are a different story. Indeed there is the JAX-WS specification, but there are still too many unanswered questions as well as alternative approaches of applying Web Services. Which SOAP implementation is suitable depends on the requirements and the environment. The sections below are describing the tools and standards that are available for developers of Web Services.

    Apache Axis2
    Axis 2 is the follow-up of the popular Axis1 framework. Axis2 is based on a completely new architecture and has been re-developed from scratch.

    The deployment of services for Axis 1 has often been criticized. Therefore Axis 2 has a completely new deployment model. An Axis 2 runtime is a Web application and can be installed on every JEE compliant Application Server. The Axis 2 web application itself is a container for Web Services now. Web Services are packed into an own file format with the file extension aar. Due to these archives, Web Services can be installed and configured by a simple user interface at run time. In Axis 2 the services can be configured by the traditional deployment descriptors, e.g. the file services.xml.

    Modules providing additional functionality, for example WS-* standard support, can also be installed during runtime. A Web Service is regarded as an independent package which can be installed into the Axis 2 runtime environment.

    Writing an Axis 2 project requires a lot of knowledge about the build tool Ant. Knowledge about the build tool is essential to write an Axis 2 project. For example the WSDL2JAVA task is generating a temporary project including a build-file. Then the projects build-file has to call the generated build-file. If a Web Service uses a library, e.g. a JDBC driver, then the library has to be copied into the generated project using Ant on each build. So development with Axis 2 will be very difficult if you are not familiar with Ant.

    Apache CXF
    CXF is also a project of the Apache software foundation. CXF came up from a fusion of the XFire and Ionas Celtix projects.

    CXF was developed with the intention to integrate it into other systems. This is reflected in CXF API and the use of the Spring framework. Therefore it is very simple to integrate CXF into existing systems.

    CXF respectively its predecessor XFire was integrated into numerous open and closed source projects like ServiceMix or Mule.

    A proprietary API as well as the standardized JAX-WS interface are available for the development and use of Web Services.

    JAX-WS
    The Java API for XML based Web Services is the successor of the JAX-RPC specification. JAX-WS respectively its predecessor is message based and supports asynchronous communication. The Configuration is managed by annotations therefore Java 5 or higher is required. JAX-WS isn't downwardly compatible to its predecessor JAX-RPC. With JAX-WS it is pretty easy to write and consume Web Services. The default values of numerous parameters are comfortable for the programmer, so that simple Pojos declared with a @WebService annotation can be used as a Service. Listing 1 shows a simple implementation of a Web Service using the @WebService annotation.

    import javax.jws.WebService;
    import javax.jws.WebMethod;

    @WebService
    public class HelloWorldService {

    public String helloWorld() {
    return "Hello World!";
    }
    }

    Listing 1: HelloWorld Web Service using JAX-WS

    A suitable WSDL document can also be generated from the class. Other annotations can concertedly exert influence of the WSDL document. For example other namespaces or element names can be used. If JAXB is already known, its annotations can be used to define the serialization in every detail. With the contract first approach a Service Interface, JAXB annotated classes for serialization and a skeleton for the implementation can be generated. According to the WSDL document the generated classes can have numerous annotations. Annotations are also the main point of criticism of JAX-WS. Despite this criticism the JAX-WS specification came out well. It is well attuned and combinable with other Java and Java EE specifications. For example, Listing 2 shows a stateless EJB 3.0 Bean which acts as a Web Service at the same time.

    @WebService
    @Stateless
    public class MyService{
    public String hello(String name) {
    return "Hallo"+name;
    }
    }

    Listing 2: Stateless SessionBean acting as Web Service

    JAX-WS Reference Implementation
    The JAX-WS Reference Implementation represents the core piece of the Web Services protocol stack Metro. The Metro Stack provides support for the following Web Services standards:

    WS-Addressing
    WS-Policy
    Web Services Security aka WS-Security
    WS-Transaction
    WS-Reliable Messaging
    WS-Trust
    WS-SecureConversation

    Metro is documented in detail. Apart from the JAX-WS, JAXB and JWS specifications there are numerous tutorials und samples. The Netbeans IDE as well as the tutorials of the enterprise pack makes it particularly easy to get started. Of course, Eclipse can also be used for the development with Metro.

    Web applications containing Web Services which have been realized with JAX-WS are executable in the Glassfish Application Server. To make services also executable in other application servers, two libraries (JAX-WS and JAXB) have to be installed. Application servers such as JBoss, WebSphere or Tomcat can be upgraded with JAX-WS within about 10 minutes.

    Performance
    Due to the modern streaming XML parser, the performance of all three SOAP engines is very well. The ping time for a locale roundtrip is about 2-4 milliseconds (message size about 3KB, Dual Core Notebook). Therefore the time delay by the SOAP communication is negligible in many projects.

    WS-* Standards
    The support of the WS-Standard family can also be decisive for the selection of a SOAP engine. For example, messages sent to services can be secured with signatures as described in the Web Service Security standard (in short WSS). Table 1 shows the support for WS*-Standards of the toolkits.

    Conclusion
    None of the Web Services frameworks is in general superior to the others. Axis 2 is structured modularly, has many features and can be used as an application server for Web Services. A special feature of Axis 2 is the support of removable binding frameworks, for example XMLBeans. Axis 2 together with the XMLBeans framework included is well suited for Web Services which are using very complex schema definitions. The disadvantages of Axis 2 are its complexity as well as the insufficient JAX-WS support. Therefore anyone who wants to work with JAX-WS should choose Apache CXF or the reference implementation.

    Those who prefer a seamless integration with the Spring framework are well advised with the JAX-WS implementation. Furthermore CXF is slim and easy to use. CXF is the tool of choice if a SOAP engine has to be embedded into an existing software.

    Who just wants to code against the standard is well advised with the JAX-WS implementation. The enterprise pack of the Netbeans development environment supports JAX-WS RI very well. Only a few clicks are needed to build a server or to call a Web Service.

    I hope this article could help you with the decision for a WS toolkit.

    StandardsAxis2CXFJAX-WS/Metro
    WS-AddressingXXX
    WS-CoordinationX(2)X
    WS-MetadataExchangeX
    WS-PolicyXXX
    WS-ReliableMessagingX(3)XX
    Web Services SecurityX(1)X(4)X
    WS-SecureConversationX(1)X
    WS-SecurityPolicyX
    WS-TransactionX(2)X
    WS-TrustXX
    WS-Federation

    Table 1: Support for WS-* Standards (stand: Juli 2008)

    (1) Supported by the additional module Apache Rampart
    (2) Supported by the additional module Apache Kandula2
    (3) Supported by the additional module Apache Sandesha2
    (4) By Apache WSS4J Interceptor

    JAX-RCP vs JAX-WS

    JAX-RPC
    A specification/API for Java developers to develop SOAP based interoperable web services. This API is now obsolete, and may be dropped from the next JEE version.

    JAX-WS
    The successor to JAX-RPC. It requires Java 5.0, and is not backwards-compatible to JAX-RPC. This article describes the high-level differences to JAX-RPC.

    SAAJ
    Another specification/API for using SOAP envelopes with or without attachments. It operates on a lower level than JAX-RPC or JAX-WS, both of which will use SOAP envelopes based on SAAJ if needed.

    JAX-RPC 2.0 (Java API for XML Based RPC) has been renamed to JAX-WS 2.0 (Java API for XML Web Services).

    This was done for a number of reasons, but the main reasons are:
    The JAX-RPC name is misleading, developers assume that all JAX-RPC is about is just RPC, not Web Services.

    By renaming JAX-RPC to JAX-WS we can eliminate this confusion. JAX-RPC 2.0 uses JAXB for all databinding.

    As the bindings are different in JAX-RPC 1.1, it introduced a number of source compatibility issues. The migration from JAX-RPC 1.1 to JAX-RPC 2.0 is not cookie cutter as generated Java code and schemas will be different than those generated by JAX-RPC 1.1.

    Although the renaming does not ease this migration, it does let the developer know that these are two separate technologies, hence the more difficult migration is more palatable.

    Maintaining binary compatibility with the JAX-RPC 1.1 APIs, was hindering our goal of ease-of-development. Because we had this binary compatibility requirement, many legacy APIs were exposed such as the various methods on javax.xml.rpc.Service and the javax.xml.rpc.Call. Having these legacy APIs around would confuse developers. By renaming JAX-RPC 2.0 to JAX-WS 2.0 we no longer have this binary compatibility requirement and we can rid the APIs of these legacy methods and interfaces and we can focus on a new set of APIs that are easier to understand and use.

    WebService Implementations
    Apache Axis
    An open source implementation of the Java WS APIs for sending and receiving SOAP messages. Axis 1 supports JAX-RPC and SAAJ, while Axis 2 supports SAAJ and JAX-WS.

    Apache SOAP
    The first SOAP implementation. It is now obsolete. It's better to use Apache Axis to avail oneself of the latest features.

    Sun JWSDP
    Sun Java Webservices Developer Pack, is an implementation of JAX-RPC, SAAJ and various other XML Java technologies. It is now deprecated in favor of GlassFish.

    Metro
    The web services stack used in GlassFish?. It supports SAAJ, JAX-WS, WS-Security and other standards.

    JAX-RS
    It is a Java API for RESTful web services.
    Jersey is the reference implementation of the JAX-RS API, as defined in the JSR-311 standard for RESTful web services.

    For more info, see http://faq.javaranch.com/java/WebServicesFaq.

    Friday, January 15, 2010

    Who is the best JPA Provider in WebLogic?

    http://www.theserverside.com/news/thread.tss?thread_id=44219

    Posted by: Gavin King on February 10, 2007 in response to Message #227266
    And by the way - I'm a bit out of date, but the actual measurements I did a year or so ago of simple CRUD performance of Hibernate vs. Kodo gave a mixed bag of results. They are slightly faster on creation/destruction of the persistence context and on inserts, we are a bit faster on queries. For mass operations on many objects, they are faster if you use standard APIs, we are quicker if you use StatelessSession. Etc.

    Nowhere did I find anything that was a big enough difference that you would prefer one product over the other on the basis of performance alone.

    Which confirmed to me that the BEA marketing line of the time that "Kodo is faster than Hibernate" is just the usual marketing BS, which was my initial reaction.

    Thursday, January 14, 2010

    EJB3 Weblogic 10 and backward compability

    (http://blog.sunfire.nu/2008/12/ejb3-weblogic-10-and-backward.html)

    Been trying to develop EJB3s that will be hosted on a Weblogic 10 server, and some client applications that will be running on Weblogic 8.
    Took me a while to figure out how to get the JDNI names and stuff right for the EJBs as well as how to be compatible with EJB2 spec (since Weblogic 8 and JDK1.4 doesn't support EJB3).

    There are of course a million tutorials and examples to find using google, so that's were I started. Found one here to start with but I ended up getting ClassCastExceptions. Looking at the EJB3 specs I found the mappedName attribute of the @Stateless annotation, and after setting that I got my client code working. Since mappedName is vendor-specific the information will not be applicable if you're running a different application server.

    package ejb;
    public interface TestRemote {
    public String echo(String s);
    }
    ----------------------
    package ejb;
    import javax.ejb.*;

    @Stateless(mappedName="Base")
    @Remote(TestRemote.class)
    public class TestBean implements TestRemote {
    public String echo(final String s) {
    return "echo: " + s;
    }
    }

    The clients can now perform a lookup like this:

    Properties p = new Properties();
    p.put("java.naming.factory.initial","weblogic.jndi.WLInitialContextFactory");
    p.put("java.naming.provider.url", "t3://localhost:7001");
    p.put("java.naming.security.principal", "weblogic");
    p.put("java.naming.security.credentials", "weblogic");
    InitialContext ctx = new InitialContext(p);
    TestRemote test = (TestRemote) ctx.lookup("Base#ejb.TestRemote");
    test.echo("Hello");

    After getting my clients to access the EJB3s (the clients were using WLS10 libraries and JDK6) and calling methods on them I moved on to get them to work with WLS8 clients.
    This turned out to involve a little more effort, suddenly it wasn't enough to write POJOs and annotations.
    First of all, we need to create a EJB2 equivivalent business interface for our EJB3 interface (TestRemote) that must extend javax.ejb.EJBObject and contain the same methods that must throw java.rmi.RemoteException.

    package ejb;
    public interface TestRemote2 extends javax.ejb.EJBObject {
    public String echo(String s) throws java.rmi.RemoteException;
    }

    Second, we need a Home interface that the EJB2 client can lookup and use to create the EJB:

    package ejb;
    import java.rmi.RemoteException;
    import javax.ejb.*;
    public interface TestRemoteHome extends EJBHome {
    public TestRemote2 create() throws CreateException, RemoteException;
    }

    Notice that the create method returns the EJB2 interface (of course...).
    Finally, we update the bean class itself:

    package ejb;

    import javax.ejb.*;

    @Stateless(mappedName="Base")
    @Remote(TestRemote2.class)
    @RemoteHome(TestRemoteHome.class)
    public class TestBean implements TestRemote {
    public String echo(final String s) {
    return "echo: " + s;
    }
    }

    Ok, we changed the Remote annotation to contain the EJB2 interface instead and we added the RemoteHome annotation as well to specify the Home interface to publish. Notice that we still implement TestRemote (not the EJB2 interface) so at least we don't have to worry about RemoteExceptions here.

    The client code looks like this:

    // Context setup as before
    Object o = ctx.lookup("Base#ejb.TestRemoteHome");
    TestRemoteHome home = (TestRemoteHome)PortableRemoteObject.
    narrow(ctx.lookup("Base#ejb.TestRemoteHome"),
    TestRemoteHome.class);
    TestRemote21 test = home.create();
    test.echo("Hello");

    That's all there is to it.

    Update after comments:
    To enable both EJB3 and EJB2 beans you just add the interfaces in the @Remote annotation like this:
    @Remote({TestRemote2.class, TestRemote.class})

    Why use ejb-ref in web.xml?

    The advantage is indirection. If the code directly references EJBs in your servlets through JNDI, it will work just when the JNDI name does not be changed during deployment.

    By using an ejb-ref you create an alias for the bean. During coding, the alias is used to locate the beans home.

    eg. context.lookup("java:comp/env/ejb/myBean");

    The developer also creates an entry in the web.xml like this:

    EJB remote reference:
    <ejb-ref>
    <ejb-ref-name>ejb/myBean</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <ejb-ref-home>some.package.MyBeanHome</ejb-ref-home>
    <ejb-ref-remote>some.package.MyBeanRemote</ejb-ref-remote>
    <ejb-link>MyAppEJB.jar#myBean</ejb-link>
    </ejb-ref>
    EJB local reference:
    <ejb-local-ref>
    <ejb-ref-name>ejb/myBean</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local>com.myapp.session.MyBeanLocal</local>
    <ejb-link>MyAppEJB.jar#myBean</ejb-link>
    </ejb-local-ref>




    On deployment, the deployer creates a mapping between the alias ejb/myBean and the JNDI name that the bean is actually deployed with. This will allows the deployer to change a beans' JNDI name without modifying the code (If you used JNDI directly, you have to modify it).

    The name referenced in the ejb-link (in this example, myBean) corresponds to the <ejb-name> element of the referenced EJB's descriptor. With the addition of the <ejb-link> syntax, the <ejb-reference-description> element is no longer required if the EJB being used is in the same application as the servlet or JSP that is using the EJB.

    In WebLogic, since the JAR path is relative to the WAR file, it begins with "../". Also, if the ejbname is unique across the application, the JAR path may be dropped and just put the bean name at there.

    Mapping is vendor specific feature. For example, in WebLogic this is done in the weblogic.xml file.

    Friday, January 08, 2010

    How to get the JNDI of EJB in WebLogic 10g R3

    If you want to the EJB accessible from general classes instead of managed beans, you have to let it can be searchable in JNDI tree. But you can not get the JNDI if you didn't set the mappedName in WebLogic 10g R3.

    A sample:

    @Stateless ( name="UserBean", mappedName="ejb.User")
    public class UserBean implements UserLocal, UserRemote {
    }


    After you deployed it in Webglogic 10, you can get access to the remote interface with:

    String JNDI_NAME = "ejb.User#" + UserRemote.class.getName();
    UserRemote user = (UserRemote) new InitialContext().lookup(JNDI_NAME);

    New features in JEE 6

    JEE 6 new features:
    profiles, pruning, and extensibility
    Enterprise JavaBeans (EJB), Java Servlet, and Java Persistence API (JPA)
    new APIs/technologies: Java API for RESTful Web Services (JAX-RS) and Java Contexts and Dependency Injection (JCDI/Web Beans)

  • Extensibility: This mechanism provides a way to include additional technologies and frameworks that are not part of the standard platform.

  • Profiles: This build on the standard Java EE platform technologies, sometimes using only a subset of those technologies, and sometimes adding Java technologies that are not part of the standard platform.

  • Pruning: Pruning provides a way to remove some technologies from the platform.


  • Enterprise JavaBeans 3.1
  • Removal of local business interface: EJB 3.0 removed the complex home and remote interfaces and made way for the plain old Java interface (POJI). EJB 3.1 goes one step further by dictating that business interfaces also are not mandatory.


  • @Stateless
    public class StockQuoteBean {...}

  • Introduction of Singleton beans: The concept of Singleton beans was introduced primarily to share application-wide data and support concurrent access. All Singleton beans are transactional and thread safe by default, making way for flexible concurrency options. Java EE 6 also introduces concurrency annotations to perform locked read/write operations on getter and setter methods.


  • @Singleton
    @Startup
    public class CounterBean {
    private int count;
    @PostConstruct
    public void initialize() {
    count=5;
    }
    }

  • Packaging EJB components directly in a WAR file: One of the major advancements in EJB 3.1 is the option for including EJB in a WAR file directly instead of creating a separate JAR file.

  • Embeddable API for executing EJB in Java SE environment: The idea behind this feature is to allow EJBs to run in Java SE environments; that is, the client and the EJB run in the same JVM. The javax.ejb.EJBContainer class represents an embeddable container. Embeddable containers support EJB Lite.

  • Asynchronous Session Bean: A session bean can support asynchronous method invocations. Bean methods annotated with @Asynchronous are invoked asynchronously. Asynchronous methods can return a Future object of the java.util.concurrent API. This will be useful for the client to get the status of the invocation, retrieve the return value of a method, check for an exception, or even cancel the invocation.

  • EJB Lite: The concept of profiles is applied to the EJB specification as well. Many enterprise applications do not require the complete set of features in EJB, so EJB Lite, a minimal subset of the EJB API, is introduced in EJB 3.1. EJB Lite provides vendors the option to implement a subset of the EJB APIs within their products. Applications created with EJB Lite can be deployed on any server that supports EJB technology, irrespective of whether it is full EJB or EJB Lite.


  • EJB Lite has the following subset of the EJB API:
    * Session bean components (Stateless, stateful, singleton session beans)
    * Supports only synchronous invocation
    * Container-managed and bean-managed transactions
    * Declarative and programmatic security
    * Interceptors
    * Support for deployment descriptor (ejb-jar.xml)



    Servlet 3.0 will introduce are:
  • Support for Annotations: Instead of making an entry in a deployment descriptor (web.xml), developers can use annotations to mark a servlet.

  • @WebServlet is used to mark a class that extends HttpServlet as a servlet.
    @WebFilter is used to mark a class that implements Filter as a filter
    @WebInitParam is used to specify an init parameter
    @WebListener is used to specify a listener

    @WebServlet("/stockquote")
    public class StockQuoteServlet extends HttpServlet {...}

    @WebServlet(name="StockQuoteServlet", urlPatterns={"/stockquote","/getQuote"})
    public class StockQuoteServlet extends HttpServlet {...}

    @WebFilter("/login")
    public class LoginFilter implements Filter {...}

  • Web fragments: Web fragments are meant to provide modularity. They provide logical partitioning of the deployment descriptor web.xml so that frameworks such as Struts and JavaServer Faces (JSF) can have their own piece of information added in the JAR file, and the developer doesn't have to edit web.xml.

    Web fragments are identified by using web-fragment as the root element. Developers can use all the elements in the deployment descriptor. The only condition is that the root element must be and hence have the name web-fragment.xml. This element is typically placed in the WEB-INF\lib folder. Any JAR file placed in the WEB-INF\lib folder can include the web fragment.

    When an application has multiple web fragments, the order of execution can be resolved using absolute ordering or relative ordering. In both cases, XML tags are used to identify the order. Absolute ordering is specified using in web.xml and relative ordering is specified using in web-fragment.xml.

    When the element is not mentioned or set to false in the deployment descriptor, the container skips processing web.xml and processes annotations and web fragments. If is set to true, then the container skips processing annotations and web fragments and processes based on the information available in web.xml, because this takes precedence.

  • Asynchronous processing: Servlets allow asynchronous processing in Java EE 6 to support AJAX. A servlet often has to wait for a response from a resource such as a database or a message connection. Asynchronous processing avoids the blocking request so that the thread can return and perform some other operation. Developers can mark servlets as asynchronous by setting the value true to the asyncSupported attribute of the @WebServlet or @WebFilter annotation. In addition to the annotation, some new APIs such as AsyncContext have been introduced, and methods such as startAsync have been added to the ServletRequest and ServletResponse classes.


  • JAX-RS 1.1 and JCDI 1.0
  • JAX-RS fully supports REST principles, and provides POJO resources to which developers can add annotations to make them support REST. Due to the nature of HTTP, JAX-RS supports only stateless interactions. Sun provides a reference implementation for JAX-RS codenamed Jersey.

  • JCDI allows developers to bind Java EE components to lifecycle contexts, to inject these components, and to enable them to support loosely coupled communication.
  • Contexts and Dependency Injection for Java EE (CDI) - Part 1

    (See details: http://www.theserverside.com/tt/articles/content/DependencyInjectioninJavaEE6/article.html)
    Contexts and Dependency Injection for Java EE (CDI) - JSR 299.
    Leader: Gavin King

    CDI is the de-facto API for comprehensive next-generation type-safe dependency injection for Java EE, which aims to synthesize the best-of-breed dependency injection features from solutions like Seam, Guice and Spring while adding many useful innovations of its own.

    Java EE 5
    What you can do is:
  • Injecting container resources such as JMS connection factories, data sources, queues, JPA entity managers, entity manager factories and EJBs via the @Resource, @PersistenceContext, @PersistenceUnit and @EJB annotations into Servlets, JSF backing beans and other EJBs.


  • What you could not is:
  • Injecting EJBs into Struts Actions or JUnit tests and you could not inject DAOs or helper classes that were not written as EJBs because they do not necessarily need to be transactional.

  • More broadly, it was difficult to integrate third-party/in-house APIs or use Java EE 5 as a basis to build such APIs that are not just strictly business components.


  • CDI is designed to solve in a highly type-safe, consistent and portable way that fits the Java philosophy well.

    Comparison with existing technologies.
  • Spring IoC - CDI is likely to feel more type-safe, futuristic and annotation-driven.

  • Seam - CDI has a lot more advanced features.

  • Guice - CDI is perhaps more geared towards enterprise development than it.


  • CDI enhances the Java EE programming model in two more important ways - both of which come from Seam.
  • First, it allows you to use EJBs directly as JSF backing beans.

  • Second, CDI allows you to manage the scope, state, life-cycle and context for objects in a much more declarative fashion, rather than the programmatic way most web-oriented frameworks handle managing objects in the request, session and application scopes.


  • CDI has no component model of its own but is really a set of services that are consumed by Java EE components such as managed beans, Servlets and EJBs.

    Managed beans are a key concept introduced in Java EE 6 to solve some of the limitations when using Java EE 5 style resource injection.

    A managed bean is just a bare Java object in a Java EE environment. Other than Java object semantics, it has a well-defined create/destroy life-cycle that you can get callbacks for via the @PostConstruct and @PreDestroy annotations. Managed beans can be explicitly denoted via the @ManagedBean annotation, but this IS NOT ALWAYS needed, especially with CDI. From a CDI perspective, this means that almost any Java object can be treated as managed beans and so can be full participants in dependency injection.

    Traditional JSF backing beans are now managed beans.
    All EJB session beans are now also redefined to be managed beans with additional services (thread-safety and transactions by default).

    Servlets are NOT yet redefined to be managed beans.

    CDI also integrates with JSF via EL bean name resolution from view technologies like Facelets and JSP as well as automatic scope management.

    CDI's integration with JPA consists of honoring the @PersistenceContext and @PersistenceUnit injection annotations, in addition to @EJB and @Resource.

    Note
    CDI DOES NOT directly support business component services such as transactions, security, remoting, messaging and the like that are in the scope of the EJB specification.

    JSR 299 utilizes the Dependency Injection for Java (JSR 330) specification as its foundational API, primarily by using JSR 330 annotations such as @Inject, @Qualifier and @ScopeType. Led by Rod Johnson and Bob Lee, JSR 330 defines a minimalistic API for dependency injection solutions and is primarily geared towards non-Java EE environments.

    CDI essentially adapts JSR 330 for Java EE environments while also adding a number of additional features useful for enterprise applications.



    Dependency Injection Basics


    @Stateless
    public class BidService {
    @Inject
    private BidDao bidDao;

    public void addBid (Bid bid) {
    bidDao.addBid(bid);
    }
    }

    public class DefaultBidDao implements BidDao {
    @PersistenceContext
    private EntityManager entityManager;

    public void addBid (Bid bid) {
    entityManager.persist(bid);
    }
    }

    public interface BidDao {
    public void addBid (Bid bid);
    }


    The bid DAO managed bean is being injected into the bid service EJB session bean via the @Inject annotation. CDI resolves the dependency by looking for any class that implement the BidDao interface. When CDI finds the DefaultBidDao implementation, it instantiates it, resolves any dependencies it has (like the JPA entity manager injected via @PersistenceContext) and injects it into the EJB bid service. Since no explicit bean scope is specified for either the service or the DAO, they are assumed to be in the implicit dependent scope.

    Qualifiers are additional pieces of meta-data that narrow down a particular class when more than one candidate for injection exists.

    @Stateless
    public class BidService {
    @Inject @JdbcDao
    private BidDao bidDao;
    ...
    }

    @JdbcDao
    public class LegacyBidDao implements BidDao {
    @Resource(name="jdbc/ActionBazaarDB")
    private DataSource dataSource;
    ...
    }


    Context Management Basics

    Every object managed by CDI has a well-defined scope and life-cycle that is bound to a specific context. As CDI encounters a request to inject/access an object, it looks to retrieve it from the context matching the scope declared for the object. If the object is not already in the context, CDI will get reference to it and put it into the context as it passes the reference to the target. When the scope corresponding to the context expires, all objects in the context are removed.

    Available Scope Definition
    Dependent, ApplicationScoped, RequestScoped, SessionScoped, ConversationScoped

    Besides the built-in scopes above, it is also possible to create custom scopes via the @Scope annotation

    @Named
    @RequestScoped
    public class BidManager {
    @Inject
    private BidService bidService;
    ...
    }

    @Stateless
    public class BidService {
    @Inject
    private BidDao bidDao;

    @Inject
    private BiddingRules biddingRules;
    ...
    }

    @ApplicationScoped
    public class DefaultBiddingRules implements BiddingRules {
    ...
    }


    @Named annotation makes the bid manager accessible from EL.



    JSR 330 defines a minimalistic API for dependency injection solutions and is primarily geared towards non-Java EE environments. In particular, it does not define scope types common in server-side Java such as request, session and conversation. It also does not define specific integration semantics with Java EE APIs like JPA, EJB and JSF.

    Thursday, January 07, 2010

    Performance monitoring for web applications

    MessAdmin is a light-weight and non-intrusive tool for monitoring and interacting with Java HttpSession. MessAdmin can be added to any J2EE application, with zero change to the monitored application!


    ZK's performance meter utility provides developers with the means to determine execution times in different stages of an Ajax request and response cycle.
    Sam Chuang illustrates his implementation of a ZK performance monitor here: http://docs.zkoss.org/wiki/A_ZK_Performance_Monitor.

    What Is The Relation Between JSR-299 and JSR-330 In Java EE 6?

    http://java.dzone.com/articles/what-relation-betwe-there

    JSR-330 (Dependency Injection for Java) led by Rod Johnson (SpringSource) and Bob Lee (Google Inc.) became a part of Java EE 6. JSR-330 is very simplistic. It comes with own few annotations from the package: javax.inject. The package contains the following elements: Inject, Qualifier, Scope, Singleton, Named and Provider. Its the definition of the basic dependency injection semantics.

    JSR-299 (Java Contexts and Dependency Injection), with Gavin King as lead, uses JSR-330 as base and enhances it significantly with modularization, cross cutting aspects (decorators, interceptors), custom scopes, or type safe injection capabilities. JSR-299 is layered on top of JSR-330.

    It is amusing to see that the built-in qualifier @Named is not recommended and should be used only for integration with legacy code:

    "The use of @Named as an injection point qualifier is not recommended, except in the case of integration with legacy code that uses string-based names to identify beans."
    [3.11 The qualifier @Named at injection points, JSR-299 Spec, Page 32]

    The relation between JSR-299 and JSR-330 is comparable to the relation between JPA and JDBC. JPA uses internally JDBC, but you can still use JDBC without JPA. In Java EE 6 you can just use JSR-330 for basic stuff, and enhance it on demand with JSR-299. There is almost no overlap in the practice. You can even mix JSR-299 / JSR-330 with EJB 3.1 - to streamline your application.

    Friday, December 18, 2009

    JBoss Riftsaw - Open Source BPEL

    Riftsaw supports short-lived and long-running process executions, process persistence and recovery, process versioning, JBoss deployment architecture enabling hot deployment of your BPEL processes and integration with JBossESB and UDDI using jUDDI. An Eclipse-based BPEL designer is bundled with JBossTools 3.1.

    Riftsaw is based on Apache Ode, and adds support to run on any JAX-WS compliant WebServices stack and it ships with a new GWT based Admin console.

    From BPEL to the ESB and Back - Introduction to the Riftsaw-JBoss ESB Integration

    jBPM goes BPMN!

    http://www.jorambarrez.be/blog/2009/12/04/jbpm-goes-bpmn/

    What is BPMN2?
    Basically, the Business Process Modeling Notation (BPMN) started out a pure graphical notation standard for business processes, maintained by the Object Management Group (OMG). Version 2.0, which currently is in beta, adds execution semantics to the specification and this is of course where it gets interesting for jBPM.

    The primary benefit of BPMN2 is that it is a standard accepted by the IT industry, which means that process models become portable (graphical and execution-wise) across process engines such as jBPM. Since process executions are the raison-d-ĂȘtre of jBPM, it is only natural we are now investing in BPMN2. People who are familiar with JPDL (the current native language of jBPM) will have generally no difficulties in learning the BPMN2 language, as many constructs and concepts are shared. In fact, from a high-level point of view, BPMN2 and JPDL are in concept solving the same problem

    What is different jBPM and Riftsaw?

    Riftsaw is based up-on Apache ODE and there is no BPEL engine available on top of the PVM(Process Virtual Machine). There is no BPEL in jBPM4 anymore. There is just jPDL and BPMN2 which is still in development.

    jBPM3 BPEL is a BPEL 1.x implementation while Riftsaw is a BPEL 2.0 implementation.

    SCA Spring in Weblogic 10.3.2 & Soa Suite 11g

    Are you ready for SCA? Currently, the SCA is much more popular. The follow links are a introduction of SCA Spring on WebLogic 10g.

    SCA Spring in Weblogic 10.3.2 & Soa Suite 11g
    SCA Spring in Weblogic 10.3.2 & Soa Suite 11g Part 2