Thursday, May 13, 2010

Integrating WebLogic Server with Websphere MQ

Most of the production system configuration relies on messaging now-a-days and which requires compatibilities and interconnection between different middleware servers and messaging system e.g. WebLogic and WebSphere MQ JMS.

In the following steps I tried to make it simple and clear. Depending on the business need it can be re-scaled or re-architect.

Links might help:
1> WebSphere MQ System Requirement
2> WebLogic System Requirement (I will be using WLS8.1 SP4 instance on Windows)

Creating WebSphere MQ queue manager and configuring JMS JNDI namespace

To work with this example, you need to have a QueueConnectionFactory and Queue objects created in JNDI namespace to connect to the queue manager and access queues. Use the following commands to create a queue manager and queues in WebSphere MQ:

1. Create the queue manager: crtmqm testqmgr.
2. Start the queue manager: strmqm testqmgr.
3. Create queues in the queue manager:

runmqsc testqmgr
DEFINE QLOCAL("MyMDBQueue")
DEFINE QLOCAL("MyReplyQueue")
end

Next, create a simple file-based JNDI context and configure the JMS objects in that JNDI namespace. These JNDI objects are used by applications running in WebSphere Application Server Community Edition to connect to the WebSphere MQ queue manager. For this exercise, WebLogic and WebSphere MQ should be on the same machine.

The setting is for file-based JNDI. Create the directory C:\JNDI-Directory before continuing with the next step. Create MyAdmin.config with the following contents:

INITIAL_CONTEXT_FACTORY=com.sun.jndi.fscontext.RefFSContextFactory
PROVIDER_URL=file:/C:/JNDI-Directory
SECURITY_AUTHENTICATION=none

Next, create the QueueConnectionFactory and Queue objects by executing the command:

C:\Program Files\IBM\WebSphere MQ\Java\bin\JMSAdmin.bat -cfg MyAdmin.config

You should see this prompt, where you can configure the JNDI objects: InitCtx>

At the prompt, type the following commands and press Enter after each one:

def xaqcf(ReceiverQCF) qmgr(testqmgr)
def xaqcf(SenderQCF) qmgr(testqmgr)
def q(MyMDBQueue) qmgr(testqmgr) queue(MyMDBQueue)
def q(MyReplyQueue) qmgr(testqmgr) queue(MyReplyQueue)
end

The above configurations are basic steps. For more information about the JMSAdmin tool, CLICK HERE (search for "Using the WebSphere MQ JMS administration tool")

Creating a WebLogic server instance

Create a WebLogic server instance, then add the WebSphere MQ JMS JAR files to its classpath and do the configuration steps below:

1. Install WebLogic Server, for example in C:\bea.
2. Open a command window (cmd.exe).
3. Execute C:\bea\weblogic81\server\bin\setWLSEnv.cmd.
4. Create the server by using the wizard: Click
Start => All Programs => BEA WebLogic Platform 8.1 => Configuration Wizard

Or you can use the following command:
1. Create a directory where you want to run the test, such as C:\jms\WebLogic\test\server, and make it your current directory.
2. Execute the following command to create the domain and server:

java -Dweblogic.Domain=MQJMSTEST -Dweblogic.Name=MQJMSTESTSERVER
-Dweblogic.management.username=weblogic -Dweblogic.management.password=weblogic
-Dweblogic.management.GenerateDefaultConfig=true weblogic.Server

5. After the above command has completed, stop the server, open another command window, and call C:\bea\weblogic81\server\bin\setWLSEnv.cmd by executing the following command:

java weblogic.Admin -url t3://localhost:7001 -username weblogic
-password weblogic FORCESHUTDOWN

6. Configure the WebLogic Server classpath to access the WebSphere MQ JMS JAR files by editing C:\jms\WebLogic\test\server\startMQJMSTEST.cmd and adding the following line just before the last command to start the server JVM:

