Tuesday, April 29, 2008

EJB 3 In Action Code Examples on WebLogic 10

In my previous blog, I made the code examples available for first four chapters of EJB 3 In Action for WebLogic 10. However I did not provide you instructions to run these examples (Chapter 2-4) for WebLogic 10.

Chapter 2 example has a stateless session bean, stateful session bean, an MDB and a JPA Entity. The JPA persistence unit requires a JDBC DataSource and the Stateful/MDB uses a JMS queue.

Chapter 3 depends upon a JDBC DataSource and Chapter 4 uses JDBC DataSource and a JMS Queue.

I’ve provided a build script to configure these resources on the default examplesServer that gets created when you install WebLogic 10.

  1. Download examples from here and unzip to a directory say c:\ejb3inaction\weblogic
  1. Set the environment variables for your server as follows:

%BEA_HOME%/wlserver_10.0/samples/domains/wl_server/setExamplesEnv

  1. Change to your directory to the directory

cd c:\ejb3inaction\weblogic

ant CreateResources

This will configure resources such as JDBC DataSource, JMS Connection Factory, Queues, etc.

4. To deploy the application, you can use WLS Admin Console. If you prefer you can use ant to deploy the application for a specific chapter.

cd chapter2
ant

  1. To run the application client:

ant run

Hope this helps! I'm working on porting rest of the examples and will make these available sooner.

Thursday, April 17, 2008

Diagnosing Production Java applications with AD4J

One of my applications that uses EJB 3 and JPA was running much slower today and I had no clue what was going on. It is a very simple application to manage service requests. When I was trying to update some data for a service request – it was taking ever. Also searching of service requests by some search criteria was taking much longer than it does.

So I thought I would give Oracle AD4J a spin and will try to find out what is going! It is good that Oracle AD4J does not require any code changes in application, because it does not use byte code instrumentation. Nor does it require to restart/redeploy the application – so it was a perfect fit.

And it really helped diagnose the problem by me get into bottom of the issues. It was indeed a DB issue as I had initially suspected.

I will not bore you with installation and configuration steps of AD4J – rather I will outline how AD4J helped me diagnose the issue.

Finding the Offending Thread

As soon as I logon to AD4J console and clicked to view active threads – it showed all threads with the correct state and I saw one thread is with status “DBWait”.





That gave me an indication that something going fishy in the database request from from JPA provider.

Finding DB issue

When I clicked on DB Wait link to view details, it became clear that the transaction is running into some row lock contention with another user session.




Finding the SQL statement

Interestingly it allowed to me to view the SQL Statement that is taking forever by clicking the SQL hash. My application uses JPA 1.0 and I could view the SQL statements causing problem without increasing the log level from my JPA provider as in the following figure:

It also helped me find the other session that held the lock. Apparently we found that it was a batch process that was hanging for some reasons. After the hanging session was killed the application ran like a champ again!

Also I found that the JPQL query for retrieving SRs was running slower because of some missing indexes on the column and it was making a full table scan. Nice, it also AD4J allows to run explain for sql statements.

Downloading AD4J

