JavaScript is required to for searching.
Skip Navigation Links
Exit Print View
Oracle GlassFish Server 3.1 Embedded Server Guide
search filter icon
search icon

Document Information

Preface

Oracle GlassFish Server 3.1 Embedded Server Guide

Introduction to Embedded GlassFish Server

Embedded GlassFish Server File System

Installation Root Directory

Instance Root Directory

The domain.xml File

Including the GlassFish Server Embedded Server API in Applications

Setting the Class Path

Creating, Starting, and Stopping Embedded GlassFish Server

Creating and Configuring an Embedded GlassFish Server

Running an Embedded GlassFish Server

Setting the Port of an Embedded GlassFish Server From an Application

Starting an Embedded GlassFish Server From an Application

Stopping an Embedded GlassFish Server From an Application

Deploying and Undeploying an Application in an Embedded GlassFish Server

To Deploy an Application From an Archive File or a Directory

Undeploying an Application

Creating a Scattered Archive

Creating a Scattered Enterprise Archive

Running asadmin Commands Using the GlassFish Server Embedded Server API

Sample Applications

Using the EJB 3.1 Embeddable API with Embedded GlassFish Server

To Use the EJB 3.1 Embeddable API with Embedded GlassFish Server

EJB 3.1 Embeddable API Properties

Default Java Persistence Data Source for Embedded GlassFish Server

Index

Including the GlassFish Server Embedded Server API in Applications

Oracle GlassFish Server provides an application programming interface (API) for developing applications in which GlassFish Server is embedded. For details, see the org.glassfish.embeddable packages at http://embedded-glassfish.java.net/nonav/apidocs/.

The following topics are addressed here:

Setting the Class Path

To enable your applications to locate the class libraries for embedded GlassFish Server, add the following JAR file to your class path:

glassfish-embedded-static-shell.jar

Contains references to classes needed for deploying all Java EE application types. Must be used with a nonembedded installation of GlassFish Server. Reference this file from the as-install/glassfish/lib/embedded directory of a nonembedded GlassFish Server installation. Do not move this file or it will not work. For an explanation of as-install, see Installation Root Directory.


Note - Oracle GlassFish Server only supports use of the glassfish-embedded-static-shell.jar file.


In addition, add to the class path any other JAR files or classes upon which your applications depend. For example, if an application uses a database other than Java DB, include the Java DataBase Connectivity (JDBC) driver JAR files in the class path.

Creating, Starting, and Stopping Embedded GlassFish Server

Before you can run applications, you must set up and run the embedded GlassFish Server.

The following topics are addressed here:

Creating and Configuring an Embedded GlassFish Server

To create and configure an embedded GlassFish Server, perform these tasks:

  1. Instantiate the org.glassfish.embeddable.BootstrapProperties class.

  2. Invoke any methods for configuration settings that you require. This is optional.

  3. Invoke the GlassFishRuntime.bootstrap() or GlassFishRuntime.bootstrap(BootstrapProperties) method to create a GlassFishRuntime object.

  4. Instantiate the org.glassfish.embeddable.GlassFishProperties class.

  5. Invoke any methods for configuration settings that you require. This is optional.

  6. Invoke the glassfishRuntime.newGlassFish(GlassFishProperties) method to create a GlassFish object.

The methods of the BootstrapProperties class for setting the server configuration are listed in the following table. The default value of each configuration setting is also listed.

Table 1 Methods of the BootstrapProperties Class

Purpose
Method
Default Value
References an existing Installation Root Directory, also called as-install
setInstallRoot(String as-install)
None. If glassfish-embedded-static-shell.jar is used, the Installation Root Directory is automatically determined and need not be specified.

The methods of the GlassFishProperties class for setting the server configuration are listed in the following table. The default value of each configuration setting is also listed.

Table 2 Methods of the GlassFishProperties Class

Purpose
Method
Default Value
References an existing Instance Root Directory, also called domain-dir
setInstanceRoot(String domain-dir)
In order of precedence:
  • glassfish.embedded.tmpdir property value specified in GlassFishProperties object

  • glassfish.embedded.tmpdir system property value

  • java.io.tmp system property value

  • as-install/domains/domain1 if a nonembedded installation is referenced

