Thursday Oct 21, 2010

Profiling GlassFish 3 with JProfiler

Recently, I investigated performance issues of GlassFish 3. I found that JProfiler 6 is a very handy tool. In this blog, I would like to share with you what I learnt. I would like to thank Dhiru Pandey and Suveen Nadipalli for their help. In the following, we will assume GlassFish 3 installed in $GLASSFISH_HOME and JProfiler 6 is running on Mac OS 10.5.8.

Set up GlassFish 3

Insert com.jprofiler.agent, com.jprofiler.agent.*, immediately after ${eclipselink.bootdelegation}, in org.osgi.framework.bootdelegation property in $GLASSFISH_HOME/glassfish3/glassfish/osgi/felix/conf/

Note that if one were to debug the GlassFish Web Profile - they would need to change $GLASSFISH_HOME/glassfish3/glassfish/osgi/felix/conf/

Issue 12364 is filed on this. Once this bug is fixed only will need to be modified.

Set up JProfile 6 with GlassFish 3

  1. Launch JProfiler.
  2. In Quickstart menu, choose "An application server, locally or remotely".
  3. Choose integration wizard: choose "Glassfish V3".
  4. Choose profiled application located: "On this computer".
  5. JVM settings: (vendor/version/mode). (Note that GlassFish 3 uses JDK "1.6.x".)
  6. Choose "Wait for connection from the JProfiler GUI".
  7. Locate the config file: $GLASSFISH_HOME/glassfish3/glassfish/domains/domain1/config/domain.xml.
  8. Locate the start script: $GLASSFISH_HOME/glassfish3/glassfish/bin/asadmin.
  9. Choose the jprofiler port: 8849 (default).
  10. Click "No".
  11. JProfile create a script asadmin_jprofiler in $GLASSFISH_HOME/glassfish3/glassfish/bin. In Mac, you may like to double check that the script has execution permission. Run chmod u+x $GLASSFISH_HOME/glassfish3/glassfish/bin/asadmin_jprofiler if necessary.
  12. Click "Start Center" > "Open Session" > Double click "Glassfish V3 on localhost" > Session Startup: "Cancel"
  13. Click "Session Settings" > "Filter Settings" > "Excluded"
    Make sure that you do not exclude the classes that you want to profile. For instance, I remove "com.sun.", "org.glassfish.", "org.apache.", "org.jvnet". Click "OK" to save it.
  14. Click "Start" for start profiling GlassFish 3.
  15. For collecting performance data, "CPU Views" > Press to record CPU data

Tips for Viewing and Analyzing Data

  1. For a given class, the most time consuming method is the first one. In general, one may like to look at the most expensive operation first.
  2. If one only interests only in profiling certain package, then one can enter the package name in "View Filters" text box near the bottom of the JProfile screen.
  3. One can export the tree view of the data into html by clicking "Export" in top menu bar.
  4. One can save the data for later comparison by clicking "Save Snapshot".
  5. One can open and compare several snapshots at the same time as follows:
    • "Session" > "Open Snapshot" > "New Window"
    • Select the snapshot data file (with extension .jps) > "Open"

Can we profile GlassFish 3 with JProfile 5?

One can profile GlassFish 3 with JProfile 5. The setup for GlassFish 3 is the same. The setup for JProfile 5 is as follows:
  1. Launch JProfiler.
  2. Close Quickstart if necessary.
  3. Click "Start Center" > "New Session".
  4. Fill in the following information and click "OK".
    • Enter the "Session name".
    • Choose "Session Type": Local.
    • Java VM: 1.6.x
    • Working Directory: $GLASSFISH_HOME/glassfishv3/glassfish/domains/domain1/config
    • VM arguments:-Dcom.sun.aas.installRoot=$GLASSFISH_HOME/glassfishv3/glassfish -Dcom.sun.aas.instanceRoot=$GLASSFISH_HOME/glassfishv3/glassfish/domains/domain1
    • Main class executable JAR: $GLASSFISH_HOME/glassfishv3/glassfish/modules/glassfish.jar
  5. Then repeat Step 12 to Step 15 of the setup for JProfile 6 above.