You can download AD4J from OTN (http://www.oracle.com/technology/software/products/oem/htdocs/jade.html)

Installing AD4J Console and agents

Installing AD4J Console is easy. You can follow this guide to do this installation of AD4J Console and agent.

After you deploy the agent you are good to go. Your JVM for application server will be automatically discovered in the console.

The AD4J agent is a WAR file that needs to be deployed to the server. You can follow the instructions in the install guide to install the agent in favorite application server. I was using my favorite container OC4J, however it supports BEA WebLogic, IBM Websphere, JBoss, and Tomcat. You can run AD4J also with standalone Java.

If you want to trace the problem to the DB tier you can install the DB Agent. You can follow the instructions in this guide.

I will play around with AD4J and blog little more about its feature in future. In the meantime you can review it's usage scenario documented in here.

Tuesday, April 15, 2008

Monday, March 31, 2008

Using JMX to Start/Stop Message Driven Bean

OC4J 10.1.3.x allows users to start/stop MDBs dynamically without having recycle container or application.

For example, you can disable an MDB upon start/deployment by adding enabled="false" in your orion-ejb-jar.xml as follows

<message-driven-deployment name="MessageLogger" enabled="false">

MDB will not start when the application is deployed/started.

You can use Application Server Control to start the MDB later as shown in the following screen shot:


You may want to perform this operation from command line. You can download this zip file that contains code to stop/start MDB using JMX.


  • Unpackage the zip and change ant-oracle.properties file to change your URL, userid and password
  • Set ORACLE_HOME to the directory where OC4J installed


  • To start your MDB:


ant start -DappName=ejb30mdb -DejbModule=ejb30mdb-ejb -DmdbName MessageLogger

  • To stop it


ant stop -DappName=ejb30mdb -DejbModule=ejb30mdb-ejb -DmdbName MessageLogger

Following is the code snippet from the Java Class that perform the stop/start operation:

StartStopMDB mdb = new StartStopMDB();

try {

mdb.connect("service:jmx:"+args[0], args[1] ,args[2] );

System.out.println(mdb);

System.out.printf("Client connected? %s\n",mdb.isConnected());

MBeanServerConnection mbs = jmxCon.getMBeanServerConnection();

String objName = "oc4j:j2eeType=MessageDrivenBean,EJBModule=\""+args[4]

+"\",J2EEApplication="+args[3]+",J2EEServer=standalone,name=\""+args[5]+"\"";

ObjectName myMDBObjectName = new ObjectName(objName);

MessageDrivenBeanMBeanProxy MDBMBean =

(MessageDrivenBeanMBeanProxy)MBeanServerInvocationHandler.newProxyInstance(mbs,

myMDBObjectName, MessageDrivenBeanMBeanProxy.class, false);

if (args[6].equals("start"))

{

System.out.println("Starting up MDB: "+args[5] +" in ejb module:"+args[4]+

" in application name:"+args[3]);

MDBMBean.start();

System.out.println("Successfully started MDB!");

}

else if (args[6].equals("stop")) {

System.out.println("Stopping MDB: "+args[5] +

" in ejb module:"+args[4]+ " in application name:"+args[3]);

MDBMBean.stop();

System.out.println("Successfully started MDB!");

}

mdb.close();

} catch (Exception e) {

e.printStackTrace();

}

}


Hope this helps!

Wednesday, March 26, 2008

Using TopLink Essentials as the JPA Provider for WebLogic 10

A couple of weeks ago, one customer asked me for instructions for using TopLink Essentials as the JPA provider with WebLogic 10. I thought I would give it a try as I’m working on migrating my book examples to WebLogic 10.

First, you have to download TopLink Essentials either from OTN or Glassfish web site.
I packaged the toplink-essentals.jar, toplink-essentials-agent.jar in the lib directory for the EAR so the structure of EAR looked like as follows:

chapter2-ejb.jar
lib/toplink-essentials.jar
lib/toplink-essentials-agent.jar

I specified provider class oracle.toplink.essentials.PersistenceProvider
in my persistence.xml packaged in my EJB module as follows:

<persistence-unit name="actionBazaar">
<provider>
class oracle.toplink.essentials.PersistenceProvider
</provider>
<properties>
<property name="toplink.ddl-generation" value="create-tables"> <property name="toplink.ddl-generation.output-mode" value="database">

If you want to use container managed entity manager with WebLogic’s JTA transaction manager you have to create your server platform class by extending oracle.toplink.essentials.transaction.JTATransactionController as follows:

package debu.weblogic;
import javax.transaction.TransactionManager;
import oracle.toplink.essentials.transaction.JTATransactionController;

public class WebLogicTransactionController extends JTATransactionController
{

private static final String WLS_TRANSACTION_MANAGER_NAME = "javax.transaction.TransactionManager";
public WebLogicTransactionController(){

}

protected TransactionManager acquireTransactionManager() throws Exception {
TransactionManager tm = (TransactionManager)jndiLookup(WLS_TRANSACTION_MANAGER_NAME);
return tm;
}
}

As you might have seen already that I’ve specified this class as the target-server property in persistence class.

You can package this class as a part of your application in the same EAR file where you packaged the TopLink Essentials jar files and the entity classes.

Using TopLink 11 with WebLogic 10

If you are using TopLink 11 preview (or EclipseLink) you do not have to create your own server platform class but you can use the server platform shipped in toplink.jar for WebLogic 10.

Here is how your persistence.xml look like when you use TopLink 11.

<persistence-unit name="actionBazaar">
<provider>
oracle.toplink.PersistenceProvider
</provider>
<jta-data-source>
jdbc/ActionBazaarDS</jta-data-source>

<properties>
<property name="toplink.ddl-generation" value="create-tables">
<property name="toplink.ddl-generation.output-mode" value="database">

<property name="toplink.target-server" value="WebLogic_10">

</property>