Creates a new or references an existing configuration file
setConfigFileURI(String configFileURI)
In order of precedence:
  • domain-dir/config/domain.xml if domain-dir was set using setInstanceRoot

  • built-in embedded domain.xml

Specifies whether the configuration file is read-only
setConfigFileReadOnly(boolean readOnly)
true
Sets the port on which Embedded GlassFish Server listens.
setPort(String networkListener, int port)
none

Note - Do not use setPort if you are using setInstanceRoot or setConfigFileURI.


Example 1 Creating an Embedded GlassFish Server

This example shows code for creating an Embedded GlassFish Server.

...
import org.glassfish.embeddable.*;
...
    GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish();
    glassfish.start();
...

Example 2 Creating an Embedded GlassFish Server with configuration customizations

This example shows code for creating an Embedded GlassFish Server using the existing domain-dir C:\samples\test\applicationserver\domains\domain1.

...
import org.glassfish.embeddable.*;
...
    BootstrapProperties bootstrapProperties = new BootstrapProperties();
    bootstrapProperties.setInstallRoot("C:\\samples\\test\\applicationserver");    
    GlassFishRuntime glassfishRuntime = GlassFishRuntime.bootstrap(bootstrapProperties);

    GlassFishProperties glassfishProperties = new GlassFishProperties();
    glassfishProperties.setInstanceRoot("C:\\samples\\test\\applicationserver\\domains\\domain1");
    GlassFish glassfish = glassfishRuntime.newGlassFish(glassfishProperties);

    glassfish.start();

...

Running an Embedded GlassFish Server

After you create an embedded GlassFish Server as described in Creating and Configuring an Embedded GlassFish Server, you can perform operations such as:

Setting the Port of an Embedded GlassFish Server From an Application

You must set the server's HTTP or HTTPS port. If you do not set the port, your application fails to start and throws an exception. You can set the port directly or indirectly.


Note - Do not use setPort if you are using setInstanceRoot or setConfigFileURI. These methods set the port indirectly.


Example 3 Setting the port of an Embedded GlassFish Server

This example shows code for setting the port of an embedded GlassFish Server.

...
import org.glassfish.embeddable.*;
...
    GlassFishProperties glassfishProperties = new GlassFishProperties();
    glassfishProperties.setPort("http-listener", 8080);
    glassfishProperties.setPort("https-listener", 8181);
...
Starting an Embedded GlassFish Server From an Application

To start an embedded GlassFish Server, invoke the start method of the GlassFish object.

Example 4 Starting an Embedded GlassFish Server

This example shows code for setting the port and starting an embedded GlassFish Server. This example also includes the code from Example 1 for creating a GlassFish object.

...
import org.glassfish.embeddable.*;
...
    GlassFishProperties glassfishProperties = new GlassFishProperties();
    glassfishProperties.setPort("http-listener", 8080);
    glassfishProperties.setPort("https-listener", 8181);
    ...
    GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish(glassfishProperties);
    glassfish.start();
...
Stopping an Embedded GlassFish Server From an Application

The API for embedded GlassFish Server provides a method for stopping an embedded server. Using this method enables your application to stop the server in an orderly fashion by performing any necessary cleanup steps before stopping the server, for example:

To stop an embedded GlassFish Server, invoke the stop method of an existing GlassFish object.

Example 5 Stopping an Embedded GlassFish Server

This example shows code for prompting the user to press the Enter key to stop an embedded GlassFish Server. Code for creating a GlassFish object is not shown in this example. For an example of code for creating a GlassFish object, see Example 1.

...
import java.io.BufferedReader;
...
import org.glassfish.embeddable.*;
...
    System.out.println("Press Enter to stop server");
        // wait for Enter
    glassfish.stop(); // Stop Embedded GlassFish Server
...

As an alternative, you can use the dispose method to stop an embedded GlassFish Server and dispose of the temporary file system.

Deploying and Undeploying an Application in an Embedded GlassFish Server

Deploying an application installs the files that comprise the application into Embedded GlassFish Server and makes the application ready to run. By default, an application is enabled when it is deployed.

