10/28/2014

Javadoc closing tags in IntelliJ

When writing javadocs, IntelliJ automatically adds a closing tag for html elements. For instance, after typing <lt>, it automaticaly adds </lt>, or after typing <p>, it adds </p>. It can be annoying since simple html elements like those used in javadocs don't really need ending tags.
To disable javadoc automatic closing tags in IntelliJ, simply go to IntelliJ Preferences -> Editor -> Smart Keys, then on the right panel, uncheck Automatically insert closing tag.

Intellij 14 screenshot:



 Intellij 15 screenshot:

A related note, JDK 8 has tightened javadoc syntax check, and as a result self-closing elements like <p/>, or <br/> are deemed invalid and will cause failures. See JDK-8020619. However, this checking can be disabled by passing nonstandard option -Xdoclint:none to javadoc tool. For official javadoc guidelines, see How to Write Doc Comments for the Javadoc Tool .

9/24/2014

Diff tools: diff, vimdiff, opendiff & twdiff

4 diff tools that can be executed from command line:

  1. diff (/usr/bin/diff): pure CLI with text output, available in any terminals:
    /tmp > diff Hello.java Hello2.java
    
    1c1
    < public class Hello {
    ---
    > public class Hello2 {
    3c3
    <         System.out.println("Hello from " + Hello.class);
    ---
    >         System.out.println("Hello2 from " + Hello2.class);
    

    use -wub option to view contextual diff:
    /tmp > diff -wub Hello.java Hello2.java
    
    --- Hello.java 2014-09-24 13:16:55.000000000 -0400
    +++ Hello2.java 2014-09-24 13:18:01.000000000 -0400
    @@ -1,5 +1,5 @@
    -public class Hello {
    +public class Hello2 {
         public static void main(String[] args) {
    -        System.out.println("Hello from " + Hello.class);
    +        System.out.println("Hello2 from " + Hello2.class);
         }
     }
    

  2. vimdiff (/usr/bin/vimdiff): part of vim, available in any terminals, pure CLI but blocks the current terminal:
    vimdiff Hello.java Hello2.java
    

  3. opendiff (/usr/bin/opendiff): part of Mac OS xcode tools, launches a FileMerge window for diff and merge:  
    opendiff Hello.java Hello2.java
    



  4. twdiff (/usr/local/bin/twdiff): command line tool of TextWrangler, and launches 3 separate TextWrangler windows (left, right and bottom) for diff and merge.
    twdiff Hello.java Hello2.java
    


7/24/2014

java.util.Properties and character encoding

java.util.Properties class (see Java SE 7 Javadoc) by default assumes ISO 8859-1 character encoding in reading and writing. So when a properties file is in other character encoding, you will see strange characters and behaviors.

Properties class has no method or constructor that takes encoding or locale parameter. Fortunately, in Java SE 6, two new methods were added to allow for reading from java.io.Reader and writing to java.io.Writer:

public synchronized void load(Reader reader) throws IOException;

public void list(PrintWriter out)
So you can create Reader or Writer instances with appropriate encoding, and pass them to Properties load or list methods. For example,
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import org.junit.Test;

public class MyTest {

    @Test
    public void loadPropertiesTest() throws Exception {
        final File jndiPropertiesFile = new File(System.getProperty("user.home"), "tmp/jndi.properties");
        final FileInputStream fileInputStream = new FileInputStream(jndiPropertiesFile);

        // FileReader does not have any constructor that takes encoding, so use InputStreamReader instead
        final InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");

        final Properties jndiProperties = new Properties();
        jndiProperties.load(inputStreamReader);

        //now dump the properties to verify
        jndiProperties.list(System.out);
    }
}
Output from running loadPropertiesTest test:
-- listing properties --
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=jnp://localhost:1099
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

11/26/2013

java.util.Properties, trim, null, whitespace, and escaping

This is the simple test to show the values of properties when loading from a properties file. It tries to answer some common questions about properties value:

Do I need to trim whitespaces from a property value loaded from a properties file?

Yes. Leading whitespaces in a property value are automatically trimmed by Java, but trailing whitespaces are preserved. So if whitespaces are not significant, then property values need to be trimmed val.trim()


Do I need to check null when operating on a property value loaded from a properties file?

Yes. If a property does not exit in the properties file, then calling props.getProperty(key) will return null.


Do I need to check isEmpty when operating on a property value loaded from a properties file?

Yes. If only the key exits in the properties file without assigning any value, then calling props.getProperty(key) will return an empty string. If the value line contains only multiple whitespaces, they will be trimmed away and its value is still empty string.


Do I need to escape = or : characters in property file?

No need to escape = or : in property value, but if the = or : is part of the property key, then you need to escape them. Java treats the first occurrence of = or : or whitespace as the key-value delimiter. So after the delimiter is identified, any use of them no longer needs escaping.

import java.util.*;
import java.io.*;

public class PropertiesTest {
    public static void main(String args[]) throws Exception {
        Properties props = new Properties();
        props.load(new FileInputStream(new File("a.properties")));
        for(String key : props.stringPropertyNames()) {
            System.out.printf("'%s' --> '%s'%n", key, props.getProperty(key));
        }

        System.out.printf("property.not.defined = %s%n", props.getProperty("adsfadsfdjsakfads"));
    }
}
The properties file a.properties:
no.value =
no.value.with.trailing.spaces =
prop.with.leading.trailing.spaces =      value              
prop.with.leading.spaces =      value
equal.sign.in.value = user=admin
colon.in.value = user:password
equal.sign.colon.in.value = user=admin:password=secrete
equal.sign.in.value.escaped = user\=admin
equal.sign.colon.in.value.escaped = user\=admin\:password\=secrete
\=\:in.key.escaped = value for =:in.key.escaped
=:in.key.not.escaped = value for =:in.key.not.escaped
To compile and run this program:
javac PropertiesTest.java
java PropertiesTest

'equal.sign.in.value' --> 'user=admin'
'equal.sign.colon.in.value' --> 'user=admin:password=secrete'
'no.value' --> ''
'prop.with.leading.spaces' --> 'value'
'equal.sign.in.value.escaped' --> 'user=admin'
'=:in.key.escaped' --> 'value for =:in.key.escaped'
'prop.with.leading.trailing.spaces' --> 'value     '
'colon.in.value' --> 'user:password'
'no.value.with.trailing.spaces' --> ''
'equal.sign.colon.in.value.escaped' --> 'user=admin:password=secrete'
'' --> ':in.key.not.escaped = value for =:in.key.not.escaped'
property.not.defined = null
For complete description, see java.util.Properties javadoc.

9/13/2013

NoSuchMethodError: javax.xml.parsers.DocumentBuilderFactory.newInstance

This is the error from running a webapp deployed to appserver:

java.lang.NoSuchMethodError: javax.xml.parsers.DocumentBuilderFactory.newInstance(Ljava/lang/String;Ljava/lang/ClassLoader;)Ljavax/xml/parsers/DocumentBuilderFactory;
The cause: there is an xml-apis.jar under JBOSS_HOME/lib/endorsed directory, and so javax.xml.* classes in xml-apis.jar override those same class from JDK. In particular, DocumentBuilderFactory class in xml-apis.jar is of old version and only has newInstance() method, but not newInstance(String, ClassLoader) method. DocumentBuilderFactory.newInstance(String factoryClassName, ClassLoader) is introduced in Java 6.

The fix is to remove xml-apis.jar from JBOSS_HOME/lib/endorsed directory. XML parser has been in Java proper for a long time, and there is no need for xml-apis.jar in most modern applications.

5/27/2013

java.io.IOException: No such file or directory and URI

You need to create a new file with a file URI like file:/tmp/a.txt, but had this error:

java.io.IOException: No such file or directory
 at java.io.UnixFileSystem.createFileExclusively(Native Method)
 at java.io.File.createNewFile(File.java:947)
 at FileTest.main(FileTest.java:7)
The directory /tmp (or java.io.tmpdir) should already exist and should have write permission for the application. So the error message may be complaining the file (a.txt) does not exist. But a.txt is the new file you are trying to create and of course it doesn't exist. Take another look at the source code:
import java.io.File;
import java.net.URI;

public class FileTest {
    public static void main(String args[]) throws Exception {
        File f = new File(args[0]);
        boolean b = f.createNewFile();
        if(b) {
            System.out.printf("Successfully created new file: %s%n", f);
        } else {
            System.out.printf("Failed to create new file: %s%n", f);
        }
    }
}
Run this class with different input, such as /tmp/a.txt, file:/tmp/a.txt:
$ java FileTest /tmp/a
Successfully created new file: /tmp/a

$ java FileTest /tmp/a
Failed to create new file: /tmp/a
# This failure is expected since /tmp/a already exists.

$ java FileTest file:/tmp/a
Exception in thread "main" java.io.IOException: No such file or directory
So the cause of the IOException is input file URI is not a valid file path. If you have a file URI, then you should use another File constructor to instantiate the File:

//to instantiate a file with URI
//TODO: need to handle java.net.URISyntaxException 
File f = new File(new URI(args[0]));

//to instantiate a filw with path string
File f = new File(args[0]);

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.