set MQ_JAVA=C:\Program Files\IBM\WebSphere MQ\Java\lib
set CLASSPATH=%MQ_JAVA%\com.ibm.mq.jar;%CLASSPATH%
set CLASSPATH=%MQ_JAVA%\com.ibm.mqjms.jar;%CLASSPATH%;
set CLASSPATH=%MQ_JAVA%\com.ibm.mqetclient.jar;%CLASSPATH%
(Above line is applicable only for WebSphere MQ + Extended Transactional Client)
set CLASSPATH=%MQ_JAVA%\fscontext.jar;%CLASSPATH%
set PATH=%MQ_JAVA%;%PATH%

7. Start the server by executing C:\jms\WebLogic\test\server\startMQJMSTEST.cmd.

WebLogic Server should be running. Access its admin console using http://localhost:7001/console and authenticating with user name and password (in this example we used weblogic for both).

Configuring a WebLogic foreign JMS server

Next, configure the WebLogic foreign JMS provider with the JNDI setting to access it.

Access http://localhost:7001/console, authenticating with the user name and password used in creating the WebLogic server instance above. After login, navigate to MQJMSTEST => Services => JMS => Foreign JMS Servers. In the right pane, click Configure a new Foreign JMSServer and enter the following values:

* Name: MQJMSTEST Foreign JMS Server
* JNDI Initial Context Factory: com.sun.jndi.fscontext.RefFSContextFactory
* JNDI Connection URL: file:/C:/JNDI-Directory

The screen should look like this:


Figure 1. Creating new Foreign JMS Server.

Click Create at right bottom. You will get another screen to choose the instance of WebLogic Server where this foreign JMS server needs to be created. Select MQJMSTESTSERVER and click Apply.

Now you are ready to configure the QueueConnectionFactory and Queue objects in the newly created foreign JMS provider. By this step what we will be doing is that referring the QueueConnectionFactory and Queues defined in the file-based JNDI as a foreign JMS provider.

Creating QueueConnectionFactory objects in a foreign JMS provider

Navigate to MQJMSTEST => Services => JMS => Foreign JMS Servers => MQJMSTEST Foreign JMS Server => Foreign JMS Connection Factories. In the right pane, click Configure a new Foreign JMSConnection Factory and enter the following values:

* Name: WLSenderQCF
* Local JNDI Name: jms/WLSenderQCF
* Remote JNDI Name: SenderQCF

The remote JNDI Name should match the QueueConnectionFactory name created in the file-based JNDI using the JMSAdmin tool. The screen should look like this:


Figure 2. Creating QueueConnectionFactory.

Click Create at right bottom to complete this operation.

Creating destination objects in the foreign JMS provider

To create the destinations, navigate to MQJMSTEST => Services => JMS => Foreign JMS Servers => MQJMSTEST Foreign JMS Server => Foreign JMS Destinations. In the right pane, click Configure a new foreign JMSDestination and enter the following values:

* Name: WLMyReplyQueue
* Local JNDI Name: jms/WLMyReplyQueue
* Remote JNDI Name: MyReplyQueue

The remote JNDI Name should match the destinations created in the file-based JNDI using the JMSAdmin tool. The screen should look like this:


Figure 3. Creating Queue Destination.
Creating Queue Destination

Click Create at right bottom to complete the operation. Now you are ready with foreign JMS configurations to look into the MDB application.

Developing a sample application and deploying it on WebLogic

Here we use an MDB that is listening for the messages from MyMDBQueue in Queue manager testqmgr. The onMessage() picks up the messages and forwards the same message to MyReplyQueue by calling the putMessage(javax.jms.Message msg) method.

A sample application can be downloaded from HERE

1. Open a command prompt and execute the following commands:

2. cd C:\wlresources

3. C:\bea\weblogic81\server\bin\setWLSEnv.cmd

4. javac com\ibm\WLSampleMDB\SampleMDBBean.java

5. jar -cvf WLSampleMDB.jar com META-INF (creates WLSampleMDB.jar, on which you will work further to deploy it on the server ).

6. Start the Application Builder: Click Start => All Programs => BEA WebLogic Platform 8.1 => Other Development Tools => WebLogic Builder.

7. In WebLogic Builder, click File =>Open and select the WLSampleMDB.jar created in Step 5 (if prompted, click Yes for creating the Deployment Descriptors).