The following topics are addressed here:

For general information about deploying applications in GlassFish Server, see Oracle GlassFish Server 3.1 Application Deployment Guide.

To Deploy an Application From an Archive File or a Directory

An archive file contains the resources, deployment descriptor, and classes of an application. The content of the file must be organized in the directory structure that the Java EE specifications define for the type of archive that the file contains. For more information, see Chapter 2, Deploying Applications, in Oracle GlassFish Server 3.1 Application Deployment Guide.

Deploying an application from a directory enables you to deploy an application without the need to package the application in an archive file. The contents of the directory must match the contents of the expanded Java EE archive file as laid out by the GlassFish Server. The directory must be accessible to the machine on which the deploying application runs. For more information about the requirements for deploying an application from a directory, see To Deploy an Application or Module in a Directory Format in Oracle GlassFish Server 3.1 Application Deployment Guide.

If some of the resources needed by an application are not under the application's directory, see Creating a Scattered Archive.

  1. Instantiate the java.io.File class to represent the archive file or directory.
  2. Invoke the getDeployer method of the GlassFish object to get an instance of the org.glassfish.embeddable.Deployer class.
  3. Invoke the deploy(File archive, params) method of the instance of the Deployer object.

    Specify the java.io.File class instance you created previously as the first method parameter.

    For information about optional parameters you can set, see the descriptions of the deploy(1) command parameters. Simply quote each parameter in the method, for example "--force=true".

Example 6 Deploying an Application From an Archive File

This example shows code for deploying an application from the archive file c:\samples\simple.war and setting the name, contextroot, and force parameters. This example also includes the code from Example 1 for creating GlassFishProperties and GlassFish objects.

...
import java.io.File;
...
import org.glassfish.embeddable.*;
...
    GlassFishProperties glassfishProperties = new GlassFishProperties();
    glassfishProperties.setPort("http-listener", 8080);
    glassfishProperties.setPort("https-listener", 8181);
    ...
    GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish(glassfishProperties);
    glassfish.start();
    File war = new File("c:\\samples\\simple.war");
    Deployer deployer = glassfish.getDeployer();
    deployer.deploy(war, "--name=simple", "--contextroot=simple", "--force=true");
    // deployer.deploy(war) can be invoked instead. Other parameters are optional.
...

Undeploying an Application

Undeploy an application when the application is no longer required to run in GlassFish Server. For example, before stopping GlassFish Server, undeploy all applications that are running in GlassFish Server.


Note - If you reference a nonembedded GlassFish Server installation using the glassfish-embedded-static-shell.jar file and do not undeploy your applications in the same server life cycle in which you deployed them, expanded archives for these applications remain under the domain-dir/applications directory.


To undeploy an application, invoke the undeploy method of an existing Deployer object. In the method invocation, pass the name of the application as a parameter. This name is specified when the application is deployed.

For information about optional parameters you can set, see the descriptions of the deploy(1) command parameters. Simply quote each parameter in the method, for example "--cascade=true".

To undeploy all deployed applications, invoke the undeployAll method of an existing EmbeddedDeployer object. This method takes no parameters.

Example 7 Undeploying an Application

This example shows code for undeploying the application that was deployed in Example 6.

...
import org.glassfish.embeddable.*;
...
    deployer.undeploy(war, "--droptables=true", "--cascade=true");
...

Creating a Scattered Archive

Deploying a module from a scattered archive (WAR or JAR) enables you to deploy an unpackaged module whose resources, deployment descriptor, and classes are in any location. Deploying a module from a scattered archive simplifies the testing of a module during development, especially if all the items that the module requires are not available to be packaged.

In a scattered archive, these items are not required to be organized in a specific directory structure. Therefore, you must specify the location of the module's resources, deployment descriptor, and classes when deploying the module.

To create a scattered archive, perform these tasks:

  1. Instantiate the org.glassfish.embeddable.archive.ScatteredArchive class.

  2. Invoke the addClassPath and addMetadata methods if you require them.

  3. Invoke the toURI method to deploy the scattered archive.

The methods of this class for setting the scattered archive configuration are listed in the following table. The default value of each configuration setting is also listed.

