12/10/2012

Java Thread Pools and their Thread Dumps

When analysing a thead dump, if the thread is created with a custom thread name, we can easily trace it to where the thread pool is created by the unique thread name.

Otherwise, we will have to guess which type of thread pool is created from the stack trace, and then search the usage of creation methods like newCachedThreadPool, newSingleThreadScheduledExecutor, newScheduledThreadPool, or newCachedThreadPool.

When using Executors.newCachedThreadPool on JDK 6:

"pool-1-thread-2" prio=5 tid=7ffb30143000 nid=0x117fde000 waiting on condition [117fdd000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <7f310c388> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:196)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:424)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:323)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:874)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:945)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:680)

When using Executors.newCachedThreadPool on JDK 7:
"pool-1-thread-2" prio=5 tid=0x00007f90b38c9800 nid=0x5603 waiting on condition [0x000000016cb92000]
   java.lang.Thread.State: TIMED_WAITING (parking)
 at sun.misc.Unsafe.park(Native Method)
 - parking to wait for  <0x000000014c55bbd8> (a java.util.concurrent.SynchronousQueue$TransferStack)
 at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:226)
 at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
 at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:359)
 at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:942)
 at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
 at java.lang.Thread.run(Thread.java:722)


When using Executors.newScheduledThreadPool(numOfCoreThreads) on JDK 6:
"pool-3-thread-1" prio=6 tid=0x4a5cc000 nid=0xc810 waiting on condition [0x4c96f000]
   java.lang.Thread.State: TIMED_WAITING (parking)
 at sun.misc.Unsafe.park(Native Method)
 - parking to wait for  <0x0934ccc8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
 at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:196)
 at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2025)
 at java.util.concurrent.DelayQueue.take(DelayQueue.java:164)
 at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:609)
 at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:602)
 at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
 at java.lang.Thread.run(Thread.java:662)

When using Executors.newScheduledThreadPool(numOfCoreThreads) on JDK 7:
"pool-1-thread-1" prio=5 tid=0x00007f8075802000 nid=0x5503 waiting on condition [0x00000001610ed000]
   java.lang.Thread.State: WAITING (parking)
 at sun.misc.Unsafe.park(Native Method)
 - parking to wait for  <0x0000000140bbc108> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
 at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
 at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
 at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1079)
 at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:807)
 at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
 at java.lang.Thread.run(Thread.java:722)


When using Executors.newSingleThreadScheduledExecutor on JDK 6:
"pool-1-thread-1" prio=5 tid=7ff0fe159800 nid=0x11442e000 waiting on condition [11442d000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <7f310c8c0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:156)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1987)
    at java.util.concurrent.DelayQueue.take(DelayQueue.java:160)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:609)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:602)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:680)
  
When using Executors.newSingleThreadScheduledExecutor on JDK 7:
"pool-1-thread-1" prio=5 tid=0x00007ff7fb0aa000 nid=0x5503 waiting on condition [0x0000000169c4d000]
   java.lang.Thread.State: WAITING (parking)
 at sun.misc.Unsafe.park(Native Method)
 - parking to wait for  <0x000000014971c208> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
 at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
 at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
 at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1079)
 at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:807)
 at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
 at java.lang.Thread.run(Thread.java:722)


When using Executors.newFixedThreadPool on JDK 6:
"pool-1-thread-2" prio=5 tid=7ff7c4854000 nid=0x118682000 waiting on condition [118681000]
   java.lang.Thread.State: WAITING (parking)
 at sun.misc.Unsafe.park(Native Method)
 - parking to wait for  <7f44c0048> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
 at java.util.concurrent.locks.LockSupport.park(LockSupport.java:156)
 at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1987)
 at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:399)
 at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
 at java.lang.Thread.run(Thread.java:680)

When using Executors.newFixedThreadPool on JDK 7:
"pool-1-thread-1" prio=5 tid=0x00007fb3b4070000 nid=0x5503 waiting on condition [0x000000016c6bf000]
   java.lang.Thread.State: WAITING (parking)
 at sun.misc.Unsafe.park(Native Method)
 - parking to wait for  <0x000000014c18b888> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
 at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
 at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
 at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
 at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
 at java.lang.Thread.run(Thread.java:722)

10/15/2012

Java Applicatioin Process Hangs on Windows and Cached Thread Pool

The following java test app runs and terminates normally on Unix but hangs on Windows.

import java.util.concurrent.*;

public class ThreadPoolTest {
    private static ExecutorService es = Executors.newCachedThreadPool();

    public static void main(String args[]) { 
        es.submit(new Task("## running task 1..."));
        es.submit(new Task("## running task 2..."));
        System.out.println("## after tasks, in main");
    }

    private static class Task implements Runnable {
        private String msg;

        private Task(String s) {
            this.msg = s;
        }

        @Override public void run() {
            System.out.println(msg);
        }
    }
}
The direct reason for hanging is the 2 worker threads were returned to the cached thread pool after finishing the printing task, and stayed alive and idle indefinitely. Pooled threads by default are non-daemon threads. A Java program will terminate only after all non-daemon threads have terminated. Although the main thread in the above test app have finished its job, the Java process will not terminate due to the 2 live worker threads.

A couple of solutions and their pros and cons:

1, So shall we make the pooled threads daemon threads to fix it? Be careful here, since the Java process may just terminate prematurely, immediately after the main thread is done, but before daemon workers complete their work. Since they are daemon threads, their task status is totally ignored in exiting JVM.

If you really want to take the daemon approach, the application will need some logic to poll the stask status, and wait for their completion before exiting the main thread.

2, How about explicitly call ExecutorService.shutdown() method? After all, a task implementing app logic is not a daemon thread, and should be marked as such. Shutting down the thread pool (the actual type of ExecutorService in our example) makes more sense. But pay attention to all possible exit paths and make sure shutdown guaranteed in all paths, such as normal completion, throwable.

If the thread pool is used by various parts of a large application, how do you coordinate them such that shutdown is called only after all clients are finished? Compared to approach 1, additional coordiation (e.g., with wait/notify or CountDownLatch) is needed. To fix the hang using shutdown():

import java.util.concurrent.*;

public class ThreadPoolTest {
    private static ExecutorService es = Executors.newScheduledThreadPool(2);

    public static void main(String args[]) throws InterruptedException {
        es.submit(new Task("# running task 1..."));
        es.submit(new Task("# running task 2..."));
        es.shutdown();

        //block here for all tasks to finish before proceeding in the main thead.
        //if you want to enforce the execution order. optional.
        es.awaitTermination(1, TimeUnit.DAYS);
        System.out.println("# after tasks, in main");
    }

    private static class Task implements Runnable {
        private String msg;

        private Task(String s) {
            this.msg = s;
        }

        @Override public void run() {
            try {
                Thread.sleep(1000*30);
            } catch (InterruptedException e) {
            }
            System.out.println(msg);
        }
    }
}

awaitTermination is totally optional. With it, you will see 2 task output before main thread output:
# running task 2...
# running task 1...
# after tasks, in main

Without it, main thread output comes before task output:
# after tasks, in main
# running task 2...
# running task 1...

3, Is there a default idle timeout for worker threads, so applications don't have to manage the shutdown? Yes, there is a default idle timeout 60 seconds for non-core threads. When creating a thread pool, you can specify the number of core threads, along with other parameters. By default core threads do not time out after becoming idle. But you can certainly make core threads subject to idle timeout by calling threadPool.allowCoreThreadsTimeout(true).

How does this apply to our test app? We created the thread pool by calling newCachedThreadPool() without passing any parameters. By default, the pool is created with 0 core threads and 60-second idle timeout. So any worker threads in the test app should be non-core and should automatically time out after 60 seconds. Yes, that is what happened on Mac OS or Linux. But on windows 7, the same program just hangs.

Do you still want to rely on its default idle timeout, which seems sensitive to OS?

4, Use Thread and Runnable class directly for simple use cases.  When you only need threads, but don't need to maintain a pool, just directly use threads.

To rewrite the above program directly using java.lang.Thread:
public class ThreadTest {
    public static void main(String args[]) throws InterruptedException {
        Thread t1 = new Thread(new Task("## running task 1..."));
        Thread t2 = new Thread(new Task("## running task 2..."));
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("## after tasks, in main");
    }

    private static class Task implements Runnable {
        private String msg;

        private Task(String s) {
            this.msg = s;
        }

        @Override public void run() {
            System.out.println(msg);
        }
    }
}
The 2 join calls are added to wait for the 2 child threads to finish processing before proceeding to the main thread execution.

10/11/2012