8. Click SampleMDBBean on the left-side tree view, select the General tab, and change the following values:

* JNDI Name: SampleMDBBean
* Transaction Timeout: 300
* Destination Type: javax.jms.Queue
* Destination JNDI: MyMDBQueue (This is the name you have given when you created a queue using JMSAdmin tool)

9. Select the Foreign JMS Provider tab, select Use Foreign JMS Provider, and enter the following values:

* Provider URL: file:/C:/JNDI-Directory
* Connection Factory JNDI Name: ReceiverQCF (The Connection Factory name we created using the JMSAdmin tool for the MDB to receive the messages)
* Initial Context Factory: com.sun.jndi.fscontext.RefFSContextFactory

10. Select the Advanced tab and ensure that for Transaction Type, the value Container is selected.

11. From the left-side tree view, under SampleMDBBean, select Methods and ensure that Default transaction is selected as required.

12. From the left-side tree view, under SampleMDBBean, select Resources.

13. Select the Resource Reference tab from the right-side pane and click Add (if the resources are already defined, click Edit). Enter the following values:

* Resource reference Name: WLSenderQCF
* Resource Type: javax.jms.QueueConnectionFactory
* Resource Authority: Application
* JNDI Name: jms/WLSenderQCF
* Sharing Scope: Unsharable

14. Click OK. Similarly add another resource reference with following values:

* Resource reference Name: MyReplyQueue
* Resource Type: javax.jms.Queue
* Resource Authority: Application
* JNDI Name: jms/MyReplyQueue
* Sharing Scope: Unsharable

15. Click File => Save to save Save WLSampleMDB.jar.

16. To deploy this assembled JAR file, click Tools => Deploy Module. If you are asked for the configuration values to connect to WebLogic Server, verify that they match the values below:

* Protocol: t3
* Host: localhost
* Port: 7001
* Server Name: MQJMSTESTSERVER
* System User Name: weblogic
* System User Password: weblogic
* Now click Connect and in next pop-up window, click Deploy Module.

17. Test the application using the command amqsput MyMDBQueue testqmgr from the command prompt and type any text you want to put it as a message, now observe the console where the WebLogic Server is running and you should be able to see something like this:

Message Received:
JMS Message class: jms_text
JMSType: null
JMSDeliveryMode: 1
JMSExpiration: 0
JMSPriority: 0
JMSMessageID: ID:414d512074657374716d6772202020203f40254420000908
JMSTimestamp: 1143559825190
JMSCorrelationID:null
JMSDestination: null
JMSReplyTo: null
JMSRedelivered: false
JMS_IBM_PutDate:20060328
JMSXAppID:WebSphere MQ\bin\amqsput.exe
JMS_IBM_Format:MQSTR
JMS_IBM_PutApplType:11
JMS_IBM_MsgType:8
JMSXUserID:sanjay
JMS_IBM_PutTime:15302519
JMSXDeliveryCount:1
This is a Test Message

putting the message to MyReplyQueue
looked up QueueConnectionFactory: weblogic.deployment.jms.PooledConnectionFactory@8710bd
looked up Queue: queue://testqmgr/MyReplyQueue
Message send

If you see the above mentioned line properly, then we have configured WebLogic Server and WebSphere MQ to connect to each other and used an MDB sample to get a message and forward it to another queue within a global transaction.

Monday, January 18, 2010

Java HotSpot VM Options

VM options categorized in two types:
  1. Standard options
  2. Non-standard options

For Standard Options please refer the follwoing links depending on your plateform

Windows: http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/java.html

Solaris: http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/java.html

Linux: http://java.sun.com/j2se/1.5.0/docs/tooldocs/linux/java.html

Non-standard options are further categorized in two:

  • Options that begin with -X are non-standard (not guaranteed to be supported on all VM implementations), and are subject to change without notice in subsequent releases of the JDK.
  • Options that are specified with -XX are not stable and are not recommended for casual use. These options are subject to change without notice.

Note: For -X options, please refer the links mentioned above.