Note that you have to package toplink-ojdbc.jar in addition to toplink.jar and antlr.jar if you are using Oracle DB as the underlying database.

Hope this helps.
Need to go to bed, feeling sleepy now!

Sunday, March 23, 2008

EJB 3 In Action Examples on WebLogic 10

Several readers requested me to provide the code examples of EJB 3 in Action for BEA WebLogic 10. We have earlier provided examples for Glassfish, Oracle Application Server and JBoss. I spent sometime last weekend to port these examples to Weblogic 10. You can download examples for first four chapters.


These examples have been modified to run on the default examplesServer on the Weblogic in the default server domain. To run the examples, first the set the environment variables by the running the SetExamplesEnv script in $BEA_HOME/wlserver_10.0/samples/domains/wl_server directory.

For example, if you are running on Windows and you have installed WebLogic 10 in C:\bea\wlserver_10.0\ directory you can run the script as follows:

C:\bea\wlserver_10.0\samples\domains\wl_server\SetExamplesEnv.bat


If you unzipped the samples in c:\WLS examples change directory to chapter 1 and you can build and deploy as follows:

cd c:\WLS examples\chapter1

ant - -> attempts to build and deploy in the examplesServer


To run the example:

ant run


You must be wondering what are the changes that I made in the to run on WebLogic 10.

Java EE promises write once run anywhere ! Then why I had to make changes in the code?

Every application server has its minor quirks here and there and code changes were very minimal.

I could not make dependency injection work in the application client code in WebLogic 10, not sure they support it. So I had to change thick client to make use JNDI lookup instead. I modified the Session bean code to define a global JNDI name for the HelloUser session bean as follows: @Stateless(mappedName="HelloUser")

public class HelloUserBean implements HelloUser


I modified the client code to lookup the remote EJB as follows:

Context ctx = new InitialContext(); helloUser = (HelloUser) ctx.lookup("HelloUser#ejb3inaction.example.HelloUser");


As you would expect, I updated the jndi.properties in the client jar file to have right environment properties for WebLogic as follows:

java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory

java.naming.provider.url=t3://localhost:7001
That's it ..

In the next blog entry, I will discuss the code changes the instructions to run Chapter 2-4 and outline changes made to run JPA and MDB examples.

Wednesday, January 23, 2008

EJB 3.1 New features

Reza Rehman, my co-author of EJB 3 in Action has authored an article on EJB 3.1 new features.

To summarize the major changes that are planned in EJB 3.1 are:


    • Singleton Beans. Using a new @Singleton annotation will support
      this.
    • Optional interfaces similar to web services. Container will generate
      the interface for you. Anyway IMHO it’s always good practice to build an
      interface your bean
    • Stateful Web services using stateful session beans
      EJB
    • Timers to include cron timers. Just to note that OC4J already supports cron
      timer as an extension.
Note that Java Persistence API is now worked under a completely new specification.

You can read the article at http://www.theserverside.com/tt/articles/article.tss?l=NewFeaturesinEJB3-1.

Monday, January 07, 2008

Managing JBoss Application Server from Oracle Enterprise Manager Grid Control

Although I would like that you use Oracle Application Server always I realize that heterogeneous platforms are reality today :) You may have JBoss application server in your environment and you may want to monitor that from Grid Control. Oracle provides a management plug-in for Grid Control to monitor health and performance of JBoss Application Server.
In this blog entry, I will outline the steps to discover JBoss Application Server from Grid Control.
Let us assume that you have installed JBoss Application Server in a server named dpanda-pc in c:\jboss\jboss4.0.2 directory (call it JBoss_Home), your agent is running on a remote host named dpanda-lap.
1. Login to Grid Control 10g R4
2. Click on Application Servers Menu item
3. Select Add -> JBoss Application Server and click on GO
4. Enter name of the server where JBoss is running as Application Server Host
5. Enter the JBoss Home -> the top level directory where JBoss is installed. Note this is not required if you are using Agent installed on a separate host.
6. You have to supply userid/password only if you have enabled security for JMX Console. See http://wiki.jboss.org/wiki/Wiki.jsp?page=SecureTheJmxConsole how you can make JBoss Console secured. This credential will be used by Agent to make JMX connection to gather health/statistics.
7. You can use a remote Intelligent Agent to discover JBoss. If so you have to appropriately select the check box as depicted in the following figure figure:








The Agent requires the JBoss JMX client jar files to make JMX connection to JMS.