How to Configure hprof in GlassFish 3.x

These are the steps to configure hprof profiler in GlassFish 3.x:

1, Identify the target JVM to profile.  In most cases, it's the domain administration (DAS) JVM, but it can be other JVM such as another standalone server instance, or a cluster server instance.

2, Edit $GLASSFISH_HOME/config/osgi.properties, locate org.osgi.framework.bootdelegation property, and append hprof classes to it, using , (comma) as the package separator.  Do not forget to add a comma at the end of the existing value.  The resulting property should look like this:

org.osgi.framework.bootdelegation=${eclipselink.bootdelegation}, \
                                  com.sun.btrace, com.sun.btrace.*, \
                                  org.netbeans.lib.profiler, org.netbeans.lib.profiler.*, \
                                  sun.tools.hprof,com.sun.tools.hat.internal.parser,com.sun.demo.jvmti.hprof

3, Start the domain, and go to admin console to add the hprof profiler:

asadmin start-domain
http://localhost:4848

On the left, choose Configurations | server-config | JVM Settings, on the rigth content panel, choose Profiler tab,

Name: hprof
Status: enabled yes
Classpath: not needed
Native library path: no needed
add a JVM Option:

-agentlib:hprof=file=log.txt,thread=y,depth=3

or using the old non-standard option:

-Xrunhprof:file=log.txt,thread=y,depth=3

Create this profiler and restart the domain from the command line.  You will see the following elements are added to $GLASSFISH_HOME/domains/domain1/config/domain.xml,

<profiler name="hprof" native-library-path="" classpath="">
  <jvm-options>-Xrunhprof:file=log.txt,thread=y,depth=3</jvm-options>
</profiler>

So you could also directly edit domain.xml (not recommended) to save you some clicks, if you know where to add this new element.  For server-config, which corresponds to DAS, it is usually after the first group of jvm-options elements.

There is also asadmin CLI commands to create and delete profiler configuration:

asadmin create-profiler hprof

asadmin delete-profiler

But create-profiler command doesn't allow you to specify hprof jvm options, so you would still need to come back to domain.xml to add jvm options.  However, it takes a --target param, where you can specify where to apply the profiler configuration.

4, After starting and stopping the domain, the hprof data file is created in $GLASSFISH_HOME/domains/domain1/config/ directory,  which is the ${user.dir} for GlassFish server process.

Another related post: How to Configure hprof in JBoss AS7

10/08/2012

My Intellij Notes

To search by keywords for a command, setting, shortcut, etc, and execute it:
Command + Shift + A

To maximize or full screen (useful when reading long lines).  You can also use the same shortcut to go full screen in FireFox, Safari, Chrome, Preview, iTunes, etc.
Command + Ctrl + F

To see javadoc for the method in focus:
Ctrl + J

To see which method/class the current line is in (with super long method body):
Ctrl + Shift + Q

To paste from clipboard history (including copied content from external apps):
Command + Shift + V

To copy the file path of a class:
Command + Shift + C, while inside the editor of that class, not even need to highlight the class name.

To copy the fully qualified name of a class (FQN):
Command + Alt + Shift + C

To delete a line:
Command + Y (y for yank)

To go to a line:
Command + G

To open a class:
Command + N (press it again to include non-project classes like JDK classes)

To organize imports:
Command + Alt + O

To bring up Version Control System popup (git, svn, etc):
Ctrl + V

To view all methods of the current class (press F12 again to include inherited methods):
Command + F12

To view type hierarchy (super-types, sub-types):
Ctrl + H

To jump to source file of another class:
Command + Click, or F4
Command + Shift + I, for a quick view in pop-up without openning it in editor

To go to next error/warning:
F2
Command + F1, to display the error details
Alt + Enter, to display recommended actions

To complete a statement (addthe semi-colon, going to the next line, etc):
Command + Shift + Enter

To auto-complete with text match (as opposed to code completion):
Alt + / (upward search), Alt + Shift + / (downward search)

To hide a tool window:
Shift + Escape
Command + window-number

To format the whole file:
Command + Alt + L

To format a selection:
Command + W to make a selection, then Command + Alt + L

To view and search for recent files:
Command + E, and type the first few letters to filter it in the pop-up
Command + Shift + E, for recent changed files

To switch between open files and tool windows:
Ctrl + Tab, or Ctrl + Shift + Tab, while holding Ctrl, repeatedly press Tab to change selection

To find usage of a type/class/method/variable:
Alt + F7

To generate constructor, getter, setter, toString, hashcode, equals, override method, inside editor window:
Ctrl + N
Command + O (select methods to override)
Command + I  (select methods to implement from interfaces)

To attach to a remote debugger: F9
To continue the debugger, skip all breakpoints: F9
To step over (go to next line): F8
To step into: F7
To set/unset a breakpoint: Command + F8
To view breakpoints: Command + Shift + F8

To increase indent of the current line:
Command + W, then Tab.  If pressing Tab without selection, it will just insert a tab at the cursor, which is not what you want unless the cursor is at the beginning of the line.

To decrease indent of the current line:
Shift + Tab.  No need to make a selection

To auto-format the current line:
Command + W, then Command + Alt + L.  Without a selection, it will just auto-indent the whole file

To auto-indent the current line:
Command + W, then Command + Alt + I.

To join next line into the current line:
Ctrl + Shift + J.  Useful when you need to get rid of the next few blank lines.  Command + Y will also delete a line, but you will need to move cursor to the blank line first.

To go to the beginning and end of the file:
Command + fn + Left
Command + fn + right
3 finger move on touch pad won't work

To go to the beginning and end of the screen:
Command + fn + Up
Command + fn + Down

To go to the beginning and end of the line:
Command + Left
Command + Right

To move the content up and down, while keeping the cursor in the current line:
Command + Up
Command + Down
2 fingers move on touch pad

Jump to navigation bar:
fn + Alt + Left

To add a user dictionary to customize spelling check, create a text file, one word per line, and name it choose-a-name.dic. Inside Intellij settings, search "dictionary", and add the directory containing choose-a-name.dic. Intellij will find all dictionary files (by extension .dic) in that directory.

10/05/2012

How to Configure hprof in JBoss AS7

These are the steps to configure hprof profiler in JBoss AS 7.x:

1, Identify the target JVM to profile.  In most cases, it's the standalone server JVM, but it can be other JVM such as domain process controller, host controller, or individual server.

2, For standalone server, edit $JBOSS_HOME/bin/standalone.conf, locate JBOSS_MODULES_SYSTEM_PKGS property, and append hprof classes to it, using , (comma) as the package separator.  This property tells JBoss Modules to make hprof classes accessible from any class loaders.

JBOSS_MODULES_SYSTEM_PKGS="org.jboss.byteman,sun.tools.hprof,com.sun.tools.hat.internal.parser,com.sun.demo.jvmti.hprof"

3, Still in standalone.conf file, uncomment JAVA_OPTS property, and append hprof options:

JAVA_OPTS="$JAVA_OPTS -agentlib:hprof=file=log.txt,thread=y,depth=3"

or using the old non-standard -X option:

JAVA_OPTS="$JAVA_OPTS -Xrunhprof:file=log.txt,thread=y,depth=3"

4, Start the standalone server, and the hprof data file (log.txt) will be created in the current directory.

One common error when enabling hprof in JBoss AS 7.x is a series of NoClassDefFoundError, which indicates JBOSS_MODULES_SYSTEM_PKGS property has not been properly configured as in step 2.

Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/demo/jvmti/hprof/Tracker
    at org.jboss.logmanager.LogManager$1.run(LogManager.java:65)
    at org.jboss.logmanager.LogManager$1.run(LogManager.java:52)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.jboss.logmanager.LogManager.<init>(LogManager.java:52)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at java.util.logging.LogManager$1.run(LogManager.java:168)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.<clinit>(LogManager.java:157)
    at org.jboss.modules.Main.main(Main.java:278)
Caused by: java.lang.ClassNotFoundException: com.sun.demo.jvmti.hprof.Tracker from [Module "org.jboss.logmanager:main" from local module loader @1a28362]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
    ... 14 more
Exception in thread "Thread-2" java.lang.NoClassDefFoundError: Could not initialize class java.util.logging.LogManager
    at java.util.logging.LogManager$Cleaner.run(LogManager.java:211)
Dumping Java heap ... allocation sites ... done.

Another related post: How to Configure hprof in GlassFish 3.x

10/03/2012

How to Create Management and Application Users in JBoss AS7