Some Useful -XX Options

  • Boolean options are turned on with -XX:+ and turned off with -XX:-.
  • Numeric options are set with -XX:=. Numbers can include 'm' or 'M' for megabytes, 'k' or 'K' for kilobytes, and 'g' or 'G' for gigabytes (for example, 32k is the same as 32768).
  • String options are set with -XX:=, are usually used to specify a file, a path, or a list of commands

Flags marked as manageable are dynamically writeable through the JDK management interface (com.sun.management.HotSpotDiagnosticMXBean API) and also through JConsole.

Behavioral Options

Option and Default Value

Description

-XX:-AllowUserSignalHandlers

Do not complain if the application installs signal handlers. (Relevant to Solaris and Linux only.)

-XX:AltStackSize=16384

Alternate signal stack size (in Kbytes). (Relevant to Solaris only, removed from 5.0.)

-XX:-DisableExplicitGC

Disable calls to System.gc(), JVM still performs garbage collection when necessary.

-XX:+FailOverToOldVerifier

Fail over to old verifier when the new type checker fails. (Introduced in 6.)

-XX:+HandlePromotionFailure

The youngest generation collection does not require a guarantee of full promotion of all live objects. (Introduced in 1.4.2 update 11) [5.0 and earlier: false.]

-XX:+MaxFDLimit

Bump the number of file descriptors to max. (Relevant to Solaris only.)

-XX:PreBlockSpin=10

Spin count variable for use with -XX:+UseSpinning. Controls the maximum spin iterations allowed before entering operating system thread synchronization code. (Introduced in 1.4.2.)

-XX:-RelaxAccessControlCheck

Relax the access control checks in the verifier. (Introduced in 6.)

-XX:+ScavengeBeforeFullGC

Do young generation GC prior to a full GC. (Introduced in 1.4.1.)

-XX:+UseAltSigs

Use alternate signals instead of SIGUSR1 and SIGUSR2 for VM internal signals. (Introduced in 1.3.1 update 9, 1.4.1. Relevant to Solaris only.)

-XX:+UseBoundThreads

Bind user level threads to kernel threads. (Relevant to Solaris only.)

-XX:-UseConcMarkSweepGC

Use concurrent mark-sweep collection for the old generation. (Introduced in 1.4.1)

-XX:+UseGCOverheadLimit

Use a policy that limits the proportion of the VM's time that is spent in GC before an OutOfMemory error is thrown. (Introduced in 6.)

-XX:+UseLWPSynchronization

Use LWP-based instead of thread based synchronization. (Introduced in 1.4.0. Relevant to Solaris only.)

-XX:-UseParallelGC

Use parallel garbage collection for scavenges. (Introduced in 1.4.1)

-XX:-UseParallelOldGC

Use parallel garbage collection for the full collections. Enabling this option automatically sets -XX:+UseParallelGC. (Introduced in 5.0 update 6.)

-XX:-UseSerialGC

Use serial garbage collection. (Introduced in 5.0.)

-XX:-UseSpinning

Enable naive spinning on Java monitor before entering operating system thread synchronizaton code. (Relevant to 1.4.2 and 5.0 only.) [1.4.2, multi-processor Windows platforms: true]

-XX:+UseTLAB

Use thread-local object allocation (Introduced in 1.4.0, known as UseTLE prior to that.) [1.4.2 and earlier, x86 or with -client: false]

-XX:+UseSplitVerifier

Use the new type checker with StackMapTable attributes. (Introduced in 5.0.)[5.0: false]

-XX:+UseThreadPriorities

Use native thread priorities.

-XX:+UseVMInterruptibleIO

Thread interrupt before or with EINTR for I/O operations results in OS_INTRPT. (Introduced in 6. Relevant to Solaris only.)

Performance Options

Option and Default Value

Description

-XX:+AggressiveOpts

Turn on point performance compiler optimizations that are expected to be default in upcoming releases. (Introduced in 5.0 update 6.)

-XX:CompileThreshold=10000

Number of method invocations/branches before compiling [-client: 1,500]

-XX:LargePageSizeInBytes=4m

Sets the large page size used for the Java heap. (Introduced in 1.4.0 update 1.) [amd64: 2m.]

-XX:MaxHeapFreeRatio=70