Table 3 Constructors and Methods of the ScatteredArchive Class

Purpose
Method
Default Value
Creates and names a scattered archive
ScatteredArchive(String name, 
ScatteredArchive.Type type)
None
Creates and names a scattered archive based on a top-level directory. If the entire module is organized under the topDir, this is the only method necessary. The topDir can be null if other methods specify the remaining parts of the module.
ScatteredArchive(String name, 
ScatteredArchive.Type type,
File topDir)
None
Adds a directory to the classes classpath
addClassPath(File path)
None
Adds a metadata locator
addMetaData(File path)
None
Adds and names a metadata locator
addMetaData(File path,
String name)
None
Gets the deployable URI for this scattered archive
toURI()
None

Example 8 Deploying an Application From a Scattered Archive

This example shows code for creating a WAR file and using the addClassPath and addMetadata methods. This example also includes the code from Example 6 for deploying an application from an archive file.

...
import java.io.File;
...
import org.glassfish.embeddable.*;
...
    GlassFishProperties glassfishProperties = new GlassFishProperties();
    glassfishProperties.setPort("http-listener", 9090);
    GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish(glassfishProperties);
    glassfish.start();
    Deployer deployer = glassfish.getDeployer();
    ScatteredArchive archive = new ScatteredArchive("testapp", ScatteredArchive.Type.WAR);
    // target/classes directory contains complied servlets
    archive.addClassPath(new File("target", "classes"));
    // resources/sun-web.xml is the WEB-INF/sun-web.xml
    archive.addMetadata(new File("resources", "sun-web.xml"));
    // resources/web.xml is the WEB-INF/web.xml
    archive.addMetadata(new File("resources", "web.xml"));
    // Deploy the scattered web archive.
    String appName = deployer.deploy(archive.toURI(), "--contextroot=hello");

    deployer.undeploy(appName);
    glassfish.stop();
    glassfish.dispose();
...

Creating a Scattered Enterprise Archive

Deploying an application from a scattered enterprise archive (EAR) enables you to deploy an unpackaged application whose resources, deployment descriptor, and classes are in any location. Deploying an application from a scattered archive simplifies the testing of an application during development, especially if all the items that the application requires are not available to be packaged.

In a scattered archive, these items are not required to be organized in a specific directory structure. Therefore, you must specify the location of the application's resources, deployment descriptor, and classes when deploying the application.

To create a scattered enterprise archive, perform these tasks:

  1. Instantiate the org.glassfish.embeddable.archive.ScatteredEnterpriseArchive class.

  2. Invoke the addArchive and addMetadata methods if you require them.

  3. Invoke the toURI method to deploy the scattered enterprise archive.

The methods of this class for setting the scattered enterprise archive configuration are listed in the following table. The default value of each configuration setting is also listed.

Table 4 Constructors and Methods of the ScatteredEnterpriseArchive Class

Purpose
Method
Default Value
Creates and names a scattered enterprise archive
ScatteredEnterpriseArchive(String name)
None
Adds a module or library
addArchive(File archive)
None
Adds a module or library
addArchive(File archive,
String name)
None
Adds a module or library
addArchive(URI URI)
None
Adds a module or library
addArchive(URI URI,
String name)
None
Adds a metadata locator
addMetaData(File path)
None
Adds and names a metadata locator
addMetaData(File path,
String name)
None
Gets the deployable URI for this scattered archive
toURI()
None

Example 9 Deploying an Application From a Scattered Enterprise Archive

This example shows code for creating an EAR file and using the addArchive and addMetadata methods. This example also includes code similar toExample 8 for creating a scattered archive.