JBoss AS7 is secured by default, which means you will have to create users before accessing services and components, such as admin console and remote EJB.

 $JBOSS_HOME/bin/add-user.sh, or add-user.bat is the tool for such purpose. By default it runs in interactive mode, and prompt for user name, password, user type, role, realm, etc. It also has a silent mode (-s, or --silent).

For example, to create a management user, which can be used in admin console (http://localhost:9990):

$JBOSS_HOME/bin/add-user.sh -s -u admin -p "abc123***"

To create an application user, which can be used in remote EJB access:

$JBOSS_HOME/bin/add-user.sh -s -u app -p "abc123***" -a -realm ApplicationRealm --role app,user

To view help info:
$JBOSS_HOME/bin/add-user.sh --help

The user data is persisted in properties files in standalone/configuration and domain/configuration directories:

application-roles.properties
application-users.properties
mgmt-users.properties

Management users currently are not associated with any role, hence no mgmt-roles.properties. It would be nice to have role-based administration.

9/26/2012

How to Create Global Modules in JBoss AS7

In other Java application servers and previous versions of JBoss AS, there is the concept of common lib, where users can put shared libraries for use by all deployed apps. How to achieve the same effect in AS7 with modules and their dependency? The easiest (not necessarily the best) way is to create a global module for a collection of shared jars.

1, Create a module directory structure: 

mkdir -p $JBOSS_HOME/modules/com/mycompany/myproject/main 

2, Copy common jar files to the above directory: 

cp my-util.jar my-service.jar $JBOSS_HOME/modules/com/mycompany/myproject/main

3, Create a module.xml file in the new module's main directory:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.mycompany.myproject">
    <dependencies>
        <module name="javaee.api"/>
    </dependencies>

    <resources>
        <resource-root path="my-util.jar"/>
        <resource-root path="my-services.jar"/>
    </resources>
</module>

4, Declare the module com.mycompany.myproject as a global module, by editing $JBOSS_HOME/standalone/configuration/standalone.xml. Add to the ee subsystem:

<subsystem xmlns="urn:jboss:domain:ee:1.1">
    <global-modules>
        <module name="com.mycompany.myproject" slot="main"/>
    </global-modules>
</subsystem>

Editing server configuration files is not a good idea, but so far this is the only way of adding global modules.

9/24/2012

GlassFish CLI and JBoss AS7 CLI Commands

A rough comparison of GlassFish 3.x CLI and JBoss AS 7 CLI commands:

Tasks GlassFish 3.x JBoss AS 7
List all available commands asadmin list-commands jboss-cli.sh -c "help --commands"
Display help info asadmin --help jboss-cli.sh --help
Check version asadmin version jboss-cli.sh version
Start server or domain asadmin start-domain standalone.sh, or domain.sh
Stop server or domain asadmin stop-domain jboss-cli.sh -c :shutdown
Restart server or domain asadmin restart-domain jboss-cli.sh -c ":shutdown(restart=true)"
Start in debug mode asadmin start-domain -d
asadmin start-domain --debug
standalone.sh --debug
Deploy an app with CLI asadmin deploy ~/test.war jboss-cli.sh -c "deploy ~/test.war"
Undeploy the test.war app asadmin undeploy test jboss-cli.sh -c "undeploy test.war"
List deployed apps asadmin list-applications
asadmin list-components
asadmin list-applications -l
asadmin list-components --long
jboss-cli.sh -c deploy
jboss-cli.sh -c undeploy
jboss-cli.sh -c "deploy -l"
jboss-cli.sh -c "undeploy -l"
jboss-cli.sh -c "ls deploy"
Add a server system property asadmin create-jvm-options -Dbuzz="This is buzz" jboss-cli.sh
-c "/system-property=buzz:add(value='This\ is\ buzz')"
List all server system properties asadmin list-jvm-options jboss-cli.sh -c "/system-property=*:read-resource"
Create a string or primitive JNDI resource asadmin create-custom-resource
--restype=java.lang.Boolean
--factoryclass=
org.glassfish.resources.custom.factory.PrimitivesAndStringFactory
--property value=true resource/flag
jboss-cli.sh -c
"/subsystem=naming/binding=
java\:global\/env\/flag:add(
binding-type=simple, type=boolean, value=true)"
List datasources asadmin list-jdbc-resources jboss-cli.sh -c
"/subsystem=datasources:read-resource-description"
Create datasource using the default db config asadmin create-jdbc-resource --connectionpoolid DerbyPool jdbc/test jboss-cli.sh -c "data-source add --name=test-ds --jndi-name=java\:jboss\/datasources\/test-ds --driver-name=h2 --connection-url=jdbc\:h2\:mem\:test;DB_CLOSE_DELAY\=-1"

jboss-cli.sh -c "data-source enable --name=test-ds"
Delete a datasource asadmin delete-jdbc-resource jdbc/test jboss-cli.sh -c "data-source remove --name=test-ds"
Batch processing based on file input asadmin multimode --file /tmp/glassfish-cli-commands.txt jboss-cli.sh -c "batch --file=/tmp/jboss-cli-commands.txt"

9/21/2012

How to Add System Properties to JBoss AS 7

Option 1, when the server is stopped, add to $JBOSS_HOME/standalone/configuration/standalone.xml, after the <extensions> element:

<system-properties>
    <property name="season" value="spring"/>
</system-properties>

Option 2, when the server is running, run jboss-cli.sh or jboss-cli.bat command to add system property. The property will be persisted to standalone.xml, so it has the same effect as option 1:
jboss-cli.sh -c "/system-property=buzz:add(value='This\ is\ buzz')"

Option 3, add -Dkey=val to standalone.sh command line:
standalone.sh -Dseason=spring

Option 4, pass a properties file containing desired properties to standalone.sh. This is especially convenient if you need a list of dynamic system properties.
standalone.sh -P /tmp/a.properties

Now after the server is up and running, how do you verify your system properties are present with correct value?
  • Test it with any deployed app that prints out the system properties. 
  • View $JBOSS_HOME/standalone/log/server.log, search for the system property name.  Only system properties specified in command line (option 3 & 4) are logged at server startup. 
  • View all system properties in admin console at http://localhost:9990.
    • Runtime tab | Server | Configuration | Environment Properties
  • To list all system properties present in standalone.xml (not including those specified in command line):
    jboss-cli.sh -c "/system-property=*:read-resource"

9/20/2012

JBoss AS7 Ant Tasks for Deploy and Undeploy

I want to use ant to control deploy and undeploy apps to JBoss AS 7 in a simple test. I know I could just have ant copy the WAR, jar, or EAR files to $JBOSS_HOME/standalone/deployments directory, but then I will have to wait till the app is fully initialized before accessing it. So I decided to write some simple ant targets using JBoss AS7 CLI commands.

<?xml version="1.0"?>
<project name="test" default="build" basedir=".">
    <property environment="env"/>
    <property name="jboss.home" value="${env.JBOSS_HOME}" />
    <property name="app.name" value="test.war" />
    <property name="app.path" value="${app.name}" />

    <presetdef name="jboss-cli">
      <java jar="${jboss.home}/jboss-modules.jar" fork="true" >
        <arg line="-mp ${jboss.home}/modules org.jboss.as.cli -c" />
      </java>
    </presetdef>

    <target name="deploy">
      <jboss-cli failonerror="true">
        <arg line="'deploy --force ${app.path}'" />
      </jboss-cli>
    </target>

    <target name="undeploy">
      <jboss-cli failonerror="true">
        <arg line="'undeploy ${app.name}'" />
      </jboss-cli>
    </target>

    <target name="restart">
      <jboss-cli failonerror="true">
        <arg line="':shutdown(restart=true)'" />
      </jboss-cli>
    </target>
</project>
The above deploy and undeploy is equivalent to the following jboss-cli commands:
jboss-cli.sh -c "deploy --force test.war"
jboss-cli.sh -c "undeploy test.war"

8/27/2012

How to Run JBoss Jandex

Jandex is a tool that processes Java annotations within a directory or jar file, and saves the resulting metadata in an index file. This is similar to what a jar file index is to a classloader.

There are 3 ways to run jandex tool:

  1. java -jar command
  2. ant task
  3. jandex maven plugin
In JBoss AS7, jandex jar is located at $JBOSS_HOME/modules/org/jboss/jandex/main/jandex-1.0.3.Final.jar

To display the usage message,
java -jar jandex-1.0.3.Final.jar

Usage: jandex [-v] [-m] [-o file-name] <directory> | <jar>
-or-
jandex [-d] <index-file-name>
Options:
-v verbose output
-m modify directory or jar instead of creating an external index file
-o name the external index file file-name
-d dump the index file index-file-name

The default behavior, with no options specified, is to autogenerate an external index file

To scan a WAR file, adding the result to WAR's META-INF/jandex.idx (not WEB-INF/jandex.idx):
java -jar jandex-1.0.3.Final.jar -v -m /tmp/test.war

Indexed test.TestBean (2 annotations)
Indexed test.TestIF (0 annotations)
Indexed test.TestServlet (2 annotations)
Wrote META-INF/jandex.idx in 0.0710 seconds (3 classes, 4 annotations, 4 instances, 257 bytes)

To scan a WAR file and put result in the default result file in the same directory as the WAR file:
java -jar jandex-1.0.3.Final.jar /tmp/test.war

Wrote /tmp/test.war.idx in 0.0280 seconds (3 classes, 4 annotations, 4 instances, 257 bytes)

To view the content of an index file:
java -jar jandex-1.0.3.Final.jar -d /tmp/test.war.idx

Annotations:
javax.ejb.Stateless:
Class: test.TestBean
javax.ejb.EJB:
Field: test.TestIF test.TestServlet.testBean
javax.ejb.Local:
Class: test.TestBean
(value = [test.TestIF])
javax.servlet.annotation.WebServlet:
Class: test.TestServlet
(urlPatterns = ["/*"])
Subclasses:
javax.servlet.http.HttpServlet:
test.TestServlet
java.lang.Object:
test.TestBean
test.TestIF

Read test.war.idx in 0.0030 seconds

To scan a directory and save the result in a custom output file (-o option currently does not work with jar file input):
java -jar jandex-1.0.3.Final.jar -v -o /tmp/ann.dat $HOME/ws/test/

Indexed test.TestBean (2 annotations)
Indexed test.TestIF (0 annotations)
Indexed test.TestServlet (2 annotations)
Wrote /tmp/ann.dat in 0.0180 seconds (3 classes, 4 annotations, 4 instances, 257 bytes)

jandex.jar comes with an ant task, org/jboss/jandex/JandexAntTask. To run jandex with ant, first create a build.xml:
<?xml version="1.0"?>
<project name="test" default="jandex.modify" basedir=".">
<property environment="env" />
<taskdef name="jandex" classname="org.jboss.jandex.JandexAntTask"
classpath="${env.JBOSS_HOME}/modules/org/jboss/jandex/main/jandex-1.0.3.Final.jar" />

<target name="jandex.modify">
<jandex run="true" verbose="true" modify="true">
<fileset dir="${env.HOME}/ws/test" />
</jandex>
</target>

<target name="jandex.newjar">
<jandex run="true" verbose="true" newJar="true">
<fileset dir="${env.HOME}/ws/test" />
</jandex>
</target>
</project>
To process all "*.jar" files within a directory (recursively, adding the index file to the original jar:

ant jandex.modify

To process all "*.jar" files within a directory (recursively), and create a new index jar file (a jar file that only contains the generated index: META-INF/jandex.idx) for each source jar:

ant jandex.newjar

JandexAntTask (at least this version) filters on file name "*.jar", so any other types of jar files (*.war, *.ear, *.rar, etc) will not be included.

Jandex maven plugin project page has all the source and usages. With this plugin, jandex processes application annotations directly at build time, instead of post-processing the archives as in the 2 other methods. I tried the basic usage by copying the plugin element to one of the quickstart project pom.xml. After running mvn clean install, I can see the console output showing jandex being invoked as part of process-classes phase:
[INFO] --- jandex-maven-plugin:1.0.1:jandex (make-index) @ jboss-as-ejb-in-war ---
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ jboss-as-ejb-in-war ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
...
To verify the index has been generated into target/classes and packaged into war file:
ls -l target/classes/META-INF/jandex.idx

jar tvf target/jboss-as-ejb-in-war.war | grep jandex

289 Tue Aug 28 10:09:40 EDT 2012 WEB-INF/classes/META-INF/jandex.idx
In the above output jandex.idx seems to have been packaged into the wrong directory inside the WAR. It should be in META-INF/jandex.idx. Could be a bug in jandex plugin?

Jandex can be used on jars or directories of any java application classes or libraries. For instance, the following command runs jandex on JDK classes.jar:
sudo java -jar jandex-1.0.3.Final.jar $JAVA_HOME/../Classes/classes.jar

Wrote /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/../Classes/classes-jar.idx
in 2.4900 seconds (20723 classes, 36 annotations, 1381 instances, 678046 bytes)

ls -l $JAVA_HOME/../Classes/*idx
-rw-r--r-- 1 root wheel 678046 Aug 28 10:45 /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/../Classes/classes-jar.idx

8/13/2012

My JBoss AS7 jboss-cli Notes

To start standalone server with the default server config (standalone.xml):
$JBOSS_HOME/bin/standalone.sh


To start standalone server on custom, non-default port numbers, using offset=1, 2, 3, etc (negative offset number is invalid).  When starting with offset 1, you will have http port number 8081 (the default 8080+1), CLI port number 10000 (the default 9999+1), admin console port 9991 (the default 9990+1), etc.
standalone.sh -Djboss.socket.binding.port-offset=1

To start standalone server with a specific server config (just the config file name in $JBOSS_HOME/standalone/configuration directory, do not specify its file path):

standalone.sh -c standalone-full.xml
standalone.sh --server-config=standalone-ha.xml
standalone.sh --server-config standalone-full-ha.xml


To avoid/disable "Press any key to continue..." when running JBoss AS7 commands on Windows:
> set NOPAUSE=true
> standalone
> jboss-cli


To start standalone server in debug mode at default debug port 8787, or at a different port, e.g., 6000:
standalone.sh --debug
standalone.sh -d
standalone.sh -d 6000
standalone.sh --debug 6000


To start domain:
domain.sh


To save the PID from AS process, define the environment variable JBOSS_PIDFILE and LAUNCH_JBOSS_IN_BACKGROUND:
export LAUNCH_JBOSS_IN_BACKGROUND=true
export JBOSS_PIDFILE=$JBOSS_HOME/pid


To stop the default standalone server or domain, with :shutdown operation request (there is no shutdown command):
jboss-cli.sh --connect --command=:shutdown
jboss-cli.sh -c "/:shutdown()"
jboss-cli.sh -c /:shutdown
jboss-cli.sh -c :shutdown


To restart
jboss-cli.sh -c ":shutdown(restart=true)"


To stop the standalone server right now no matter what. If the server is running, it has the same effect as Ctrl-C. If the server is not running, $JBOSS_PIDFILE is not present and so nothing is done.
/bin/kill -9 `cat $JBOSS_PIDFILE`


To exit from the shell started with jboss-cli.sh, use any of the following (Ctrl-D does not work, though):
[standalone@localhost:9999 /] Ctrl-C
[standalone@localhost:9999 /] exit
[standalone@localhost:9999 /] quit
[standalone@localhost:9999 /] q


To list all deployed applications, with either deploy or undeploy command (-l option gives more details about the deployed applications):
jboss-cli.sh -c deploy
jboss-cli.sh -c undeploy

jboss-cli.sh -c "ls deployment"
jboss-cli.sh -c "deploy -l"
jboss-cli.sh -c "undeploy -l"


To deploy an application:
jboss-cli.sh -c "deploy $HOME/tmp/hello.war"


To redeploy (forcefully overwrite any existing deployed app) an app:
jboss-cli.sh -c "deploy --force $HOME/tmp/hello.war"


To undeploy an application:
jboss-cli.sh -c "undeploy hello.war"


To get CLI help info:
jboss-cli.sh help
jboss-cli.sh -c help


To show help info for deploy command:
jboss-cli.sh -c "deploy --help"


To display the version of the current running JBoss AS, along with $JBOSS_HOME, $JAVA_HOME, java.version, os.name, os.version, etc:
jboss-cli.sh -c version


To create a string or primitive JNDI resource. Do not quote the value attribute, otherwise the quote will become part of the content. Also need to escape whitespace.
jboss-cli.sh -c "/subsystem=naming/binding=java\:global\/env\/flag:add(binding-type=simple, type=boolean, value=true)"

jboss-cli.sh -c "/subsystem=naming/binding=java\:global\/env\/text:add(binding-type=simple, type=java.lang.String, value=This\ is\ a\ text\ value.)"


To create an alias for a JNDI resource (java:global/env/condition is an alias for java:global/env/flag):
jboss-cli.sh -c "/subsystem=naming/binding=java\:global\/env\/condition:add(binding-type=lookup, lookup=java\:global\/env\/flag)"


To list server extensions, profiles, subsystems, network interfaces, or socket-binding-groups:
jboss-cli.sh -c "ls subsystem"
jboss-cli.sh -c "ls extension"
jboss-cli.sh -c "ls profile"
jboss-cli.sh -c "ls interface"
jboss-cli.sh -c "ls socket-binding-group"

 
To create a datasource witht the default h2 database: 
data-source add --name=test-ds --jndi-name=java\:jboss\/datasources\/test-ds --driver-name=h2 --connection-url=jdbc\:h2\:mem\:test;DB_CLOSE_DELAY\=-1

data-source enable --name=test-ds


To verify a datasource and check if a connection can be obtained: 
data-source test-connection-in-pool --name=test-ds

To disable a datasource: 
data-source disable --name=test-ds 

To delete a datasource: 
data-source remove --name=test-ds

6/13/2012

GlassFish multimode Command for Batch Processing

GlassFish asadmin multimode command runs a series of asadmin subcommands within one single session. The --file option takes a file containing the list of subcommands.

In the following example, I created 2 files named asadmin-create-resources and asadmin-delete-resources, and pass each of them to asadmin multimode:

# content of file asadmin-create-resources
create-jms-resource --restype javax.jms.QueueConnectionFactory jms/QueueConnectionFactory1
create-jms-resource --restype javax.jms.Queue jms/Queue1
create-jms-resource --restype javax.jms.Queue jms/Queue2


$ asadmin multimode --file /tmp/asadmin-create-resources


# content of file asadmin-delete-resources
delete-jms-resource jms/Queue1
delete-jms-resource jms/Queue2
delete-jms-resource jms/QueueConnectionFactory1


$ asadmin multimode --file /tmp/asadmin-delete-resources
More details are available in asadmin help:
asadmin help multimode
asadmin multimode --help
asadmin multimode -\?

6/04/2012

How to Manage Type Visibility

Type (class/interface) visibility can be managed at three levels:

1, at Java language level, a type can be declared as either public, private, or package private. A public type is visible globally, a private type (usually as a private nested type) is visible only to the enclosing element, and a package private type is visible only in the current package. This is the most common mechanism for handling type visibility and information hiding.

2, at module level, a type can be declared via module metadata to be exported externally, or kept strictly internal. Examples of such module systems are OSGi, Jigsaw, JBoss Modules, etc. In a runtime environment based on such module framework, the dependency and interaction between module components are clearly defined. Public classes in a module are not externally exposed unless declared so.

3, at component level, an implementation class can be proxied or wrapped to mitigate any external exposure. With 1 & 2, some types may still end up being exposed. But that is not too bad with a proxy or wrapper. Even though the client application can load the proxied implementation class, but what is directly exposed is the immutable proxy/wrapper.

For example, getServletContext() returns an implementation of javax.servlet.ServletContext, but it will not be the actual implementation class in the application server. Instead it is most likely an immutable proxy that exposes what is needed in javax.servlet.ServletContext interface. The similar pattern is also used in the implementation of ServletRequest, ServletResponse, javax.ejb.EJBContext, javax.ejb.TimerService, etc.

Why do we want to hide certain types? A software module provides services by publishing essential interfaces and classes, which become the liability of the module. These published types are expected to be there and maintained for the life of the module. When it comes time to redesign, you will need to evaluate how to keep backward compatibility while evolving the API to adapt to the new technology. This is also the time you really wish these interfaces/classes/methods had never been exposed.

Java EE application deployed to application server is an interesting case. User-provided application code and application server code cooperate to make the app work, but they should also be isolated from each other and keep a respectful distance. Application server internal implementation types should be completely hidden from user applications for security purpose. If the application packages the same library that the server contains, care must be taken that the server does not inadvertently load the application's version via thread context classloader.

5/18/2012

GlassFish 3.1 to JBoss AS 7.1.1 EJB Invocation


This post demonstrates how to call a remote EJB deployed to JBoss AS 7.1.1 standalone server from an application deployed to GlassFish 3.1.x. It is similar to the standalone Java client connecting to JBoss AS 7.1.1, except that the remote client is running inside another application server product (GlassFish). The complete project is available in github: glassfish-calling-jboss.

The following is some steps and noteworthy points.

1, configure and start JBoss 7.1.1 standalone server (in a new terminal):

cd $JBOSS_HOME/bin
./standalone.sh
# in a new terminal/tab, or split it
# username: test
# password: 1234
./add-user.sh
2, configure and start GlassFish 3.1.x:
cd $$GLASSFISH_HOME/bin
./asadmin start-domain
./asadmin create-jvm-options -Dcom.sun.enterprise.naming.allowJndiLookupFromOSGi=false

cp $JBOSS_HOME/bin/client/jboss-client.jar $GLASSFISH_HOME/domains/domain1/lib/ext/
cp project-root/client-on-glassfish/src/main/resources/jboss-ejb-client.properties $GLASSFISH_HOME/domains/domain1/lib/classes/
./asadmin restart-domain
The com.sun.enterprise.naming.allowJndiLookupFromOSGi system property option is needed to disable the use of javax.naming.spi.InitialContextFactoryBuilder in GlassFish, which customizes its jndi bootstrapping. Since this configuration is jvm wide, we need to disable it to avoid any interference with JBoss jndi initialization inside GlassFish.

jboss-client.jar is copied to GlassFish domain lib/ext to provide the JBoss client-side ejb and naming funcionality. jboss-ejb-client.properties is also copied to GlassFish domain lib/classes dir so that it share the same classloader as jboss-client.jar.

jboss-ejb-client.properties inside the application should be sufficient. It is also copied in the above step to ensure it is always available to jboss client inside GlassFish. jboss-ejb-client.properties packaged inside the client ejb jar will be loaded by GlassFish application classloader, while jboss client-side runtime classes are loaded by GlassFish common classloader. So jboss client-side may not be able to load jboss-ejb-client.properties, especially if it uses its current classloader for resource loading.

If you see the following error, it means jboss-ejb-client.properties is not loaded:
Tests in error:
invokeClientBean(com.blogspot.javahowto.ClientBeanTestIT):
javax.naming.NameNotFoundException:
ejb:/service-on-jboss/ServiceBean!com.blogspot.javahowto.ServiceIF -- service jboss.naming.context.java.jboss.exported.ejb:.service-on-jboss."ServiceBean!com.blogspot.javahowto.ServiceIF"
3, build and run the project:
cd project-root
mvn clean install

...

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.blogspot.javahowto.ClientBeanTestIT
May 18, 2012 2:00:37 PM com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl findDerbyClient
INFO: Cannot find javadb client jar file, derby jdbc driver will not be available by default.
Look up ClientBean by name java:global/client-on-glassfish/ClientBean, got com.blogspot.javahowto._ClientIF_Wrapper@3735f04a
Result from clientBean.clientHello(): In serviceHello of com.blogspot.javahowto.ServiceBean@3e9c66de

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 14.354 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

There is no transaction context or security context propagation during the remote invocation. If you need them, another approach is to use IIOP protocol and the interoperable naming service. But that requires EJB on both sides to expose 2.x-style remote home interface even for EJB 3 beans. Topic for another day.

5/12/2012

Standalone Java Client for JBoss AS 7.1.1: Maven and JUnit Edition

In previous post, Standalone Java Client for JBoss AS 7.1.1, I showed a hand-written project of standalone client in JBoss AS 7. In this post, I will rewrite it as a maven project with JUnit and jboss-as-maven-plugin. The result is project jboss-as-7-client at github.

The steps are slightly different than the handwritten edition:

1, start JBoss AS and add users:
cd $JBOSS_HOME
./standalone.sh
./add-user.sh (user name: test, password: 1234)


2, "mvn clean install" will build the project, package and deploy the ejb jar to JBoss AS 7, and run the standalone client test.

3, if the ejb jar is already deployed in JBoss AS, step 2 will forcefully overwrite it. If you want to undeploy the ejb jar, run
mvn jboss-as:undeploy

5/11/2012

Standalone Java Client for JBoss AS 7.1.1

In this previous post, I created a sample Java standalone client connecting to JBoss AS 5 & 6. Now let's look at how to do it in JBoss AS 7.1.1.

This sample application consists of a stateless EJB, its remote business interface and a standalone java client that looks up the EJB and invokes its business method.

ClientIF.java
package test;

public interface ClientIF {
public String clientHello();
}
ClientBean.java
package test;
import javax.ejb.*;

@Stateless
@Remote
public class ClientBean implements ClientIF {
public String clientHello() {
return "In clientHello of " + this;
}
}
Client.java
package test;

import javax.naming.*;

public class Client {
public static void main(String args[]) throws Exception {
ClientIF clientBean = InitialContext.doLookup(args[0]);
System.out.printf("Result from clientBean.clientHello(): %s%n%n",
clientBean.clientHello());
}
}
In addition, you also need to prepare a jndi.properties file, and a jboss-ejb-client.properties file, both should be in the client classpath:
# jndi.properties
#
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
java.naming.provider.url=remote://localhost:4447
java.naming.security.principal=test
java.naming.security.credentials=1234
# jboss-ejb-client.properties
#
endpoint.name=client-endpoint
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false

remote.connections=default

remote.connection.default.host=localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false

remote.connection.default.username=appuser
remote.connection.default.password=apppassword

With the above 5 source and config files in place, the project structure looks like this:
jboss-ejb/
.........jndi.properties
.........jboss-ejb-client.properties
.........test/
.............ClientIF.java
.............ClientBean.java
.............Client.java
While in project root directory, compile and package the ejb jar:
javac -cp $JBOSS_HOME/bin/client/jboss-client.jar test/*java
jar cvf client-ejb.jar test/ClientIF.class test/ClientBean.class
If JBoss AS is not already running, start it in a new terminal, and add the application user referenced in the above jndi.properties (add-user.sh is an interactive script). When prompted, enter user name test and password 1234.
cd $JBOSS_HOME/bin
./standalone.sh

./add-user.sh
To deploy the ejb jar, simply copy it to JBoss AS deploy directory:
cp client-ejb.jar $JBOSS_HOME/standalone/deployments/
Finally, run our standalone Java client that looks up and invokes the remote EJB:
java -cp $JBOSS_HOME/bin/client/jboss-client.jar:. test.Client ejb:/client-ejb//ClientBean\!test.ClientIF

May 11, 2012 10:21:16 PM org.xnio.Xnio <clinit>
INFO: XNIO Version 3.0.3.GA
May 11, 2012 10:21:16 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.0.3.GA
May 11, 2012 10:21:16 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 3.2.3.GA
May 11, 2012 10:21:17 PM org.jboss.ejb.client.EJBClient <clinit>
INFO: JBoss EJB Client version 1.0.5.Final
May 11, 2012 10:21:17 PM org.jboss.ejb.client.remoting.VersionReceiver handleMessage
INFO: Received server version 1 and marshalling strategies [river]
May 11, 2012 10:21:17 PM org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver associate
INFO: Successful version handshake completed for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext@53f64158, receiver=Remoting connection EJB receiver [connection=Remoting connection <a995a79>,channel=jboss.ejb,nodename=m-2]} on channel Channel ID bc3ed9ca (outbound) of Remoting connection 2e00e753 to localhost/127.0.0.1:4447
May 11, 2012 10:21:17 PM org.jboss.ejb.client.remoting.ChannelAssociation$ResponseReceiver handleMessage
WARN: Unsupported message received with header 0xffffffff
Result from clientBean.clientHello(): In clientHello of test.ClientBean@4783165b
The client class does a generic lookup, taking lookup jndi name from application arg. In the above java command line, ejb:/client-ejb//ClientBean!test.ClientIF is the jndi name for our remote EJB. This jndi name is constructed from the ejb module name, bean name, bean distinct name, and its remote business interface. More details are in this JBoss docs page.

4/22/2012

Thoughts on ThreadLocal

2 main usages of java.lang.ThreadLocal variables:

  1. Vertical sharing: sharing and propagation of contextual data through the entire processing cycle. This is similar to http request attributes binding, except for the different scopes. A ThreadLocal variable (e.g., security context, transaction context) can be propagated across different tiers, e.g., from web to local EJB. After the processing is done, care must be taken to clear ThreadLocal variables to avoid context leaking.

  2. Horizontal sharing: sharing of objects across repeated and concurrent processing tasks. It offers a third approach for achieving thread safety, besides object locking and unshared instances. No need to clear TheadLocal variables after the current processing is done, since they are intended to be shared throughout the life of the thread.
However, when different class loaders are used among those tasks, the ThreadLocal object previously stored is not visible to the new class loader, and a new binding will be created. So over time, stales entries (instances of ThreadLocal data, and possibly anonymous inner subclass of ThreadLocal) will continue to consume memory. On the bright side, ThreadLocalMap keys use WeakReference and will eventually be cleared when the map approaches its capacity.

Think of ThreadLocal as a container that holds thread-sensitive application data. Therefore, a ThreadLocal variable can be associated with multiple threads. A thread can be associated with multiple ThreadLocal variables.

Thread class maintains a threadLocals Map (ThreadLocal.ThreadLocalMap) to hold all ThreadLocal variables for the current thread. The map key is the ThreadLocal instance, and the value is the actual object for this thread. When you call aThreadLocal.get() to retrieve the current binding, the get() method just asks the current thread to look up in its threadLocals map, using itself (aThreadLocal) as the key.

So the per-thread data is internally stored inside Thread class. Why did they create this ThreadLocal mediator class sitting in the middle? If I were to implement it, my first thought would be to introduce new methods to Thread class, such as setContextData(key, val), getContextData(key) & removeContextData(key).

Here are some reasons I can think of why ThreadLocal was designed this way:

1, Division of labor. Thread as a low-level construct should not be directly manipulated by applications. Application state is better managed by applcation classes.

2, Type safety. ThreadLocal<T> as a generic type is type-safe, and you can declare it to be ThreadLocal<Integer>, ThreadLocal<String>, or ThreadLocal<MyType>.

3, Encapsulation. The recommended practice is to declare a ThreadLocal<T> variable to be

private static final ThreadLocal<MyType> xxx = new ThreadLocal<MyType>();

The applicaton class can choose to completely hide the use of ThreadLocal as an implementation detail, or selectively allow certain operations, e.g., getXXX, setXXX, or removeXXX.

3/31/2012

Different Strategies for Acquiring Dependency inside a Method

When we create or refactor a method, we find some input data is needed for the method to do its job. What are the various options to acquire these dependency? I just went through a major code refactoring and module restructuring, and would like to share some thoughts:

  1. Pass it in as method parameters. This seems to be most common approach, and some considerations are:
    • First forget about implementation details and needs, does it make sense to require the additional data in order to do the work? Think in terms of raw materials for completing the task, as opposed to method parameters.

    • The client code will need to acquire the new data, if not already available, or the target method declares a parameter injection.

    • All subtypes (e.g., subclasses overriding this method) and callers need to be updated to the new method signature. That may not be a problem if we are changing internal interfaces or implementation classes. But for public interfaces, it presents a backward compatibility problem.

    • To what granularity do we want to add the new parameter? Is it a coarse-grained or fine-grained parameter? For example, do we pass in (String name), or (UserInfo userInfo)? Some guidelines:

      • Conceptually, what input is needed for the method to perform its task? Try to reduce the granularity to what's really necessary, to make it usable in more contexts. Some calling code may only have the fine-grained data (e.g., zipCode), but not the coarse-grained data (e.g., userInfo)

      • Be consistent with other methods in the same interface or class. If many peer methods take UserInfo, it makes sense to have UserInfo in the new method even if only part of UserInfo is needed.

      • Unless it's remote invocation, the overhead of parameter passing is the same between a fine-grained and a coarse-grained parameter.

      • Avoid exporting information that is specific to a design tier or implementation layer. If the coarse-grained data fall into this category, then choose to export the fine-grained data that are not tied to the current tier or layer. For example,

        • HttpServletRequest or HttpServletResponse are tied to web tier, and may be passed around during the current request processing inside web tier, but should never be exported to business tier.

        • Security realm instances should not be passed outside security layer.

      • The above point is more evident and enforced by a module system like OSGi. A public class that is not exported by its host module will not be visible to other modules, and so may not be passed outwards. In this case, a fine-grained data type or even a string literal is more appropriate.


  2. Derive from existing method parameters, when the required data is indirectly reachable from existing parameters. For example,

    • String zip = person.getAddress().getZip();

  3. Is it already available as static or instance fields, or inherited from super classes?

    If some data are intrinsic attributes and relationship fields of a class, they should be initialized in constructors or injected via IoC framework and available to be shared by all methods. They consistute the class and instance state. It's possible that a method takes a type of parameter that is already available in class or instance state. They are intended to be distinct objects. For example,
    /**
    * @param userInfo a different UserInfo instance than represented by this person.
    * @return true if userInfo is a potential friend of this person; false otherwise.
    */
    public boolean maybeFriends(UserInfo userInfo) {
    return this.userInfo.similarTo(userInfo);
    }

  4. Derive it from existing static or instance fields, for example,

    • String zipCode = this.userInfo.getZipCode();

  5. Is it available from a global registry, or naming service? Typically, the global namespace is initialized and populated upon program start. If subsequent concurrent and write operations are supported, the global namespace needs to be thread-safe. For example,

    • User user = GlobalPlace.getCurrent(User.class);

    • String m = InitialContext.doLookup("config/mode");

  6. Create my own instances, using direct instantiation or some sort of factory method. Use this option if the current method has adequate information and knows how to create. For example,

    • Config config = new Config(mapping);

    • Handler handler = HandlerFactory.createHandler();

    • Logger logger = Logger.getLogger("abc"); //find or create the named logger

3/23/2012

How to Instantiate Annotation Type and Qualifier

Java annotations are usually used to annotate a language element, to inject dependency, or to provide metadata. They are interface types and cannot be directly instantiated. But sometimes we find it necessary to have instances of annotation types. This post demonstrates how to instantiate annotation types and use qualifier in simple search.

In short, you will need to write an abstract class that implements your annotation type T, and extends javax.enterprise.util.AnnotationLiteral<T> (see ContainsQualifier class below). The client code then can instantiate this abstract class by using anonymous inner class that supplies appropriate values to T (see AnnotationLiteralTest#findBy below).

A somewhat contrived use case: there are bags and baskets that contain items like gold or fruit. So bag and basket are annotated with what they contain. In a warehouse, the staff needs to find all packgages containing gold, all packages containing fruit, etc, based on one or more qualifiers.

This is implemented in the following maven project (project source in github):


pom.xml:


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.blogspot.javahowto</groupId>
<artifactId>annotation-literal</artifactId>
<version>1.0</version>

<build>
<defaultGoal>install</defaultGoal>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>

<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.0-SP4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
The annotation type qualifier: Contains

package com.blogspot.javahowto;

import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Qualifier
@Documented
@Retention(value= RetentionPolicy.RUNTIME)
public @interface Contains {
String value() default "";
}
Bag type containing gold:

package com.blogspot.javahowto;

@Contains("Gold")
public class Bag {
}
Basket type containing fruit:

package com.blogspot.javahowto;

@Contains("Fruit")
public class Basket {
}
Abstract class that implements the qualifier Contains:

package com.blogspot.javahowto;

import javax.enterprise.util.AnnotationLiteral;

public abstract class ContainsQualifier extends AnnotationLiteral<Contains>
implements Contains {}
The qualifier-based search is implemented in CollectionManager:

package com.blogspot.javahowto;

import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.LinkedList;

public class CollectionManager {
private Collection collection;

public CollectionManager(Collection collection) {
this.collection = collection;
}

/**
* Finds all objects matching all criteria represented by annotations
* @param annotationsToMatch one or multiple search qualifiers
* @return a collection of objects that match all the search qualifiers
*/
public Collection findBy(Annotation... annotationsToMatch) {
Collection result = new LinkedList();
for(Object obj : collection) {
boolean matched = false;
Annotation[] classAnnotations = obj.getClass().getAnnotations();
for(Annotation an : annotationsToMatch) {
if(contains(classAnnotations, an)) {
matched = true;
} else {
matched = false;
break;
}
}
if(matched)
result.add(obj);
}
return result;
}

/**
* Checks if an array of Annotations contains an individual Annotation
* @param annotations an array of annotations
* @param ann an individual annotation
* @return true if ann is equal to at least one of the element in
* annotations array; false otherwise
*/
private boolean contains(Annotation[] annotations, Annotation ann) {
for(Annotation a : annotations) {
if(a.equals(ann)) {
return true;
}
}
return false;
}
}
The JUnit test class:

package com.blogspot.javahowto.test;

import com.blogspot.javahowto.*;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class AnnotationLiteralTest {
private static List mixed = new LinkedList();
private static CollectionManager collectionManager;

@BeforeClass
public static void setUp() throws Exception {
for (int i = 0; i < 2; i++) {
mixed.add(new Bag());
mixed.add(new Basket());
}
collectionManager = new CollectionManager(mixed);
}

@Test
public void testContainsGold() throws Exception {
System.out.printf("contains Gold: %s%n%n", findBy("Gold"));
}

@Test
public void testContainsFruit() throws Exception {
System.out.printf("contains Fruit: %s%n%n", findBy("Fruit"));
}

@Test
public void testContainsFruitGold() throws Exception {
System.out.printf("contains Gold and Fruit: %s%n%n", findBy("Gold", "Fruit"));
}

/**
* Finds all objects matching all criteria
* @param criteria one or multiple search qualifiers
* @return a collection of objects that match all the search qualifiers
*/
private Collection findBy(final String... criteria) {
Contains[] qualifiers = new Contains[criteria.length];
for (int i = 0; i < criteria.length; i++) {
final String s = criteria[i];
Contains containsQualifier = new ContainsQualifier() {
@Override
public String value() {
return s;
}
};
qualifiers[i] = containsQualifier;
}
return collectionManager.findBy(qualifiers);
}
}
To build the project and run the JUnit tests:

$ mvn install

Running com.blogspot.javahowto.test.AnnotationLiteralTest
contains Gold: [com.blogspot.javahowto.Bag@7b112783, com.blogspot.javahowto.Bag@23394894]

contains Fruit: [com.blogspot.javahowto.Basket@69198891, com.blogspot.javahowto.Basket@b551d7f]

contains Gold and Fruit: []

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec
Some points for discussion:

The subclass of ContainsQualifier (the anonymous inner class) represents a strategy in strategy pattern. Traditionally the strategy is an implementation of a common interface. Now this seems another area that annotation can replace the traditional interface.

In this project the search criteria are based on string values, and wrap them as annotation may be overkill. But in more complex cases, annotation offers a very flexible and generic interface for specifying conditions and qualifiers.

3/05/2012

ConcurrentHashMap Examples

4 steps when accessing a cache implemented with java.util.ConcurrentHashMap (javadoc):

  1. get the value from the ConcurrentMap;
  2. if null, assume it's the first access, and create the value;
  3. call putIfAbsent on the concurrentMap to store the new value;
  4. if return value is not null (it's rare but happens), use the return value as the golden copy, and discard the newly-created object.
The following test class, SqrtTest, displays the square root of numbers, and each square root value is accessed multiple times concurrently. The intent is to calculate it only on the first access and return the cached value for subsequent requests.
import java.util.*;
import java.util.concurrent.*;

public class SqrtTest {
private static final String CONCURRENCY_LEVEL_DEFAULT = "50";
private static final String CONCURRENCY_KEY = "concurrency";
private ConcurrentMap<Double, Double> sqrtCache = new ConcurrentHashMap<Double, Double>();

public static void main(String args[]) {
final SqrtTest test = new SqrtTest();
final int concurrencyLevel = Integer.parseInt(System.getProperty(CONCURRENCY_KEY, CONCURRENCY_LEVEL_DEFAULT));
final ExecutorService executor = Executors.newCachedThreadPool();

try {
for(int i = 0; i < concurrencyLevel; i++) {
for(String s : args) {
final Double d = Double.valueOf(s);
executor.submit(new Runnable() {
@Override public void run() {
System.out.printf("sqrt of %s = %s in thread %s%n",
d, test.getSqrt(d), Thread.currentThread().getName());
}
});
}
}
} finally {
executor.shutdown();
}
}

// 4 steps as outlined above
public double getSqrt(Double d) {
Double sqrt = sqrtCache.get(d);
if(sqrt == null) {
sqrt = Math.sqrt(d);
System.out.printf("calculated sqrt of %s = %s%n", d, sqrt);
Double existing = sqrtCache.putIfAbsent(d, sqrt);
if(existing != null) {
System.out.printf("discard calculated sqrt %s and use the cached sqrt %s", sqrt, existing);
sqrt = existing;
}
}
return sqrt;
}
}
To compile and run the SqrtTest (-Dconcurrency=123 can be used to adjust the concurrency level):
$ javac SqrtTest.java
$ java SqrtTest 0.5 11 999 0.1

calculated sqrt of 0.5 = 0.7071067811865476
sqrt of 0.5 = 0.7071067811865476 in thread pool-1-thread-1
calculated sqrt of 11.0 = 3.3166247903554
sqrt of 11.0 = 3.3166247903554 in thread pool-1-thread-2
calculated sqrt of 999.0 = 31.606961258558215
sqrt of 999.0 = 31.606961258558215 in thread pool-1-thread-1
sqrt of 11.0 = 3.3166247903554 in thread pool-1-thread-2
calculated sqrt of 0.1 = 0.31622776601683794
calculated sqrt of 0.1 = 0.31622776601683794
sqrt of 999.0 = 31.606961258558215 in thread pool-1-thread-1
sqrt of 11.0 = 3.3166247903554 in thread pool-1-thread-8
sqrt of 0.5 = 0.7071067811865476 in thread pool-1-thread-4
sqrt of 0.5 = 0.7071067811865476 in thread pool-1-thread-7 calculated sqrt of 0.1 = 0.31622776601683794
discard calculated sqrt 0.31622776601683794 and use the cached sqrt 0.31622776601683794sqrt of 0.1 = 0.31622776601683794 in thread pool-1-thread-6
...
From the above output, we can see at least one calculation is discarded since the value already exists in the cache. It had been added to the cache by another thread between step 1 and step 3.

Multiple input double numbers are used to increase thread contention. When testing with one single input number, I couldn't trigger the race condition as evidenced by the "discard calculated sqrt" log message. It is probably because it takes time for the thread pool to create the second thread, and by the time it kicks in, the result is already calculated by the first thread and well established in the cache.

2/18/2012

How to Create POJO JavaBean Custom Resource in GlassFish

In addition to simple value custom resources, GlassFish also provides decent support for POJO JavaBean custom resources. The steps are very similar to String and primitive custom resources, except that you will need to provide your resource impl class and use a different GlassFish factory class. For example, suppose we need to implement a Person class:


public class Person implements java.io.Serializable {
private String firstName;
private String lastName;
private int age;

public String getFirstName() {
return firstName;
}

public void setFirstName(String s) {
firstName = s;
}

public String getLastName() {
return lastName;
}

public void setLastName(String s) {
lastName = s;
}

public int getAge() {
return age;
}

public void setAge(int i) {
age = i;
}

@Override
public String toString() {
return String.format("Person firstName:%s, lastName:%s, age:%s",
firstName, lastName, age);
}
//TODO override equals and hashCode
}
Compile it and copy Person.class to GlassFish domain lib directory, restart the domain, and create a custom resource of type Person:

$ javac Person.java
$ cp Person.class $GLASSFISH_HOME/domains/domain1/lib/classes/
$ asadmin restart-domain
$ asadmin create-custom-resource --restype=Person --factoryclass=org.glassfish.resources.custom.factory.JavaBeanFactory --property firstName\="Jon":lastName\="Smith":age\=20 resource/person
To list the attributes and properties of the newly-created resource with GlassFish asadmin get command:

$ asadmin get 'resources.custom-resource.resource/person.*'

resources.custom-resource.resource/person.property.age=15
resources.custom-resource.resource/person.property.lastName=Smith
resources.custom-resource.resource/person.property.firstName=Jon
resources.custom-resource.resource/person.enabled=true
resources.custom-resource.resource/person.factory-class=org.glassfish.resources.custom.factory.JavaBeanFactory
resources.custom-resource.resource/person.jndi-name=resource/person
resources.custom-resource.resource/person.object-type=user
resources.custom-resource.resource/person.res-type=Person
Command get executed successfully.
To update the age property of the resource with asadmin set command:

$ asadmin set 'resources.custom-resource.resource/person.property.age'=15

resources.custom-resource.resource/person.property.age=15
Command set executed successfully.
To look up the custom resource, resource/person, from a webapp, or Java EE application:

try {
InitialContext ic = new InitialContext();
Person person = (Person) ic.lookup("resource/person");
} catch (NamingException e) {
throw new RuntimeException(e);
}
You can inject it into Java EE web component or EJB component class such as servlet, filter, web listener, interceptor, or EJB bean class:

@Resource(lookup="resource/person")
private Person person;
A Java SE remote client can also look up the resource:

import javax.naming.*;
/**
* A generic remote client for testing JNDI lookup.
*/
public class TestLookup {
public static void main(String args[]) throws Exception {
InitialContext ic = new InitialContext();
for(String name : args) {
System.out.printf("Looked up jndi name %s, got %s%n",
name, ic.lookup(name));
}
}
}
The following shows how to build and run the remote JNDI client, and the output:

$ javac TestLookup.java
$ java -cp "$GLASSFISH_HOME/modules/*:." TestLookup resource/person

Feb 18, 2012 11:42:12 AM com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl findDerbyClient
INFO: Cannot find javadb client jar file, derby jdbc driver will not be available by default.
Looked up jndi name resource/person, got Person firstName:Jon, lastName:Smith, age:15
Note that both TestLookup.class and Person.class are in current directory and therefore are in the client classpath. Person class also implements java.io.Serializable to make remote access possible.

For more advanced example of GlassFish custom resources, see How to create and look up thread pool resource in GlassFish

2/04/2012

How to Create Simple String and Primitive Resources in GlassFish

Sometimes you need to create simple resources in application server so that all deployed applications can look them up. Their types can be string, boolean, number, or any custom java bean types. In GlassFish CLI, they are created and managed with a set of generic commands,


asadmin create-custom-resource ...
asadmin list-custom-resources ...
asadmin delete-custom-resource ...
asadmin get 'resources.custom-resource.*'
asadmin set ...
GlassFish admin console provides GUI way of doing things but I found using CLI is a lot faster.

For example:
$ asadmin create-custom-resource --restype=java.lang.String --factoryclass=org.glassfish.resources.custom.factory.PrimitivesAndStringFactory --property value="http\://javahowto.blogspot.com" resource/javahowto

$ asadmin create-custom-resource --restype=java.lang.Double --factoryclass=org.glassfish.resources.custom.factory.PrimitivesAndStringFactory --property value=0.5 resource/rate

$ asadmin create-custom-resource --restype=java.lang.Boolean --factoryclass=org.glassfish.resources.custom.factory.PrimitivesAndStringFactory --property value=true resource/flag
To look up the custom resource created above, just perform the following in any web or EJB component classes, e.g., servlet, filter, interceptor, web listener, EJB bean class:
try {
InitialContext ic = new InitialContext();
String javahowto = (String) ic.lookup("resource/javahowto");
double rate = (Double) ic.lookup("resource/rate");
boolean flag = (Boolean) ic.lookup("resource/flag");
System.out.printf(
"custom resources from lookup: javahowto=%s, rate=%s, flag=%s%n",
javahowto, rate, flag);
} catch (NamingException e) {
throw new RuntimeException(e);
}
An easier way to obtain these resources is through @Resource injection in any web or EJB component class:
  @Resource(lookup="resource/javahowto")
private String withLookup;

@Resource(lookup="resource/rate")
private double rate;

@Resource(lookup="resource/flag")
private boolean flag;
These custom resources can also be accessed from a remote Java SE client:

import javax.naming.*;

/**
* A generic remote client for testing JNDI lookup.
*/
public class TestLookup {
public static void main(String args[]) throws Exception {
InitialContext ic = new InitialContext();
for(String name : args) {
System.out.printf("Looked up jndi name %s, got %s%n",
name, ic.lookup(name));
}
}
}
To compile and run the remote client:

javac TestLookup.java
java -cp "$GLASSFISH_HOME/modules/*:." TestLookup resource/javahowto resource/rate resource/flag

Feb 16, 2012 8:21:21 PM com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl findDerbyClient
INFO: Cannot find javadb client jar file, derby jdbc driver will not be available by default.
Looked up jndi name resource/javahowto, got http://javahowto.blogspot.com
Looked up jndi name resource/rate, got 0.5
Looked up jndi name resource/flag, got true
The warning message "Cannot find javadb client jar file" can be safely ignored. To avoid this annoying message, just add command line system property AS_DERBY_INSTALL, pointing to a valid derby installation:

java -cp "$GLASSFISH_HOME/modules/*:." -DAS_DERBY_INSTALL=$GLASSFISH_HOME/../javadb TestLookup resource/javahowto resource/rate resource/flag
You can view all attributes and properties of a custom resource with asadmin get command:

asadmin get 'resources.custom-resource.resource/rate.*'

resources.custom-resource.resource/rate.property.value=0.6
resources.custom-resource.resource/rate.enabled=true
resources.custom-resource.resource/rate.factory-class=org.glassfish.resources.custom.factory.PrimitivesAndStringFactory
resources.custom-resource.resource/rate.jndi-name=resource/rate
resources.custom-resource.resource/rate.object-type=user
resources.custom-resource.resource/rate.res-type=java.lang.Double
Command get executed successfully.
To update the value of a custom resource with asadmin set command:

asadmin set 'resources.custom-resource.resource/rate.property.value'=0.6
resources.custom-resource.resource/rate.property.value=0.6
Command set executed successfully.
The updated value is visible to the client application immediately without server restart.