Maximum percentage of heap free after GC to avoid shrinking.

-XX:MaxNewSize=size

Maximum size of new generation (in bytes). Since 1.4, MaxNewSize is computed as a function of NewRatio. [1.3.1 Sparc: 32m; 1.3.1 x86: 2.5m.]

-XX:MaxPermSize=64m

Size of the Permanent Generation. [5.0 and newer: 64 bit VMs are scaled 30% larger; 1.4 amd64: 96m; 1.3.1 -client: 32m.]

-XX:MinHeapFreeRatio=40

Minimum percentage of heap free after GC to avoid expansion.

-XX:NewRatio=2

Ratio of new/old generation sizes. [Sparc -client: 8; x86 -server: 8; x86 -client: 12.]-client: 4 (1.3) 8 (1.3.1+), x86: 12]

-XX:NewSize=2.125m

Default size of new generation (in bytes) [5.0 and newer: 64 bit VMs are scaled 30% larger; x86: 1m; x86, 5.0 and older: 640k]

-XX:ReservedCodeCacheSize=32m

Reserved code cache size (in bytes) - maximum code cache size. [Solaris 64-bit, amd64, and -server x86: 48m; in 1.5.0_06 and earlier, Solaris 64-bit and and64: 1024m.]

-XX:SurvivorRatio=8

Ratio of eden/survivor space size [Solaris amd64: 6; Sparc in 1.3.1: 25; other Solaris platforms in 5.0 and earlier: 32]

-XX:TargetSurvivorRatio=50

Desired percentage of survivor space used after scavenge.

-XX:ThreadStackSize=512

Thread Stack Size (in Kbytes). (0 means use default stack size) [Sparc: 512; Solaris x86: 320 (was 256 prior in 5.0 and earlier); Sparc 64 bit: 1024; Linux amd64: 1024 (was 0 in 5.0 and earlier); all others 0.]

-XX:+UseBiasedLocking

Enable biased locking.

-XX:+UseFastAccessorMethods

Use optimized versions of GetField.

-XX:-UseISM

Use Intimate Shared Memory. [Not accepted for non-Solaris platforms.]

-XX:+UseLargePages

Use large page memory. (Introduced in 5.0 update 5.)

-XX:+UseMPSS

Use Multiple Page Size Support w/4mb pages for the heap. Do not use with ISM as this replaces the need for ISM. (Introduced in 1.4.0 update 1, Relevant to Solaris 9 and newer.) [1.4.1 and earlier: false]

-XX:+StringCache

Enables caching of commonly allocated strings.

-XX:AllocatePrefetchLines=1

Number of cache lines to load after the last object allocation using prefetch instructions generated in JIT compiled code. Default values are 1 if the last allocated object was an instance and 3 if it was an array.

-XX:AllocatePrefetchStyle=1

Generated code style for prefetch instructions.
0 - no prefetch instructions are generate*d*,
1 - execute prefetch instructions after each allocation,
2 - use TLAB allocation watermark pointer to gate when prefetch instructions are executed.

Debugging Options

Option and Default Value

Description

-XX:-CITime

Prints time spent in JIT Compiler. (Introduced in 1.4.0.)

-XX:ErrorFile=./hs_err_pid.log

If an error occurs, save the error data to this file. (Introduced in 6.)

-XX:-ExtendedDTraceProbes

Enable performance-impacting dtrace probes. (Introduced in 6. Relevant to Solaris only.)

-XX:HeapDumpPath=./java_pid.hprof

Path to directory or filename for heap dump. Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)

-XX:-HeapDumpOnOutOfMemoryError

Dump heap to file when java.lang.OutOfMemoryError is thrown. Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)

-XX:OnError=";"

Run user-defined commands on fatal error. (Introduced in 1.4.2 update 9.)

-XX:OnOutOfMemoryError=";
"

Run user-defined commands when an OutOfMemoryError is first thrown. (Introduced in 1.4.2 update 12, 6)

-XX:-PrintClassHistogram

Print a histogram of class instances on Ctrl-Break. Manageable. (Introduced in 1.4.2.) The jmap -histo command provides equivalent functionality.