Enjoy profiling GlassFish 3.

Friday Jun 11, 2010

Change Session Id on Authentication in GlassFish

Session fixation attack is a security vulnerabiltiy where the victim is tricked to login using the session given by a hacker, then the hacker can use the session after that.

Prior to GlassFish v3, one can mininize the exposure of session id in url encoding by specifying a session-properties in WEB-INF/sun-web.xml:

      <property name="enableURLRewriting" value="false" />

In GlassFish v3, with the support of Servlet 3.0, one can also achieve above by specifying the tracking-mode in WEB-INF/web.xml:

<web-app ...>

Note that the default tracking-mode in GlassFish v3 is COOKIE and URL.

In GlassFish 3.0.1 and GlassFish 3.1, a security feature is ported from Tomcat. One can configure a web application so that the session id will be changed after authentication. This mininizes the session fixation attack. One can achieve this by configuring META-INF/context.xml in war file. For instance,

<?xml version="1.0" encoding="ISO-8859-1"?>
  <Valve className="org.apache.catalina.authenticator.FormAuthenticator" changeSessionIdOnAuthentication="true"/>

The above example used form based login. If BASIC is used, then the className should be org.apache.catalina.authenticator.BaseAuthenticator.

Wednesday Mar 17, 2010

Https outbound connection from GlassFish Enterprise Server v2 to Oracle GlassFish Server 3.0

Oracle GlassFish Server 3.0 is a Java EE 6 container. It uses JKS as keystore. In GlassFish Enterprise Server v2, it uses NSS. In this simple blog, we will show how to set up environments for https outbound connection from GlassFish v2 to Oracle GlassFish Server 3.0.
  1. Export the certificate from Oracle GlassFish Server 3.0 from JKS.
    Change to domain config directory where one can find cacerts.jks and run the following command:
    keytool -export -rfc -alias s1as -file s1asv3.cert -keystore cacerts.jks -storepass changeit
    Note that one should let keytool prompt for password rather than using -storepass. It is used here for illustration.
  2. Import the certificate to GlassFish Enterprise Server v2.
    Note that one need to use a different alias name "s1asv3" as there is already a certificate of name "s1as" in NSS db. Change to the domain config directory where one can find cert8.db and run the following command:
    certutil -A -n s1asv3 -d . -i s1asv3.cert -t "T,c,c"
    Restart the GlassFish Enterprise Server.
I find that the following jsp testing code is quite handy. It is included here for convenience:

<%@page import="\*,\*,\*" %>
    try {
        String host = request.getParameter("host");
        String port = request.getParameter("port");
        String urlStr = "https://" + host + ":" + port;
        out.println("Url = " + urlStr + "<hr>");
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = "";
        while ((line = in.readLine()) != null) {
    } catch(Throwable ex) {
        ex.printStackTrace(new PrintWriter(out));

Note that one can read more about GlassFish Enterprise Server v2 and NSS in "Key Management and PKCS#11 Tokens in Sun Java System Application Server 8.1".

Tuesday Mar 10, 2009

Using Jetty Bayeux Client in GlassFish v3

In Cometd environment, one can access cometd services through simple Javascript, Java API for Bayeux Protoc, DOJO, etc.

In the Grizzly Issue 174, developer amplus has contributed a first porting of Jetty Bayeux Java Client to Grizzly. A modification of the contribution has been checkin to Grizzly. The above client code is based on Jetty 6.1.11. Subsequently, various cometd bugs has been fixed in Grizzly 1.9.8 or later.

In this blog, we will describe how to use the Jetty Bayeux client in Grizzly with GlassFish v3.

Environment Setting

In this moment, comet support is turned off by default. The comet/cometd can be turned on in GlassFish v3 by adding the following property to corresponding http-listener. In our case, it is the http-listener-1.

    <property name="cometSupport" value="true">

Note that it is recommended that one should set the above property by using asadmin rather than directly editing the domain.xml. For instance,

    asadmin set

Download the following jars and put it under $GLASSFISH_HOME/domains/domain1/lib:

  • grizzly-cometd-client-1.9.8.jar
  • cometd-bayeux-6.1.11.jar
  • jetty-6.1.11.jar
  • jetty-client-6.1.11.jar
  • jetty-util-6.1.11.jar
The first jar is from Grizzly repository. Note that you may like to get the correct Grizzly version working with your GlassFish v3. (For instance, one can find out the Grizzly version in MANIFEST.MF of web-glue.jar.) The remaining jars are from Jetty repository 6.1.11.

Finally, we have to start the server.

A Cometd client application using Jetty Bayeux client

In our example, we will create a web Bayeux Client for Cometd Chat Sample. It can be downloaded here.

One need to import Jetty's classes as follows:

    import org.mortbay.cometd.AbstractBayeux;
    import org.mortbay.cometd.client.BayeuxClient;
    import org.mortbay.jetty.client.HttpClient;
    import org.mortbay.thread.QueuedThreadPool;
    import org.mortbay.util.ajax.JSON;
    import dojox.cometd.Bayeux;
    import dojox.cometd.Client;
    import dojox.cometd.Message;
    import dojox.cometd.MessageListener;

Then one need to create a BayeuxClient in as follows:

  • Create a HttpClient.

        httpClient = new HttpClient();

  • Create a QueuedThreadPool for the HttpClient.

        QueuedThreadPool pool = new QueuedThreadPool();

  • Start the HttpClient and create a BayeuxClient.

        client = new BayeuxClient(httpClient, address, cometdUri) {
            public void deliver(Client from, Message message) {
                // do something
                super.deliver(from, message);

    where address is an InetSocketAddress and cometdUri is the cometd service uri.

  • Create a MessageListener for the BayeuxClient.

        MessageListener listener = new MessageListener() {
            public void deliver(Client fromClient, Client toClient, Message msg) {
                Object data = msg.get(AbstractBayeux.DATA_FIELD);
                if (data != null) {
                   // do something

    This listener is a no-op as we only use the client to send message in our case.

  • Start the BayeuxClient and subscribe the channel.


With the setup above, the JSON message can be published as follows:

    Object msg=new JSON.Literal("{\\"user\\":\\"" + name + "\\",\\"chat\\":\\"" + chat + "\\"}");
    client.publish(channel, msg, String.valueOf(mid.getAndIncrement()));

where msg is a JSON object associated to data.

Comparison with Java API for Bayeux Protocol

In this section, we will compare Jetty Bayeux client with the Java API for Bayeux Protocol. For convenience, I will summarize the Java API for Bayeux Protocol as follows:
  • Get the CometContext.

        CometEngine context = CometEngine.getEngine().getCometContext(channel);

  • Create the DeliverResponse.

        Map map = new HashMap();
        map.put(messageDataName, messageDataValue);
        Data data = new Data();

        DeliverResponse deliverResponse = new DeliverResponse();

    Note that in this moment, one has to setFinished(true) in addition to setLast(true).

  • Notify the deliverResponse


 Jetty Bayeux ClientJava API for Bayeux Protocol
Setupmore involvedsimple
Access Cometd Servicelocal and remotelocal
Clientin server and standlonein server
Construction of JSON messagessome explicitlyall use API

Friday Sep 26, 2008

compression and compressionMinSize in GlassFish v3

In Enabling HTTP Compression in GlassFish, Jean-Francois discussed about compression in GlassFish. There are four properties to configure compression, namely:
  • compression
  • compressionMinSize (in OCTET)
  • compressableMimeType
  • noCompressionUserAgents
One can turn compression on and off by setting compression = force and compression = off respectively. And one can also turn on the compression if the content-length is unknown or known to be greater than a certain size. There are two properties related to this: compression and compressionMinSize. In this blog, we will discuss various ways to accomplish this scenario in GlassFish v3.

compression vs compressionMinSize

propertypossible value if setDefault
compressionon, force, off, integeroff

There are several possible combinations. We will summarize the behaviors of GlassFish v3 in the below table. In the following, α and β are integers.

onβcompression with min size β
onnot setcompression with default min size (2048)
forceβ or not setcompression with no size constraint
αβ or not setcompression with min size α
off or not setβ or not setno compression

So, roughly speaking, whenever there is conflicting information between compression and compressionMinSize, the compression property will take precedence.

Since we use strict inequality to check for known content length, the following are equivalent:

  • compression = force
  • compression = on and compressionMinSize = any negative integer

How to test it?

If one has turned on compression in GlassFish, then one will get HTTP compression if the HTTP request is
  • using HTTP 1.1
  • with a HTTP header:
        Accept-Encoding: gzip
  • the content-length is unknown or greater than the compression minimum size
    (or compression = force)
One can confirm that there is a HTTP compression by using Firefox with Firebug. There will be a HTTP response header:
  • Content-Encoding: gzip
Note that one can also notice some changes in HTTP response for HTTP compression by using the http client posted in one of my previous blogs.

Thursday Aug 14, 2008

WEBDAV in GlassFish

WEBDAV (RFC 4918) protocol is a predecessor to HTTP/1.1 for management resources, etc. The WEBDAV code in GlassFish workspace is based on Tomcat. Jean-Francois blogged about this in 2006. WEBDAV Level 2 will be a supported feature in GlassFish v3. In this blog, we would provide additonal information about WEBDAV in GlassFish v3.

Configuration of WebDAVServlet

WEBDAV can be enabled by specifying the org.apache.catalina.servlets.WebdavServlet in web.xml for a given web application. Also, it can be enabled and configured globally in default-web.xml. One can configure WebDAVServlet by specifying the init-param as follows:

debugintdebug level0 (no debug)
listingsbooleanwhether one can list resourcesfalse
readonlybooleanwhether resources are readonlytrue

It is important to note that when listings is set to true or readonly is set to false, one must set up security constraints and turn on security manager.

WEBDAV Clients

I have verified that the following WEBDAV clients work with GlassFish v3:
  • Microsoft Word 2002 and 2003
      File > Open > the url
  • Internet Explorer 6 and 7
      File > Open (check "Open as Web Folder") > the url
    Note that under "Internet Options > Programs > HTML editor", we may like to set it to Microsoft Word above or Mircrosoft FrontPage.

Hand-On Examples on WEBDAV protocol

WEBDAV includes the following HTTP methods:
  • GET
  • HEAD
  • POST
  • PUT
  • COPY
  • MOVE
  • LOCK
I find that it is a good exercise to send HTTP requests directly and see what happens there. For instance,
  • the following HTTP request copy index.html to index2.html:
    COPY /webdavtest/index.html HTTP/1.1
    Host: localhost
    Destination: http://localhost:8080/webdavtest/index2.html
    Connection: close
  • the following HTTP request delete the index2.html created above:
    DELETE /webdavtest/index2.html HTTP/1.1
    Host: localhost
    Connection: close
There are many ways to send http client requests to server. I find that it is quite handy to have the following Ruby script.

  require "socket"

  if ARGV.length != 3
      puts "ruby httpclient.rb <host> <port> <http request file>\\n"

  host = ARGV[0];
  port = ARGV[1].to_i;
  filename = ARGV[2];

  socket =, port)

  file =
  while line = file.gets
      command = line.chomp
      puts command + "\\r\\n"
      socket.write(command + "\\r\\n")

  puts socket.readlines


Note that you may like to update the path of ruby or run the interpretator directly.

Tuesday Jul 15, 2008

Common Gateway Interface in GlassFish

Common Gateway Interface (CGI) supports dynamic contents in web environment. CGI programs are executable programs in the server platform with specific output. It can be a Bourne shell script, Perl script or even a C binary executable. It was very popular before the the appearance of Servlet, JSP and PHP. The CGI code in GlassFish workspace is based on Tomcat. In GlassFish v3, CGI will be a supported feature. Let us look at a very simple example.

Create a CGI script

In our example, we have a simple Perl program, hello, to print a hello message and the timestamp of the server.

    print "Content-type: text/html\n\n";
    print "Hello World: ";
    print scalar localtime;
    print "\n";

Enabling CGI processing and packaging the war file

The CGI processing can be enabled in a war file by adding CGIServlet et al in web.xml as follows:



In this case, one need to package the hello under the default cgiPathPrefix which is WEB-INF/cgi. For security, it is highly recommended that the contents / binaries of CGI programs should be prohibited from direct viewing or download.

Alternatively, one can enable CGI by uncommenting the corresponding sections in default-web.xml.

In our case, the CGI program can be invoked through http://localhost:8080/YOUR_CONTEXT/cgi-bin/hello .

Configuration of CGIServlet

One can configure CGIServlet by specifying the init-param as follows:

cgiPathPrefixStringsubdirectory containing the cgi programsWEB-INF/cgi
debugintdebug level0 (no debug)
executableStringexecutable for running the CGI scriptperl
parameterEncodingStringencoding use for parameterSystem.getProperty("file.encoding", "UTF-8")
passShellEnvironmentbooleanwhether to pass environment properties to CGI programfalse

CGI with native executables

GlassFish v3 CGI can work with native executables as follows:

  • set the init-param with name executable to be the empty String in web.xml
  • has exploded directory structure for the war in a directory, say /export/cgitest
  • make sure those executables has the executable bits set correctly
  • deploy the "directory" (not the "war"), for instance
    asadmin deploy /export/cgitest
Note that one works with the exploded directory structure rather than war file as the executable bits information is lost during the process of jar and unjar.

Friday Jul 11, 2008

Server Side Include in GlassFish

Server Side Include (SSI) allows including dynamic contents in html. SSI and CGI were very popular before the the appearance of JSP and PHP. The SSI code in GlassFish workspace is based on Tomcat. In GlassFish v3, SSI will be a supported feature. Let us look at a very simple example.

Create a SSI file

In our example, we create a index.shtml which
  • includes the content of header.html,
  • prints a Hello message with server side timestamp, and
  • executes a command say, uname (or any command in your operating system).
The page is as follows:

    <!--#include virtual="header.html"-->
    <br>Hello, it is <!--#echo var="DATE_LOCAL"-->.
    <br>Result: <!--#exec cmd="uname"-->

Note that the extension shtml is configurable in web.xml (see servlet-mapping below).

Enable SSI processing

The SSI processing can be enabled in a war file by adding SSIServlet et al in web.xml as follows:




One can find more details about the configuration of SSIServlet in the section below. Alternatively, one can enable SSI by uncommenting the corresponding sections in default-web.xml.

Note that the mime-mapping is to notify the browser that the result of shtml file is of content-type: text/html. If you don't specify this, then GlassFish will try to get the mime-type from default-web.xml or the default in the system.

Configuration of SSIServlet

One can configure SSIServlet by specifying the init-param as follows:

bufferedboolean (or String converted to boolean)whether the output should be bufferedfalse
debugintrepresents debug level0 (no debug)
expiresLongexpiration time in secondsdo not set "Expires" header in Http Response
inputEncodingStringencoding for SSI input if there is no URL content encoding specifiedserver platform encoding
isVirtualWebappRelativeboolean (or String converted to boolean)whether the "virtual" path of "#include" directive is relative to content-rootfalse (means relative to the given SSI file)
outputEncodingStringencoding for SSI outputUTF-8

Friday May 25, 2007

Comparison of Security features in GlassFish and SJSAS 8.x EE

Security is very essential, especially in the enterprise environment. In this blog, we will compare security of Profiles in GlassFish (GF) v2 and also note those feature availability in Sun Java System Application Server (SJSAS) 8.x Enterprise Edition. Note that Enterprise Profile is not available in public yet and will be in beta around July 2007. More information on Profiles in GlassFish v2 can be found here.

Comparison of Security with GF and SJSAS 8.x EE
FeatureGlassFish SJSAS 8.x EE
v1v2 Development Profilev2 Cluster Profile v2 Enterprise Profile
Support JSR 196 noyesno
KeyStore for SSL JKS NSS
Key/Certificate management tools keytool certutil, pk12util, modutil
Java Security Manageroff (default)on (default)on
Support JDBCRealm yesno
SingleSignOn (SSO)disable (default)enable (default)
Virtual Server Realms noyesno

With JDK 1.5 and NSS 3.11.4, Enterprise Profile in GlassFish v2 and SJSAS 8.x EE (but not available in GF v2 Cluster Profile) support the following:

  • management of the PKCS#11 modules using modutil
  • explicit reference of keys in PKCS#11 providers for https or iiop/SSL listeners. (Note that with JDK 1.5 or later, one can add PKCS#11 providers to a given JDK. But those keys cannot be references by current server.)
  • Elliptic Curve algorithm for SSL and other crypto operations (need Enterprise Profile GlassFish v2 and JDK 1.6)

In SJSAS 8.2 EE and the coming GlassFish v2 Enterprise Profile, there is support for the use of private key in Solaris 10 Softtoken. As an example, let us take a look at how to set up Solaris 10 Softtoken.

  1. Initialize Solaris 10 Softtoken password if you have not.

    /bin/pktool setpin

  2. Register the Solaris 10 Softtoken to NSS.

    modutil -dbdir $SJSAS_HOME/domains/domain1/config -force -add "Solaris 10 Softtoken" -libfile /usr/lib/ -mechanisms RSA:DSA

  3. Verify that the token is added properly and find out the corresponding token name.

    modutil -dbdir $SJSAS_HOME/domains/domain1/config -list

    A sample output is as follows:

    Using database directory ....
    Listing of PKCS #11 Modules
      1. NSS Internal PKCS #11 Module
             slots: 2 slots attached
            status: loaded
             slot: NSS Internal Cryptographic Services                            
            token: NSS Generic Crypto Services
             slot: NSS User Private Key and Certificate Services                  
            token: NSS Certificate DB
      2. Solaris 10 Softtoken
            library name: /usr/lib/
             slots: 1 slot attached
            status: loaded
             slot: Sun Crypto Softtoken
            token: Sun Software PKCS#11 softtoken

    In this case, the token name is "Sun Software PKCS#11 softtoken". And this will be used in subsequent commands.

  4. Create a private key and certificate in Solaris 10 Softtoken.

    certutil -S -x -n mytestcert -t "u,u,u" -v 120 -s "cn=j2ee,ou=J2EE,o=Sun,L=Santa Clara,ST=California,C=US" -d $SJSAS_HOME/domains/domain1/config -h "Sun Software PKCS#11 softtoken"

    A sample output is as follows:

    Enter Password or Pin for "Sun Software PKCS#11 softtoken":
    A random seed must be generated that will be used in the
    creation of your key.  One of the easiest ways to create a
    random seed is to use the timing of keystrokes on a keyboard.
    To begin, type keys on the keyboard until this progress meter
    Continue typing until the progress meter is full:
    Finished.  Press enter to continue: 
    Generating key.  This may take a few moments...
  5. Change the cert-nickname to "Sun Software PKCS#11 softtoken:mytestcert" in your listeners.

  6. Restart the server, then it will prompt the password for Solaris 10 Softtoken as follows:

    Please enter password for NSS slot Sun Software PKCS#11 softtoken>

Monday Apr 23, 2007

JDBCRealm in GlassFish with MySQL

In these few months, there were several discussions of using GlassFish JDBCRealm with MySQL. In this blog, I will share my experience about using GlassFish JDBCRealm with MySQL.

  1. Download the MySQL Community Server. I have downloaded the Solaris 10 (x86, 32 bit TAR package), version 5.0.37, of the "MySQL Community Server".

  2. Expand the download file.

    gunzip mysql-5.0.37-solaris10-i386.tar.gz
    tar xf mysql-5.0.37-solaris10-i386.tar

  3. cd mysql-5.0.37-solaris10-i386

    and read INSTALL-BINARY.

  4. Set up the grant table.


  5. Start the MySQL server.


  6. Set a password for the MySQL "root" user

    bin/mysqladmin -u root password YOUR_PASSWORD

  7. Create database and table. The following is a sample command.
    bin/mysql -u root --password=YOUR_PASSWORD
    create database database01;
    use database01;
    create table usertable(userid varchar(10) primary key, password varchar(32) not null);
    create table grouptable(userid varchar(10) not null, groupid varchar(20) not null, primary key (userid, groupid));
    alter table grouptable add constraint FK_USERID foreign key(userid) references usertable(userid);
    grant all privileges on *.* to 'root'@'YOUR_HOST' identified by 'YOUR_PASSWORD' with grant option;
    Note that you may like to replace YOUR_PASSWORD and YOUR_HOST in above.

  8. Populate user, group and passwor data. For the purpose of testing the database, you may try to use clear text password first as follows:
    insert into usertable values ('webuser', 'webuser');
    insert into grouptable values ('webuser', 'employee');
    For MD5, please take a look at another blog on JDBCRealm.

  9. Download the JDBC driver from Connectors > Connector/J . I have downloaded

  10. Unpack the package and copy the JDBC driver to $GLASS_HOME/lib.

    unzip mysql-connector-java-5.0.5-bin.jar
    cd mysql-connector-java-5.0.5
    cp mysql-connector-java-5.0.5-bin.jar $GLASSFISH_HOME/lib

  11. Restart the GlassFish server in order to pick up the JBDC driver.

  12. Create a Connector pool in Admin Console as follows:

    Resource Typejavax.sql.DataSource
    Database VendorMySQL

    then click "Next" and add the following properties:


    Note that different versions of the JDBC driver may have different properties. You may need to check the readme file there. Furthermore, you may need to remove extra default properties from Admin Console.

  13. Create a DataSource jdbc/mysql associated with the above pool.

  14. Create a JDBCRealm, named jdbcrealm with the following properties:


    Note that if you are using MD5 for password data, then you need to set value of digest-algorithm to MD5.

  15. Now a JDBCRealm is ready and it can be used by specifying it in deployment descriptors. If there is anything wrong and cannot authenticate, then one can turn on security log to FINE level and check if there is any exception in server.log.

Friday Apr 06, 2007

Multiple Private Keys in a GlassFish domain

GlassFish uses Java JKS for storing keys and certificates. Out of the box, the keyStore (keystore.jks) and the trustStore (cacerts.jks) reside in $GLASSFISH_HOME/domains/domain1. Even though there are several CA root certificates in cacerts.jks, there is only one private key in keystore.jks.

GlassFish supports the use of multiple private keys in a given domains. For instance, you may have two https listeners having different server private keys. This is a very useful scenario especially when one have EC key. So, in a given domain, we can have one https listener using RSA key for normal browser and one https listener using EC key for PDA.

In this blog, we will discuss the configuration when there are multiple private keys in a given domain of GlassFish. In this case, one needs to specify the private key / certificate to be used for SSL communication. If the information is not specified, then the server will pick up one which may not be desirable. Since one wants to be more precise in security environment, one would like to specify the corresponding certificate nickname in order to pick up the correct key.

There are two kinds of certificate nicknames: inbound, https outbound.

Inbound Certificate Nickname

One needs to specify the inbound cert-nickname for a given listener in domain.xml. For instance, in http listener, it is as follows:

    <http-listener ... security-enabled="true" ... />
      <ssl cert-nickname="s1as" ... />

Instead of hand-crafting the domain.xml, it would be a good idea to use Admin Console as follows: Configuration > HTTP Services > Http listeners > http-listener-2, and choose SSL tab and enter the valid alias value you want in "Certificate Nickname" textbox. Then one needs to restart the given domain (if there is a change of certificate nickname) in order to activate the change.

Similarly for iiop listeners.

Https Outbound Certificate Nickname

GlassFish also supports the https outbound from server. A private key / certificate is used for https outbound mutual SSL authentication. In this case, we can specify the https outbound certificate nickname as jvm-options in domain.xml:

One can achieve this through Admin Console as follows: Application Server > JVM Settings > JVM Options > Add JVM option, and enter the above jvm option in the new textbox. Then one needs to restart the server in order to activate this change.


Shing Wai Chan


« June 2016