Hence you have to copy the following files to a directory e.g. c:\jboss\lib and make it available to the Agent as Library Path:


  • jboss-management.jar from JBoss_Home/server//lib

  • jnp-client.jar from JBoss_Home/client

  • jbossall-client.jar from JBoss_Home/client

  • dom4j.jar from JBoss_Home/lib



Note: Make sure that you restart IA otherwise the current status of JBoss Servers will not be reported correctly post discovery.



8. You have to supply the JNDI port for JBoss server and click next

9. Then you have to supply the credentials for the server/host where JBoss is running

10. It will provide a list of the JBoss partitions and/or Servers that it found in the host and you can select the servers that you want to manage and then click Next



After you confirm at the end of wizard , the JBoss servers will be discovered and you can monitor JBoss Application Server from Grid Control.

Monday, November 12, 2007

At Oracle Open World in San Francisco

Oracle Open World started yesterday. Today I've a session on Java EE with my coworkers Dan Hynes and Dana Singleterry. It is at 3:15pm at Hilton San Francisco. We will present how to build Java EE 5 applications and deploy and manage with Oracle Application Server. If you have a copy of EJB 3 In Action then you can bring it to the session and I can sign it if you want.

I will be hanging around the Oracle Enterprise Manager (Middleware and Apps management booth J04, J06, etc) booths in the demo ground where we are demoing our new product Oracle Application Diagnostics for Java (Oracle AD4J) that help diagnose problems in production environment. Please stop by and learn how Oracle AD4J makes your life simple in diagnosing problems in your production J2EE applications. You can also see some cool demos on SOA management, Application Server Config and Provisioning, SLA management and many more.

Friday, November 02, 2007

Spring and EJB 3: All-Star Team or Neighbors with Good Fences

I presented a Spring / EJB 3 Comparison/Integration talk at the IndicThreads Java conference in Poona. It was very well received. Here is the link to the presentation for your reading pleasure.

It is primarily based on the contents on our book EJB 3 In Action and my research with my coauthor Reza Rehman on this topic.

All EJB 3 books in the market ignore existence Spring considering it as a competitor. Even the classic Java Persistence on Hibernate says nothing about Spring framework. However EJB 3 In Action takes a pragmatic approach and tries to recommend whenever Spring makes sense. Although Spring and EJB 3 are viewed as competitors it can be used complementary technologies and a whole chapter of EJB 3 In Action is dedicated to this integration story. So why wait .. buy a copy for yourself :)

Monday, October 29, 2007

Using Dependency Injection from Web Container in OC4J 10.1.3.x

OC4J 10.1.3.1 and later supports dependency injection from web container. I've seen this question from many customers via email or in OTN forum that using dependency injection from web container generates NPE. If you are running into such problems, make sure that you have specified version as "2.5" in your deployment descriptor (web.xml) as follows:


<?xml version = '1.0'?>?
<?web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">?
...

Monday, September 03, 2007

IndicThread Java Conference















I will be speaking at the IndicThread Java Conference in Pune, India (Oct 26-27). Two of my talks on (Spring / EJB 3 Integration) and SOA management has been accepted. If you are in the Indian subcontinent then it's the only independent Java conference and I highly recommend this conference.

Tuesday, July 24, 2007

More praises for EJB 3 In Action

EJB 3 In Action gets Five STARs rating from Cicero Zandoná of JavaLobby.
Here is some excerpt from his review:

If you want an EJB 3.0 book to read from cover-to-cover this is the one. You will learn how to create an EJB application, the concepts related to them and receive a lot of useful advice.
I really can't give this book less then five "stars".

Here is an interesting comment from the book:

One of the authors, Debu Panda is a Lead Product Manager of the Oracle Application Server development team, and I was afraid this could lead to a biased book. Fortunately this doesn't happen at all, he is completely impartial along the book and always warns the reader about vendor-dependent features.

I'm really happy that everyone seems to like the Sadhu story that I started the book with. Here is what Cicero puts in his review:

In an unusual beginning for a technical book, the authors start talking about ladybugs, elephants and cows (one of the authors name is Panda by the way). But I can't think in a more gentle and creative way to illustrate the specification evolution than the analogy they made (you can read the tale in Meera's review).

Read the detailed review at JavaLobby

Thursday, July 05, 2007

Automatically Executing a Client Application Archive


Many applications have a requirement that they want to automatically execute an application client archive(CAR) packaged as a part of enterprise application (EAR) when server starts up or an application is restarted. This is a Java EE 5 standard compliant alternative to Startup class about which I blogged about 2 and half years back!