...
import java.io.File;
...
import org.glassfish.embeddable.*;
...
    GlassFishProperties glassfishProperties = new GlassFishProperties();
    glassfishProperties.setPort("http-listener", 9090);
    GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish(glassfishProperties);
    glassfish.start();
    Deployer deployer = glassfish.getDeployer();

    // Create a scattered web application.
    ScatteredArchive webmodule = new ScatteredArchive("testweb", ScatteredArchive.Type.WAR);
    // target/classes directory contains my complied servlets
    webmodule.addClassPath(new File("target", "classes"));
    // resources/sun-web.xml is my WEB-INF/sun-web.xml
    webmodule.addMetadata(new File("resources", "sun-web.xml"));
 
    // Create a scattered enterprise archive.
    ScatteredEnterpriseArchive archive = new ScatteredEnterpriseArchive("testapp");
    // src/application.xml is my META-INF/application.xml
    archive.addMetadata(new File("src", "application.xml"));
    // Add scattered web module to the scattered enterprise archive.
    // src/application.xml references Web module as "scattered.war". 
    //Hence specify the name while adding the archive.
    archive.addArchive(webmodule.toURI(), "scattered.war");
    // lib/mylibrary.jar is a library JAR file.
    archive.addArchive(new File("lib", "mylibrary.jar"));
    // target/ejbclasses contain my compiled EJB module.
    // src/application.xml references EJB module as "ejb.jar". 
    //Hence specify the name while adding the archive.
    archive.addArchive(new File("target", "ejbclasses"), "ejb.jar");
 
    // Deploy the scattered enterprise archive.
    String appName = deployer.deploy(archive.toURI());

    deployer.undeploy(appName);
    glassfish.stop();
    glassfish.dispose();
...

Running asadmin Commands Using the GlassFish Server Embedded Server API

Running asadmin(1M) commands from an application enables the application to configure the embedded GlassFish Server to suit the application's requirements. For example, an application can run the required asadmin commands to create a JDBC technology connection to a database.

For more information about configuring embedded GlassFish Server, see the Oracle GlassFish Server 3.1 Administration Guide. For detailed information about asadmin commands, see Section 1 of the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.


Note - Ensure that your application has started an embedded GlassFish Server before the application attempts to run asadmin commands. For more information, see Running an Embedded GlassFish Server.


The org.glassfish.embeddable package contains classes that you can use to run asadmin commands. Use the following code examples as templates and change the command name, parameter names, and parameter values as needed.

Example 10 Running an asadmin create-jdbc-resource Command

This example shows code for running an asadmin create-jdbc-resource command. Code for creating and starting the server is not shown in this example. For an example of code for creating and starting the server, see Example 4.

...
import org.glassfish.embeddable.*;
...
    String command = "create-jdbc-resource";
    String poolid = "--connectionpoolid=DerbyPool";
    String dbname = "jdbc/DerbyPool";
    CommandRunner commandRunner = glassfish.getCommandRunner();
    CommandResult commandResult = commandRunner.run(command, poolid, dbname);
...

Example 11 Running an asadmin set-log-level Command

This example shows code for running an asadmin set-log-level command. Code for creating and starting the server is not shown in this example. For an example of code for creating and starting the server, see Example 4.

...
import org.glassfish.embeddable.*;
...
    String command = "set-log-level";
    String weblevel = "javax.enterprise.system.container.web=FINE";
    CommandRunner commandRunner = glassfish.getCommandRunner();
    CommandResult commandResult = commandRunner.run(command, weblevel);
...

Sample Applications

Example 12 Using an Existing domain.xml File and Deploying an Application From an Archive File

This example shows code for the following:

import java.io.File;
import java.io.BufferedReader;
import org.glassfish.embeddable.*;

public class Main {
        
     /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        File configFile = new File ("c:\\myapp\\embeddedserver\\domains\\domain1\\config\\domain.xml");
        File war = new File("c:\\samples\\simple.war");
        try {
            GlassFishRuntime glassfishRuntime = GlassFishRuntime.bootstrap();
            ...
            GlassFishProperties glassfishProperties = new GlassFishProperties();
            glassfishProperties.setConfigFileURI(configFile.toURI());
            glassfishProperties.setConfigFileReadOnly(false);
            ...
            GlassFish glassfish = glassfishRuntime.newGlassFish(glassfishProperties);
            glassfish.start();
            
            Deployer deployer = glassfish.getDeployer();
            deployer.deploy(war, "--force=true");
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Press Enter to stop server");
        // wait for Enter
        new BufferedReader(new java.io.InputStreamReader(System.in)).readLine();
        try {
            glassfish.dispose();
            glassfishRuntime.shutdown();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}