-XX:-PrintConcurrentLocks

Print java.util.concurrent locks in Ctrl-Break thread dump. Manageable. (Introduced in 6.) The jstack -l command provides equivalent functionality.

-XX:-PrintCommandLineFlags

Print flags that appeared on the command line. (Introduced in 5.0.)

-XX:-PrintCompilation

Print message when a method is compiled.

-XX:-PrintGC

Print messages at garbage collection. Manageable.

-XX:-PrintGCDetails

Print more details at garbage collection. Manageable. (Introduced in 1.4.0.)

-XX:-PrintGCTimeStamps

Print timestamps at garbage collection. Manageable (Introduced in 1.4.0.)

-XX:-PrintTenuringDistribution

Print tenuring age information.

-XX:-TraceClassLoading

Trace loading of classes.

-XX:-TraceClassLoadingPreorder

Trace all classes loaded in order referenced (not loaded). (Introduced in 1.4.2.)

-XX:-TraceClassResolution

Trace constant pool resolutions. (Introduced in 1.4.2.)

-XX:-TraceClassUnloading

Trace unloading of classes.

-XX:-TraceLoaderConstraints

Trace recording of loader constraints. (Introduced in 6.)

-XX:+PerfSaveDataToFile

Saves jvmstat binary data on exit.



Friday, January 1, 2010

How to Use Log4j with WebLogic Logging Services

WebLogic logging services use an implementation based on the Java Logging APIs, by default. Using the LogMBean.isLog4jLoggingEnabled attribute, you can direct the logging services to use Log4j instead.

In the Administration Console, you can specify Log4j or keep the default Java Logging implementation.

Alternatively, you can configure Log4j logging through the LogMBean interface and by adding WebLogic-specific Log4j classes, WL_HOME/server/lib/wllog4j.jar, and the log4j.jar file to the server CLASSPATH. The recommended way to do this is to place the wllog4j.jar and log4j.jar files in the DOMAIN_NAME/lib directory; there, they will get added to the server CLASSPATH dynamically during server startup.

Note: WebLogic Server does not provide a Log4j version in its distribution.

When Log4j is enabled, you get a reference to the org.apache.log4j.Logger that the server is using from the weblogic.logging.log4j.Log4jLoggingHelper class.

With a Log4j Logger reference, you can attach you own custom appender to receive the server log events; for example, you might attach an appender that sends the server log events to Syslog or the Windows Event Viewer. Additionally, you can use the Logger reference to issue log requests to WebLogic logging services; this requires that the Log4j libraries be available to your deployed application.

If your application has no requirement to interact with WebLogic logging services, package the Log4j libraries in the application's LIB directory. The server logging will continue to use the default Java Logging implementation.

Enabling Log4j Logging

To specify logging to a Log4j Logger instead of the default Java Logging:

* When you start the Administration Server, include the following Java option in the weblogic.Server command:

-Dweblogic.log.Log4jLoggingEnabled=true

* After the Administration Server has started, use the Administration Console to specify the Log4j logging implementation. See "Specifying the Logging Implementation" in the Administration Console Online Help.
* Use the WLST to set the value of the Log4jLoggingEnabled property and re-start the server.


The WLST commands to enable logging to a Log4j Logger in the Administration Server:

#invoke WLST
C:\>java weblogic.WLST

#connect WLST to an Administration Server
wls:/offline> connect('username','password')

#navigate to the writable MBean configuration tree
wls:/mydomain/serverConfig> edit()
wls:/mydomain/edit> startEdit()

#set cmo to the server log config
wls:/mydomain/edit !> cd("Servers/myserver/Log/myserver")

#set log4j logging to true
wls:/mydomain/edit/Servers/myserver/Log/myserver !> cmo.setLog4jLoggingEnabled(true)

#save and activate the changes
wls:/mydomain/edit/Servers/myserver/Log/myserver !> save()
wls:/mydomain/edit/Servers/myserver/Log/myserver !> activate()


You can enable Log4j for the server Logger as well as the domain Logger, which resides only on the Administration Server. The domain Log4j Logger reference is provided by invoking the weblogic.logging.log4j.Log4jLoggingHelper.getLog4jDomainLogger() method.