In this article, I will outline steps to do this in OC4J.



  • Develop and compile your application client class. This class must contain a main method that will be called by your server during startup.


  • Create a META-INF/Manifest.mf file for the application-client, for example
    Manifest-Version: 1.0
    Main-Class: OracleASStartup


  • Create a deployment descriptor for the application client (application-client.xml) as follows:
    <application-client>
    <display-name>OracleASStartup</display-name>
    </application-client>


  • Create the application client archive (CAR) file for your startup class with the above Manifest and deployment descriptor.


  • Create an EAR file for the application client module with the an OC4J-specific deployment descriptor orion-application.xml as follows:
    <orion-application>
    <client-module path="startup-client.jar" start="true" user="anonymous" >
    </orion-application >


  • Build your EAR and deploy your application with auto start set to "true" as follows in the server.xml:<application name="startup"
    path="../applications\startup.ear" parent="default" start="true" >


Whenever your application is deployed or if you restart your server, the application client will be executed automatically!

Hope this helps!

Wednesday, June 27, 2007

JDJ Article: Java EE 5 and Spring

JDJ just published second part of my article on Java EE 5/ EJB 3 integration with Spring. You can read the article in the June 2007 issue. Here is link to the article for your reading pleasure.

Thursday, June 21, 2007

EJB 3 In Action is #1 spot of hot new released Java Books


EJB 3 In Action got the #1 spot of best selling new and future release Java books. Note that Amazon keeps on changing the rank every hour


Here is the screen shot that shows that it's #1

Wednesday, June 06, 2007

IndicThreads Java Coding Contest and EJB 3 In Action

India's premier Java Developer portal IndicThreads is holding a Java coding contest. This week winner gets a copy of my book EJB 3 In Action!

Also EJB 3 In Action has been reprinted in India by DreamTech press and is available now at most computer book stores!

Monday, June 04, 2007

Injecting POJOs and using resource injection in POJOs

Java EE 5 greatly simplifies using resources and EJBs by using dependency injection. However this support limits only to managed classes such as EJBs, Interceptors, Servlets, etc. Many applications use helper classes those are regular POJOs. However Java EE 5 / EJB 3 does not require support of dependency injection with regular POJOs or injecting POJOs into managed classes.


In this article, I will discuss about Oracle’s extension of managed POJOs and describes how to use dependency injection such as @Resource or @PersistenceContext with regular POJOs (in OC4J 11 Preview).


This example has a session bean named EmployeeFacade that injects a regular POJO named EmployeeHelper. The EmployeeHelper POJO uses @PersistenceContext to inject an instance of EntityManager.


Using Annotations in regular POJOs


To use dependency injection with regular POJO it does not require any Oracle specific extension. The only requirement is that it must be injected to another managed class by using @oracle.j2ee.annotation.InjectedObject or using Oracle specific descriptor e.g. orion-ejb-jar.xml.



Following is an example of regular POJO that uses dependency injection.


public class EmployeeHelper {
@PersistenceContext
private EntityManager em;
private Employee emp;
public Employee findById(int empNo) {
return ((Employee) em.find(Employee.class, empNo));
}
public Employee saveEmployee(String eName, double sal) {
..
return emp;
}
}

Injecting a POJO
OC4J 11 allows injecting POJOs to a managed class or to another POJO using @oracle.j2ee.annotation.InjectedObject. To inject the EmployeeHelper class into the EmployeeFacade EJB we need the following code:


@Stateless
public class EmployeeFacadeBean implements EmployeeFacade {
@InjectedObject
private EmployeeHelper eh;

public Employee findEmployeeByEmpNo(int empNo) {
return eh.findById(empNo);
}
public int addEmployee(String eName, double sal) {
return eh.saveEmployee(eName,sal).getEmpNo();
}
}


Conclusion

OC4J 11 allows injecting one POJO to another POJO. You can try this with OC4J 11 Preview and let us know what other features you want to see.

Another Five STAR rating for EJB 3 In Action

Another reviewer of JavaLobby (Michael Smolyak ) gave five star rating to EJB 3 In Action. Here is what he says:

"The book is enjoyable, extremely well organized and covers a wide range of EJB subjects. I would recommend EJB 3 in Action to both old hands and newly-initiated in the EJB craft. My only complaint is the size of the book; but I think the logical, unhurried and deliberate manner, with which the authors approached the non-trivial subjects addressed in this book, making them accessible to EJB novices, and the breadth of material covered in the volume do make up for its weightiness."

Read the detailed review at JavaLobby