Log4j Code Example

import org.apache.log4j.Logger;
import weblogic.logging.log4j.Log4jLoggingHelper;
import weblogic.logging.LoggerNotAvailableException;

/**
* This example shows how to use the Log4j server Logger.
*/

public class MyLog4jTest {
public void testWLSLog4j() {
try {
Logger logger = Log4jLoggingHelper.getLog4jServerLogger();
logger.addAppender(myAppender); // The Appender is configured using either the log4j props file or other custom mechanism.
logger.info("Test log message");
} catch(LoggerNotAvailableException lex) {
System.err.println("Unable to get a reference to the log4j Logger: "+
lex.getMessage())
}
}
}



You have programmatic access to the Log4j Logger and its appenders (handlers) and layouts (formatters) for configuration purposes.

Java Logging is the default for client and server-side logging; Log4j is available only for server-side and not client-side logging.

The Concept of Classloaders

Classloaders, as the name suggests, are responsible for loading classes within the JVM. Before your class can be executed or accessed, it must become available via a classloader. Given a class name, a classloader locates the class and loads it into the JVM. Classloaders are Java classes themselves. This brings the question: if classloaders are Java classes themselves, who or what loads them?

When you execute a Java program (i.e., by typing java at a command prompt), it executes and launches a native Java launcher. By native, I mean native to your current platform and environment. This native Java launcher contains a classloader called the bootstrap classloader. This bootstrap classloader is native to your environment and is not written in Java. The main function of the bootstrap classloader is to load the core Java classes.


Figure 1; Classloader delegation hierarchy

The JVM implements two other classloaders by default. The bootstrap classloader loads the extension and application classloaders into memory. Both are written in Java. As mentioned before, the bootstrap classloader loads the core Java classes (for example, classes from the java.util package). The extension classloader loads classes that extend the core Java classes (e.g., classes from the javax packages, or the classes under the ext directory of your runtime). The application classloader loads the classes that make up your application.

All three default classloaders follow the delegation model. Before a child classloader tries to locate a class, it delegates that task to a parent. When your application requests a particular class, the application classloader delegates this request to the extension classloader, which in turn delegates it to the bootstrap classloader. If the class that you requested is a Java core class, the bootstrap classloader will make the class available to you. However, if it cannot find the class, the request returns to the extension classloader, and from there to the application classloader itself. The idea is that each classloader first looks up to its parent for a particular class. Only if the parent does not have the class does the child classloader try to look it up itself.

In application servers, each separately-deployed web application and EJB gets its own classloader (normally; this is certainly the case in WebLogic). This classloader is derived from the application classloader and is responsible for that particular EJB or web application. (Note that if an application is deployed as an EAR file--a combination of EJB and webapps--it gets one classloader, no more). This new classloader loads all classes that the webapp or EJB require that are not already part the Java core classes or the extension packages. It is also responsible for loading and unloading of classes, a feature missing from the default classloaders. This feature helps in hot deploy of applications.

When WebLogic starts up, it uses the Java-supplied application classloader to load the classes that make up its runtime. It then launches individual classloaders, derived from the Java application classloader, which load the classes for individual applications. The individual classloaders are invisible to the classloaders of the other applications; hence, classes loaded for one particular application will not be seen by another application.


Figure 2: Individual application classloaders

What if you want to make a single class available to all applications? Load it in a top-level classloader. This could be in the classpath of WebLogic. When WebLogic starts, it will automatically load this class in memory using the Java-supplied application classloader. All sub-application classloaders get access to it. However, the negatives of this approach are clear too. First, you lose the capability of hot deploy for this particular class in all individual applications. Second, any change in this class means that the server needs to be restarted, as there is no mechanism for a Java application classloader to reload classes. You will need to weigh in the pros and cons before you take this approach.

Friday, July 10, 2009

How to - Interceptors in EJB 3.0

I was checking the interceptors concept with EJB 3.0, and found it quite confusing, so just thought of writing this to clear the clouds around.

EJB 3.0 allows you to define interceptor methods that are called around the business methods and lifecycle events on the bean instances. The interceptor methods can either be defined within the bean class or in separate interceptor classes. Interceptor definitions and binding interceptors to bean classes or specific methods within the beans can be done either using annotations or within the deployment descriptors. Here, I will try to provide a simple example of using interceptors on business methods using annotations.

Methods that intercept invocations to business methods or lifecycle events can be defined either in the bean class or in separator interceptor classes. Only one interceptor method is allowed per class. The interceptor methods should be annotated with the @AroundInvoke annotation and should have the signature, Object (javax.ejb.InvocationContext). If the bean class has a method with the above signature and annotation, the method will be used to interpose on all the business method invocations on that bean. Additionally, you can define interceptors for all the business methods on the bean or individual business methods using the @Interceptors annotation. The value of this annotation is the list of interceptor classes. The interceptor classes are required to have a single interceptor method with the same signature and annotation as explained earlier. Interceptor classes have the same lifecycle as the associated bean instance and can have dependency injection, which will be done using the same naming context as the bean.

InvocationContext

InvocationContext allows you to propagate state across a chain of interceptors. In addition it allows to get/set method parameters, get a reference to the bean, get the invoked method name etc. The methods provided by InvocationContext interface are,
# Object getBean(): Returns a reference to the bean.
# Method getMethod(): Returns a reference to the invoked method.
# Object[] getParameters(): Returns the parameters passed to the method.
# void setParameters(Object[] parameters) : Sets the parameters.
# Map getContextData(): Get contextual data that can be shared in a chain.
# Object proceed(): Proceed to the next interceptor in the chain or the business method if it is the last interceptor.

Order of Interception

The interceptors are invoked in the order in which they are declared in the annotation. Bean level interceptors using interceptor classes are invoked before method level interceptors using interceptor classes. Interceptor method defined in the bean class itself is invoked at the end. If the bean or the interceptor classes have super classes with interceptor methods, they are invoked before the interceptor methods on the sub-classes are called.

Example

Now we will have a look at a simple example for doing interception on an EJB's business method.
Bean Class

package com.ed.ejb;

import javax.ejb.AroundInvoke;
import javax.ejb.Interceptors;
import javax.ejb.InvocationContext;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;

@Stateless
@WebService
@Interceptors( { Interceptor2.class })
public class HelloWorldBean {

@Interceptors( { Interceptor1.class })
@WebMethod
public String sayHello() {
return "Hello";
}

@WebMethod
public String sayHi() {
return "Hi";
}

@AroundInvoke
public Object log(InvocationContext invocationContext) throws Exception {
System.err.println(invocationContext.getMethod().getName() + " called from interceptor 3");
return invocationContext.proceed();
}

}

The bean class has an AroundInvoke method, a bean level interceptor and a method level interceptor. A call to sayHello will invoke the interceptors in the order bean level interceptor, method level interceptor and the AroundInvoke method within the bean class. A call to sayHi will invoke the interceptors in the order bean level interceptor and the AroundInvoke method within the bean class.

Interceptor Classes

package com.ed.ejb;

import javax.ejb.AroundInvoke;
import javax.ejb.InvocationContext;

public class Interceptor1 {

@AroundInvoke
public Object log(InvocationContext invocationContext) throws Exception {
System.err.println(invocationContext.getMethod().getName() + " called from interceptor 1");
return invocationContext.proceed();
}

}

package com.ed.ejb;

import javax.ejb.AroundInvoke;
import javax.ejb.InvocationContext;

public class Interceptor2 {

@AroundInvoke
public Object log(InvocationContext invocationContext) throws Exception {
System.err.println(invocationContext.getMethod().getName() + " called from interceptor 2");
return invocationContext.proceed();
}

}

Testing the Example

The classes shown above can be packaged as a jar file and deployed to your application Server domain. The EJB is annotated with the @WebService annotation and the methods are annotated with the @WebMethod annotation, you can easily test the method invocations.

Cloud vs. Cloud Native

Introduction These days everyone is moving “On cloud”. Having many cloud vendors with lucrative offers of TCO reduction, does deploying yo...