type=page
status=published
title=Eclipse GlassFish Server 7 Embedded Server Guide
prev=preface.html
~~~~~~

= Eclipse GlassFish Server 7 Embedded Server Guide

[[GSESG00001]][[gjldt]]


[[glassfish-server-open-source-edition-embedded-server-guide]]
== 1 Eclipse GlassFish Server 7 Embedded Server Guide

This document explains how to run applications in embedded GlassFish
Server Open Source Edition and to develop applications in which
GlassFish Server is embedded. This document is for software developers
who are developing applications to run in embedded GlassFish Server. The
ability to program in the Java language is assumed.

The following topics are addressed here:

* link:#giidt[Introduction to Embedded GlassFish Server]
* link:#gkubb[Embedded GlassFish Server File System]
* link:#giijw[Including the GlassFish Server Embedded Server API in Applications]
* link:#gijhs[Testing Applications with the Maven Plug-in for Embedded GlassFish Server]
* link:#gjlde[Using the EJB 3.1 Embeddable API with Embedded GlassFish Server]
* link:#gjlfe[Changing Log Levels in Embedded GlassFish Server]
* link:#gksmw[Default Java Persistence Data Source for Embedded GlassFish Server]
* link:#gihxf[Restrictions for Embedded GlassFish Server]

[[giidt]][[GSESG00035]][[introduction-to-embedded-glassfish-server]]

=== Introduction to Embedded GlassFish Server

Embedded Eclipse GlassFish Server enables you to use
GlassFish Server as a library. Embedded GlassFish Server also enables
you to run GlassFish Server inside any Virtual Machine for the Java
platform (Java Virtual Machine or JVMmachine).

No installation or configuration of embedded GlassFish Server is
required. The ability to run GlassFish Server inside applications
without installation or configuration simplifies the process of bundling
GlassFish Server with applications.


[NOTE]
====
Embedded GlassFish Server does not run on the Java Platform, Micro Edition (Java ME platform).
====

You can use embedded GlassFish Server in the following ways:

* With the Embedded Server API (see link:#giijw[Including the GlassFish
Server Embedded Server API in Applications])
* With the Maven Plug-in (see link:#gijhs[Testing Applications with the
Maven Plug-in for Embedded GlassFish Server])
* With the EJB 3.1 Embeddable API (see link:#gjlde[Using the EJB 3.1
Embeddable API with Embedded GlassFish Server])

Embedded GlassFish Server provides a plug-in for
http://maven.apache.org/[Apache Maven] (`http://maven.apache.org/`).
This plug-in simplifies the testing of applications by enabling you to
build an application and run it with GlassFish Server on a single
system. Testing and debugging are simplified because the need for an
installed and configured GlassFish Server is eliminated. Therefore, you
can run unit tests automatically in every build.


[NOTE]
====
For information on how to embed GlassFish Server in an OSGi environment,
see the link:../add-on-component-development-guide/toc.html#GSACG[GlassFish Server Open Source Edition Add-On
Component Development Guide].
====


[[gkubb]][[GSESG00036]][[embedded-glassfish-server-file-system]]

=== Embedded GlassFish Server File System

The following Embedded GlassFish Server directories and files are
important if you are referencing a nonembedded installation of GlassFish
Server:

* link:#gikqf[Installation Root Directory]
* link:#gikvf[Instance Root Directory]
* link:#giiak[The `domain.xml` File]

[[gikqf]][[GSESG00054]][[installation-root-directory]]

==== Installation Root Directory

The installation root directory, represented as as-install, is the
parent of the directory that embedded GlassFish Server uses for
configuration files. This directory corresponds to the base directory
for an installation of GlassFish Server. Configuration files are
contained in the following directories in the base directory for an
installation of GlassFish Server:

* `domains`
* `lib`

Specify the installation root directory only if you have a valid
nonembedded GlassFish Server installation and are using
`glassfish-embedded-static-shell.jar`.

[[gikvf]][[GSESG00055]][[instance-root-directory]]

==== Instance Root Directory

The instance root directory, represented as domain-dir, is the parent
directory of a server instance directory. Embedded GlassFish Server Open
Source Edition uses the server instance directory for domain
configuration files.

Specify the instance root directory only if you have a valid nonembedded
GlassFish Server domain directory and are using
`glassfish-embedded-static-shell.jar`.


[NOTE]
====
If you have valid nonembedded GlassFish Server as-install and domain-dir
directories, specify both in the `BootstrapProperties` and
`GlassFishProperties` classes respectively as described in
link:#gihyr[Creating and Configuring an Embedded GlassFish Server].
====


If domain-dir is not specified, GlassFish Server creates a directory
named ``gfembed``random-number``tmp`` in a temporary directory, where
random-number is a randomly generated 19-digit number. GlassFish Server
then copies configuration files into this directory. The temporary
directory is the value of the system property `java.io.tmpdir`. You can
override this value by specifying the `glassfish.embedded.tmpdir`
property in the `GlassFishProperties` class or as a system property.

[[giiak]][[GSESG00056]][[the-domain.xml-file]]

==== The `domain.xml` File

Using an existing `domain.xml` file avoids the need to configure
embedded GlassFish Server programmatically in your application. Your
application obtains domain configuration data from an existing
`domain.xml` file. You can create this file by using the administrative
interfaces of an installation of nonembedded GlassFish Server. To
specify an existing `domain.xml` file, invoke the `setConfigFileURI`
method of the `GlassFishProperties` class as described in
link:#gihyr[Creating and Configuring an Embedded GlassFish Server].


[NOTE]
====
The built-in `domain.xml` file used by default by Embedded GlassFish
Server can be downloaded from
`http://embedded-glassfish.java.net/domain.xml`. You can customize this
file and pass it in using the `setConfigFileURI` method while creating
an Embedded GlassFish Server.
====


[[giijw]][[GSESG00037]][[including-the-glassfish-server-embedded-server-api-in-applications]]

=== Including the GlassFish Server Embedded Server API in Applications

Eclipse 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:

* link:#giide[Setting the Class Path]
* link:#giiky[Creating, Starting, and Stopping Embedded GlassFish
Server]
* link:#giigc[Deploying and Undeploying an Application in an Embedded
GlassFish Server]
* link:#gjldy[Running `asadmin` Commands Using the GlassFish Server
Embedded Server API]
* link:#gikrt[Sample Applications]

[[giide]][[GSESG00057]][[setting-the-class-path]]

==== Setting the Class Path

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

`glassfish-embedded-nucleus.jar`::
  Corresponds to the nucleus distribution. Download this file from
  `http://download.java.net/maven/glassfish/org/glassfish/extras/glassfish-embedded-nucleus/`.
`glassfish-embedded-web.jar`::
  Contains classes needed for deploying Jakarta EE web applications.
  Download this file from
  `http://download.java.net/maven/glassfish/org/glassfish/extras/glassfish-embedded-web/`.
`glassfish-embedded-all.jar`::
  Contains classes needed for deploying all Jakarta EE application types.
  Download this file from
  `http://download.java.net/maven/glassfish/org/glassfish/extras/glassfish-embedded-all/`.
`glassfish-embedded-static-shell.jar`::
  Contains references to classes needed for deploying all Jakarta EE
  application types. Must be used with a nonembedded installation of
  GlassFish Server. Reference this file from the
  as-install`/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 link:#gikqf[Installation Root
  Directory].


[NOTE]
====
Oracle GlassFish Server only supports use of the
`glassfish-embedded-static-shell.jar` file. The other files are part of
Eclipse GlassFish Server and are offered without official support.
====


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.

[[giiky]][[GSESG00058]][[creating-starting-and-stopping-embedded-glassfish-server]]

==== 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:

* link:#gihyr[Creating and Configuring an Embedded GlassFish Server]
* link:#gihyz[Running an Embedded GlassFish Server]

[[gihyr]][[GSESG00043]][[creating-and-configuring-an-embedded-glassfish-server]]

===== 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.

[[sthref4]][[gksir]]

Table 1-1 Methods of the `BootstrapProperties` Class

[width="100%",cols="<29%,<33%,<38%",options="header",]
|===
|Purpose |Method |Default Value
|References an existing link:#gikqf[Installation Root Directory], also called as-install
a|[source]
----
setInstallRoot(String as-install)
----

|None. If `glassfish-embedded-static-shell.jar` is used, the
link:#gikqf[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.

[[sthref5]][[gkskl]]

Table 1-2 Methods of the `GlassFishProperties` Class

[width="100%",cols="<24%,<37%,<39%",options="header",]
|===
|Purpose |Method |Default Value
|References an existing link:#gikvf[Instance Root Directory], also
called domain-dir
a|
[source]
----
setInstanceRoot(String domain-dir)
----

a|
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
a|
[source]
----
setConfigFileURI(String configFileURI)
----
a|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
a|
[source]
----
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`.
====


[[GSESG00005]][[gikmz]]
Example 1-1 Creating an Embedded GlassFish Server

This example shows code for creating an Embedded GlassFish Server.

[source,java]
----
...
import org.glassfish.embeddable.*;
...
    GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish();
    glassfish.start();
...
----

[[GSESG00006]][[gksjo]]
Example 1-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`.

[source,java]
----
// ...
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();
    // ...
----

[[gihyz]][[GSESG00044]][[running-an-embedded-glassfish-server]]

===== Running an Embedded GlassFish Server

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

* link:#gjkxx[Setting the Port of an Embedded GlassFish Server From an Application]
* link:#gihzg[Starting an Embedded GlassFish Server From an Application]
* link:#gihzy[Stopping an Embedded GlassFish Server From an Application]

[[gjkxx]][[GSESG00002]][[setting-the-port-of-an-embedded-glassfish-server-from-an-application]]

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.
====


* To set the port directly, invoke the `setPort` method of the
`GlassFishProperties` object.
* To set the port indirectly, use a `domain.xml` file that sets the
port. For more information, see link:#giiak[The `domain.xml` File].

[[GSESG00007]][[gjkxc]]
Example 1-3 Setting the port of an Embedded GlassFish Server

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

[source,java]
----
...
import org.glassfish.embeddable.*;
...
    GlassFishProperties glassfishProperties = new GlassFishProperties();
    glassfishProperties.setPort("http-listener", 8080);
    glassfishProperties.setPort("https-listener", 8181);
...
----

[[gihzg]][[GSESG00003]][[starting-an-embedded-glassfish-server-from-an-application]]

Starting an Embedded GlassFish Server From an Application

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

[[GSESG00008]][[gilry]]
Example 1-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
link:#gikmz[Example 1-1] for creating a `GlassFish` object.

[source,java]
----
...
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();
...
----

[[gihzy]][[GSESG00004]][[stopping-an-embedded-glassfish-server-from-an-application]]

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:

* Undeploying deployed applications
* Releasing any resources that your application uses

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

[[GSESG00009]][[gilnz]]
Example 1-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 link:#gikmz[Example 1-1].

[source,java]
----
...
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.

[[giigc]][[GSESG00059]][[deploying-and-undeploying-an-application-in-an-embedded-glassfish-server]]

==== 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:

* link:#gilrf[To Deploy an Application From an Archive File or a Directory]
* link:#gilpm[Undeploying an Application]
* link:#gjrcs[Creating a Scattered Archive]
* link:#gkvgc[Creating a Scattered Enterprise Archive]

For general information about deploying applications in GlassFish
Server, see the link:../application-deployment-guide/toc.html#GSDPG[GlassFish Server Open Source Edition
Application Deployment Guide].

[[gilrf]][[GSESG00021]][[to-deploy-an-application-from-an-archive-file-or-a-directory]]

===== 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 Jakarta EE specifications define for the
type of archive that the file contains. For more information, see
"link:../application-deployment-guide/deploying-applications.html#GSDPG00004[Deploying Applications]" in GlassFish Server Open
Source Edition 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 Jakarta 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 "link:../application-deployment-guide/deploying-applications.html#GSDPG00043[To
Deploy an Application or Module in a Directory Format]" in GlassFish
Server Open Source Edition Application Deployment Guide.

If some of the resources needed by an application are not under the
application's directory, see link:#gjrcs[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, String... 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
link:../reference-manual/deploy.html#GSRFM00114[`deploy`(1)] subcommand parameters.
Simply quote each parameter in the method, for example `"--force=true"`.

[[GSESG00010]][[gioph]]
Example 1-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
link:#gikmz[Example 1-1] for creating `GlassFishProperties` and
`GlassFish` objects.

[source,java]
----
...
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.
...
----

[[gilpm]][[GSESG00045]][[undeploying-an-application]]

===== 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
link:../reference-manual/deploy.html#GSRFM00114[`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.

[[GSESG00011]][[gilwu]]
Example 1-7 Undeploying an Application

This example shows code for undeploying the application that was
deployed in link:#gioph[Example 1-6].

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

[[gjrcs]][[GSESG00046]][[creating-a-scattered-archive]]

===== 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.

[[sthref6]][[gjrdg]]

Table 1-3 Constructors and Methods of the `ScatteredArchive` Class

[width="100%",cols="<52%,<38%,<10%",options="header",]
|===
|Purpose |Method |Default Value
|Creates and names a scattered archive
a|[source,java]
----
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.
a|[source,java]
----
ScatteredArchive(String name, ScatteredArchive.Type type, File topDir)
----

|None

|Adds a directory to the classes classpath
a|[source,java]
----
addClassPath(File path)
----

|None

|Adds a metadata locator
a|[source,java]
----
addMetaData(File path)
----

|None

|Adds and names a metadata locator
a|[source,java]
----
addMetaData(File path, String name)
----

|None

|Gets the deployable URI for this scattered archive a|
[source,java]
----
toURI()
----

|None
|===


[[GSESG00012]][[gjrfq]]
Example 1-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 link:#gioph[Example 1-6] for deploying an application from an
archive file.

[source,java]
----
...
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();
...
----

[[gkvgc]][[GSESG00047]][[creating-a-scattered-enterprise-archive]]

===== 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.

[[sthref7]][[gkvgb]]

Table 1-4 Constructors and Methods of the `ScatteredEnterpriseArchive`
Class

[width="99%",cols="<42%,<48%,<10%",options="header",]
|===
|Purpose |Method |Default Value
|Creates and names a scattered enterprise archive a|
[source,java]
----
ScatteredEnterpriseArchive(String name)
----

 |None
|Adds a module or library a|
[source,java]
----
addArchive(File archive)
----

 |None
|Adds a module or library a|
[source,java]
----
addArchive(File archive, String name)
----

 |None
|Adds a module or library a|
[source,java]
----
addArchive(URI URI)
----

 |None
|Adds a module or library a|
[source,java]
----
addArchive(URI URI, String name)
----

 |None
|Adds a metadata locator a|
[source,java]
----
addMetaData(File path)
----

 |None
|Adds and names a metadata locator a|
[source,java]
----
addMetaData(File path, String name)
----

 |None
|Gets the deployable URI for this scattered archive a|
[source,java]
----
toURI()
----

 |None
|===


[[GSESG00013]][[gkvga]]
Example 1-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 tolink:#gjrfq[Example 1-8] for creating a scattered archive.

[source,java]
----
...
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();
...
----

[[gjldy]][[GSESG00060]][[running-asadmin-commands-using-the-glassfish-server-embedded-server-api]]

Running `asadmin` Commands Using the GlassFish Server Embedded Server
==== API

Running link:../reference-manual/asadmin.html#GSRFM00263[`asadmin`] 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 link:../administration-guide/toc.html#GSADG[GlassFish Server Open Source Edition Administration
Guide]. For detailed information about `asadmin` commands, see Section 1
of the link:../reference-manual/toc.html#GSRFM[GlassFish Server Open Source Edition 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 link:#gihyz[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.

[[GSESG00014]][[gjldj]]
Example 1-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 link:#gilry[Example 1-4].

[source,java]
----
...
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);
...
----

[[GSESG00015]][[gjlfm]]
Example 1-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
link:#gilry[Example 1-4].

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

For another way to change log levels, see link:#gjlfe[Changing Log
Levels in Embedded GlassFish Server].

[[gikrt]][[GSESG00061]][[sample-applications]]

==== Sample Applications

[[GSESG00016]][[gionq]]
Example 1-12 Using an Existing `domain.xml` File and Deploying an
Application From an Archive File

This example shows code for the following:

* Using the existing file
`c:\myapp\embeddedserver\domains\domain1\config\domain.xml` and
preserving this file when the application is stopped.
* Deploying an application from the archive file
`c:\samples\simple.war`.

[source,java]
----
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();
        }
    }
}
----

[[gijhs]][[GSESG00038]][[testing-applications-with-the-maven-plug-in-for-embedded-glassfish-server]]

=== Testing Applications with the Maven Plug-in for Embedded GlassFish Server

If you are using http://maven.apache.org/[Apache Maven]
(`http://maven.apache.org/`), the plug-in for embedded GlassFish Server
simplifies the testing of applications. This plug-in enables you to
build and start an unpackaged application with a single Maven goal.

The following topics are addressed here:

* link:#gihus[To Set Up Your Maven Environment]
* link:#giivt[To Build and Start an Application From Maven]
* link:#gijly[To Stop Embedded GlassFish Server]
* link:#gijjn[To Redeploy an Application That Was Built and Started From Maven]
* link:#gjkps[Maven Goals for Embedded GlassFish Server]

Predefined Maven goals for embedded GlassFish Server are described in
link:#gjkps[Maven Goals for Embedded GlassFish Server].

To use Maven with Embedded GlassFish Server and the EJB 3.1 Embeddable
API, see link:#gjxff[Using Maven with the EJB 3.1 Embeddable API and
Embedded GlassFish Server].

[[gihus]][[GSESG00022]][[to-set-up-your-maven-environment]]

==== To Set Up Your Maven Environment

Setting up your Maven environment enables Maven to download the required
embedded GlassFish Server distribution file when you build your project.
Setting up your Maven environment also identifies the plug-in that
enables you to build and start an unpackaged application with a single
Maven goal.

[[sthref8]]

Before You Begin

Ensure that http://maven.apache.org/[Apache Maven]
(`http://maven.apache.org/`) is installed.

1. Identify the Maven plug-in for embedded GlassFish Server.
+
Add the following `plugin` element to your POM file:
+
[source,xml]
----
...
        ...
        <plugins>
            ...
            <plugin>
                <groupId>org.glassfish</groupId>
                <artifactId>maven-embedded-glassfish-plugin</artifactId>
                <version>version</version>
            </plugin>
            ...
        </plugins>
...
----
version::
  The version to use. The version of the final promoted build for this
  release is `3.1.1`. The Maven plug-in is not bound to a specific version
  of GlassFish Server. You can specify the version you want to use. If
  no version is specified, a default version is used.

2. Configure the `embedded-glassfish` goal prefix, the application
name, and other standard settings.
+
Add the following `configuration` element to your POM file:
+
[source,xml]
----
...
        <plugins>
            ...
            <plugin>
                ...
                <configuration>
                    <goalPrefix>embedded-glassfish</goalPrefix>
                    ...
                    <app>target/test.war</app>
                    <port>8080</port>
                    <contextRoot>test</contextRoot>
                    <autoDelete>true</autoDelete>
                    ...
                </configuration>
                ...
            </plugin>
            ...
        </plugins>
...
----
app::
  In the app parameter, substitute the archive file or directory for your
  application. The optional port, contextRoot, and autoDelete parameters
  show example values. For details, see link:#gjkps[Maven Goals for
  Embedded GlassFish Server].

3. Perform advanced plug-in configuration. This step is optional.
Add the following `configuration` element to your POM file:
+
[source,xml]
----
...
        <plugins>
            ...
            <plugin>
                ...
                <configuration>
                    <goalPrefix>embedded-glassfish</goalPrefix>
                    <app>target/test.war</app>
                    <name>test</name>
                    <contextRoot>test</contextRoot>
                    <ports>
                        <http-listener>8080</http-listener>
                        <https-listener>8181</https-listener>
                    </ports>
                    <bootstrapProperties>
                        <property>test_key=test_value</property>
                    </bootstrapProperties>
                    <bootstrapPropertiesFile>bootstrap.properties</bootstrapPropertiesFile>
                    <glassfishProperties>
<property>embedded-glassfish-config.server.jms-service.jms-host.default_JMS_host.port=17676</property>
                    </glassfishProperties>
                    <glassfishPropertiesFile>glassfish.properties</glassfishPropertiesFile>
                    <systemProperties>
                        <property>ANTLR_USE_DIRECT_CLASS_LOADING=true</property>
                    </systemProperties>
                    <systemPropertiesFile>system.properties</systemPropertiesFile>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>start</goal>
                            <goal>deploy</goal>
                            <goal>undeploy</goal>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            ...
        </plugins>
...
----

4. Configure Maven goals.
Add `execution` elements to your POM file:
+
[source,xml]
----
...
        <plugins>
            ...
            <plugin>
                ...
                <executions>
                    <execution>
                        <phase>install</phase>
                        <goals>
                                <goal>goal</goal>
                        </goals>
                    </execution>
                </executions>
                ...
            </plugin>
            ...
        </plugins>
...
----
goal::
  The goal to use. See link:#gjkps[Maven Goals for Embedded GlassFish Server].

5. Configure the repository.
Add the following `repository` element to your POM file:
+
[source,xml]
----
<pluginRepositories>
    <pluginRepository>
        <id>maven2-repository.dev.java.net</id>
        <name>Java.net Repository for Maven</name>
        <url>http://download.java.net/maven/glassfish/</url>
    </pluginRepository>
</pluginRepositories>
----

[[GSESG00017]][[gjkod]]
Example 1-13 POM File for Configuring Maven to Use Embedded GlassFish Server

This example shows a POM file for configuring Maven to use embedded GlassFish Server.

[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!--
Line breaks in the following element are for readability purposes only
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>org.glassfish</groupId>
  <artifactId>maven-glassfish-plugin-tester</artifactId>
  <version>3.1</version>
  <name>Maven test</name>
  <build>
    <plugins>
      <plugin>
        <groupId>org.glassfish</groupId>
        <artifactId>maven-embedded-glassfish-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <goalPrefix>embedded-glassfish</goalPrefix>
          <app>target/test.war</app>
          <port>8080</port>
          <contextRoot>test</contextRoot>
          <autoDelete>true</autoDelete>
       </configuration>
       <executions>
          <execution>
             <phase>install</phase>
             <goals>
                   <goal>run</goal>
             </goals>
          </execution>
       </executions>
     </plugin>
    </plugins>
  </build>
  <pluginRepositories>
      <pluginRepository>
          <id>maven2-repository.dev.java.net</id>
          <name>Java.net Repository for Maven</name>
          <url>http://download.java.net/maven/glassfish/</url>
      </pluginRepository>
  </pluginRepositories>
</project>
----

[[giivt]][[GSESG00023]][[to-build-and-start-an-application-from-maven]]

==== To Build and Start an Application From Maven

If you are using Maven to manage the development of your application,
you can use a Maven goal to build and start the application in embedded
GlassFish Server.

[[sthref9]]

Before You Begin

Ensure that your Maven environment is configured, as described in
link:#gihus[To Set Up Your Maven Environment].

1. Include the path to the Maven executable file `mvn` in your path
statement.
2. Ensure that the `JAVA_HOME` environment variable is defined.
3. Create a directory for the Maven project for your application.
4. Copy to your project directory the POM file that you created in
link:#gihus[To Set Up Your Maven Environment].
5. Run the following command in your project directory:
+
[source]
----
mvn install
----
This command performs the following actions:
* Installs the Maven repository in a directory named `.m2` under your
home directory.
* Starts Embedded GlassFish Server.
* Deploys your application.
+
The application continues to run in Embedded GlassFish Server until
Embedded GlassFish Server is stopped.

[[gijly]][[GSESG00024]][[to-stop-embedded-glassfish-server]]

==== To Stop Embedded GlassFish Server

1. Change to the root directory of the Maven project for your
application.
2. Run the Maven goal to stop the application in embedded GlassFish
Server.
+
[source]
----
mvn embedded-glassfish:stop
----
This runs the `stop` method of the `GlassFish` object and any other
methods that are required to shut down the server in an orderly fashion.
See link:#gihzy[Stopping an Embedded GlassFish Server From an
Application].

[[gijjn]][[GSESG00025]][[to-redeploy-an-application-that-was-built-and-started-from-maven]]

==== To Redeploy an Application That Was Built and Started From Maven

An application that was built and started from Maven continues to run in
Embedded GlassFish Server until Embedded GlassFish Server is stopped.
While the application is running, you can test changes to the
application by redeploying it.

To redeploy, in the window from where the application was built and
started from Maven, press Enter.

[[gjkps]][[GSESG00062]][[maven-goals-for-embedded-glassfish-server]]

==== Maven Goals for Embedded GlassFish Server

You can use the following Maven goals to test your applications with
embedded GlassFish Server:

* link:#gjkxo[`embedded-glassfish:run` Goal]
* link:#gjkwy[`embedded-glassfish:start` Goal]
* link:#gjkvc[`embedded-glassfish:deploy` Goal]
* link:#gjkvg[`embedded-glassfish:undeploy` Goal]
* link:#gjkyl[`embedded-glassfish:stop` Goal]
* link:#gjkxq[`embedded-glassfish:admin` Goal]

[[gjkxo]][[GSESG00048]][[embedded-glassfishrun-goal]]

===== `embedded-glassfish:run` Goal

This goal starts the server and deploys an application. You can redeploy
if you change the application. The application can be a packaged archive
or a directory that contains an exploded application. You can set the
parameters described in the following table.

[[sthref10]][[gjkws]]

Table 1-5 `embedded-glassfish:run` Parameters

[width="100%",cols="<18%,<42%,<40%",options="header",]
|===
|Parameter |Default |Description
|app |None |The archive file or directory for the application to be deployed.

|serverID |`maven` |(optional) The ID of the server to start.

|containerType |`all` |(optional) The container to start: `web`, `ejb`, `jpa`, or `all`.

|installRoot |None |(optional) The link:#gikqf[Installation Root Directory].

|instanceRoot a|
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

 |(optional) The link:#gikvf[Instance Root Directory]

|configFile |domain-dir``/config/domain.xml`` |(optional) The
configuration file.

|port |None. Must be set explicitly or defined in the configuration
file. |The HTTP or HTTPS port.

|name a|
In order of precedence:

* The `application-name` or `module-name` in the deployment descriptor.
* The name of the archive file without the extension or the directory name.

For more information, see "link:../application-deployment-guide/overview.html#GSDPG00323[Naming Standards]" in
Eclipse GlassFish Server Application Deployment Guide.

 |(optional) The name of the application.

|contextRoot |The name of the application. |(optional) The context root
of the application.

|precompileJsp |`false` |(optional) If `true`, JSP pages are precompiled
during deployment.

|dbVendorName |None |(optional) The name of the database vendor for
which tables can be created. Allowed values are `javadb`, `db2`,
`mssql`, `mysql`, `oracle`, `postgresql`, `pointbase`, `derby` (also for
CloudScape), and `sybase`, case-insensitive.

|createTables |Value of the `create-tables-at-deploy` attribute in
`sun-ejb-jar.xml`. |(optional) If `true`, creates database tables during
deployment for beans that are automatically mapped by the EJB container.

|dropTables |Value of the `drop-tables-at-undeploy` attribute in
`sun-ejb-jar.xml`. a|
(optional) If `true`, and deployment and undeployment occur in the same
JVM session, database tables that were automatically created when the
bean(s) were deployed are dropped when the bean(s) are undeployed.

If `true`, the name parameter must be specified or tables may not be
dropped.

|autoDelete |`false` a|
(optional) If `true`, deletes the contents of the link:#gikvf[Instance
Root Directory] when the server is stopped.

Caution: Do not set `autoDelete` to `true` if you are using
`installRoot` to refer to a preexisting GlassFish Server installation.

|===


[[gjkwy]][[GSESG00049]][[embedded-glassfishstart-goal]]

===== `embedded-glassfish:start` Goal

This goal starts the server. You can set the parameters described in the
following table.

[[sthref11]][[gjkye]]

Table 1-6 `embedded-glassfish:start` Parameters

[width="100%",cols="<17%,<38%,<45%",options="header",]
|===
|Parameter |Default |Description
|serverID |`maven` |(optional) The ID of the server to start.

|containerType |`all` |(optional) The container to start: `web`, `ejb`,
`jpa`, or `all`.

|installRoot |None |(optional) The link:#gikqf[Installation Root
Directory].

|instanceRoot a|
In order of precedence:

* `glassfish.embedded.tmpdir` system property value
* `java.io.tmpdir` system property value
* as-install`/domains/domain1`

 |(optional) The link:#gikvf[Instance Root Directory]

|configFile |domain-dir`/config/domain.xml` |(optional) The
configuration file.

|port |None. Must be set explicitly or defined in the configuration
file. |The HTTP or HTTPS port.

|autoDelete |`false` a|
(optional) If `true`, deletes the contents of the link:#gikvf[Instance
Root Directory] when the server is stopped.

Caution: Do not set `autoDelete` to `true` if you are using
`installRoot` to refer to a preexisting GlassFish Server installation.

|===


[[gjkvc]][[GSESG00050]][[embedded-glassfishdeploy-goal]]

===== `embedded-glassfish:deploy` Goal

This goal deploys an application. You can redeploy if you change the
application. The application can be a packaged archive or a directory
that contains an exploded application. You can set the parameters
described in the following table.

[[sthref12]][[gjkvv]]

Table 1-7 `embedded-glassfish:deploy` Parameters

[width="100%",cols="<18%,<39%,<43%",options="header",]
|===
|Parameter |Default |Description
|app |None |The archive file or directory for the application to be
deployed.

|serverID |`maven` |(optional) The ID of the server to start.

|name a|
In order of precedence:

* The `application-name` or `module-name` in the deployment descriptor.
* The name of the archive file without the extension or the directory
name.

For more information, see "link:../application-deployment-guide/overview.html#GSDPG00323[Naming Standards]" in
Eclipse GlassFish Server Application Deployment Guide.

 |(optional) The name of the application.

|contextRoot |The name of the application. |(optional) The context root
of the application.

|precompileJsp |`false` |(optional) If `true`, JSP pages are precompiled
during deployment.

|dbVendorName |None |(optional) The name of the database vendor for
which tables can be created. Allowed values are `javadb`, `db2`,
`mssql`, `oracle`, `postgresql`, `pointbase`, `derby` (also for
CloudScape), and `sybase`, case-insensitive.

|createTables |Value of the `create-tables-at-deploy` attribute in
`sun-ejb-jar.xml`. |(optional) If `true`, creates database tables during
deployment for beans that are automatically mapped by the EJB container.
|===


[[gjkvg]][[GSESG00051]][[embedded-glassfishundeploy-goal]]

===== `embedded-glassfish:undeploy` Goal


[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.
====


This goal undeploys an application. You can set the parameters described
in the following table.

[[sthref13]][[gjkxf]]

Table 1-8 `embedded-glassfish:undeploy` Parameters

[width="100%",cols="<14%,<34%,<52%",options="header",]
|===
|Parameter |Default |Description
|name |If the name is omitted, all applications are undeployed. |The
name of the application.

|serverID |`maven` |(optional) The ID of the server to start.

|dropTables |Value of the `drop-tables-at-undeploy` attribute in
`sun-ejb-jar.xml`. a|
(optional) If `true`, and deployment and undeployment occur in the same
JVM session, database tables that were automatically created when the
bean(s) were deployed are dropped when the bean(s) are undeployed.

If `true`, the name parameter must be specified or tables may not be
dropped.

|cascade |`false` a|
(optional) If `true`, deletes all connection pools and connector
resources associated with the resource adapter being undeployed.

If `false`, undeployment fails if any pools or resources are still
associated with the resource adapter.

This attribute is applicable to connectors (resource adapters) and
applications with connector modules.

|===


[[gjkyl]][[GSESG00052]][[embedded-glassfishstop-goal]]

===== `embedded-glassfish:stop` Goal

This goal stops the server. You can set the parameters described in the
following table.

[[sthref14]][[gjkwm]]

Table 1-9 `embedded-glassfish:stop` Parameters

[width="100%",cols="<16%,<17%,<67%",options="header",]
|===
|Parameter |Default |Description
|serverID |`maven` |(optional) The ID of the server to stop.
|===


[[gjkxq]][[GSESG00053]][[embedded-glassfishadmin-goal]]

===== `embedded-glassfish:admin` Goal

This goal runs a GlassFish Server administration command. You must use
either the command and commandParameters parameters in combination or
the commandLine parameter. For more information about administration
commands, see the link:../reference-manual/toc.html#GSRFM[GlassFish Server Open Source Edition
Reference Manual]. You can set the parameters described in the following
table.

[[sthref15]][[gjkwe]]

Table 1-10 `embedded-glassfish:start` Parameters

[width="100%",cols="<24%,<10%,<66%",options="header",]
|===
|Parameter |Default |Description
|serverID |`maven` |(optional) The ID of the server on which to run the
command.

|command |None |The name of the command, for example
`createJdbcResource`.

|commandParameters |None |A map of the command parameters. See the
`org.glassfish.embeddable.admin.CommandParameters` class at
`http://glassfish.java.net/nonav/docs/v3/api/`.

|commandLine |None |The full `asadmin` syntax of the command.
|===


[[gjlde]][[GSESG00039]][[using-the-ejb-3.1-embeddable-api-with-embedded-glassfish-server]]

=== Using the EJB 3.1 Embeddable API with Embedded GlassFish Server

The EJB 3.1 Embeddable API is designed for unit testing of EJB modules.
You must use this API with a pre-installed, nonembedded GlassFish Server
instance. However, you can take advantage of Embedded GlassFish Server's
ease of use by referencing the nonembedded GlassFish Server instance
with the `glassfish-embedded-static-shell.jar` file.

Embedded GlassFish Server is not related to the EJB 3.1 Embeddable API,
but you can use these APIs together.

The Maven plug-in does not apply to embeddable EJB applications.
However, you can use Maven with the POM file shown in link:#gjxff[Using
Maven with the EJB 3.1 Embeddable API and Embedded GlassFish Server].

The EJB 3.1 Embeddable API is described in
http://jcp.org/en/jsr/detail?id=318[Java Specification Request (JSR)
318] (`http://jcp.org/en/jsr/detail?id=318`). An `ejb-embedded` sample
is included in the samples available at
http://www.oracle.com/technetwork/java/javaee/downloads/index.html[Java
EE 7 Downloads]
(`http://www.oracle.com/technetwork/java/javaee/downloads/index.html`)
or
http://www.oracle.com/technetwork/java/javaee/documentation/index.html[Code
Samples]
(`http://www.oracle.com/technetwork/java/javaee/documentation/index.html`).

The EJB 3.1 Embeddable API supports all EJB 3.1 Lite features with
addition of the EJB timer service and testing of EJB modules packaged in
a WAR file.

For EJB modules in a WAR file (or an exploded directory), if a web
application has one EJB module, and there are no other EJB modules in
the classpath, those entries (libraries) are ignored. If there are other
EJB modules, a temporary EAR file is created. For EJB modules in a WAR
file to be tested, the client code must use EJB modules with interfaces
or without annotations. Those EJB modules are not part of the classpath
and can't be loaded by the client class loader.

The following topics are addressed here:

* link:#gjlcr[To Use the EJB 3.1 Embeddable API with Embedded GlassFish
Server]
* link:#gksnv[EJB 3.1 Embeddable API Properties]
* link:#gjxff[Using Maven with the EJB 3.1 Embeddable API and Embedded
GlassFish Server]

[[gjlcr]][[GSESG00026]][[to-use-the-ejb-3.1-embeddable-api-with-embedded-glassfish-server]]

==== To Use the EJB 3.1 Embeddable API with Embedded GlassFish Server

1. To specify GlassFish Server as the Container Provider, include
`glassfish-embedded-static-shell.jar` or `glassfish-embedded-all.jar` in
the class path of your embeddable EJB application.
+
Reference the `glassfish-embedded-static-shell.jar` file from the
as-install`/lib/embedded` directory of a GlassFish Server installation.
Do not move this file or it will not work.
+
See link:#giide[Setting the Class Path] and Section 22.3.3 of the EJB
3.1 Specification, Embeddable Container Bootstrapping.
2. Configure any required resources.
+
For more information about configuring resources, see the Administration
Console Online Help or "link:../administration-guide/toc.html#GSADG00298[Resources and Services
Administration]" in Eclipse GlassFish Server Administration
Guide. The `jdbc/__default` Java DB database is preconfigured with all
distributions of GlassFish Server. However, if you are using
`glassfish-embedded-static-shell.jar`, you must start the database
manually.
+
If your embeddable EJB application uses Java Persistence, you do not
need to specify a JDBC resource. See link:#gksmw[Default Java
Persistence Data Source for Embedded GlassFish Server].
3. Invoke one of the `createEJBContainer` methods.
+

[NOTE]
====
Do not deploy your embeddable EJB application or any of its dependent
Jakarta EE modules before invoking one of the `createEJBContainer` methods.
These methods perform deployment in the background and do not load
previously deployed applications or modules.
====

4. To change the link:#gikvf[Instance Root Directory], set the
`org.glassfish.ejb.embedded.glassfish.instance.root` system property
value by using the `createEJBContainer``(Map<?, ?> properties)` method.
+
The default link:#gikvf[Instance Root Directory] location is
as-install`/domains/domain1` if a nonembedded installation is
referenced. This system property applies only to embeddable EJB
applications used with nonembedded GlassFish Server.
5. Close the EJB container properly to release all acquired resources
and threads.

[[gksnv]][[GSESG00063]][[ejb-3.1-embeddable-api-properties]]

==== EJB 3.1 Embeddable API Properties

Properties that can be passed to the
`EJBContainer#createEJBContainer(Properties)` method are summarized in
the following table. All properties are in the
`org.glassfish.ejb.embedded.glassfish` package. For example, the full
name of the `installation.root` property is
`org.glassfish.ejb.embedded.glassfish.installation.root`.

[[sthref16]][[gksop]]

Table 1-11 EJB 3.1 Embeddable API Properties

[width="100%",cols="<30%,<39%,<31%",options="header",]
|===
|Property |Default |Description
|`installation.root` |GlassFish Server installation location from which
`glassfish-embedded-static-shell.jar` is referenced |The
link:#gikqf[Installation Root Directory].

|`instance.root` a|
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

 |The link:#gikvf[Instance Root Directory].

|`configuration.file` |domain-dir`/config/domain.xml` |The configuration
file.

|`keep-temporary-files` |`false` |If `true`, keeps temporary files
(exploded EAR file and configuration file) created by the embedded EJB
container when Embedded GlassFish Server is stopped.

|`web.http.port` |None |Enables the web container if set. Needed for
testing web services in a WAR file. The value is ignored and can be an
empty string.

|`instance.reuse` |`false` |If `true`, no changes are made to the
existing configuration file, and a temporary server instance is not
created for the embedded run. Instead, execution happens against the
existing server instance. Do not use this option if the reused server
instance could be in use by the running nonembedded GlassFish Server.

|`skip-client-modules` |`false` |If `true`, omits modules from the
classpath if they are not specified using `EJBContainer.MODULES` and
have a manifest file with a `Main-Class` attribute.
|===


[[gjxff]][[GSESG00064]][[using-maven-with-the-ejb-3.1-embeddable-api-and-embedded-glassfish-server]]

==== Using Maven with the EJB 3.1 Embeddable API and Embedded GlassFish Server

When using Maven with the EJB 3.1 Embeddable API and Embedded GlassFish
Server, you cannot use the features of the Maven plug-in. You must start
and stop Embedded GlassFish Server manually or programmatically outside
of Maven.

[[GSESG00018]][[gjxds]]
Example 1-14 Maven POM File for Using the EJB 3.1 Embeddable API with
Embedded GlassFish Server

This example shows a POM file for configuring Maven to use the EJB 3.1
Embeddable API with Embedded GlassFish Server.

[source,xml]
----
<!--
Line breaks in the following element are for readability purposes only
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.glassfish</groupId>
    <artifactId>my-ejb-app-tester</artifactId>
    <version>3.1</version>
    <name>Maven test</name>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.extras</groupId>
            <artifactId>glassfish-embedded-static-shell</artifactId>
            <version>${project.version}</version>
            <scope>system</scope>
            <systemPath>
                ${env.S1AS_HOME}/lib/embedded/glassfish-embedded-static-shell.jar
            </systemPath>
        </dependency>
<!--
        The javaee-api is stripped of any code and is just used to compile your
        application. The scope provided in Maven means that it is used for compiling,
        but is also available when testing. For this reason, the javaee-api needs to
        be below the embedded Glassfish dependency. The javaee-api can actually be
        omitted when the embedded Glassfish dependency is included, but to keep your
        project Java-EE 6 rather than GlassFish 3, specification is important.
-->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <pluginRepositories>
        <pluginRepository>
            <id>maven2-repository.dev.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/glassfish/</url>
        </pluginRepository>
    </pluginRepositories>
</project>
----

If you are using `glassfish-embedded-static-shell.jar`, you can omit the
`dependency` element with the `javaee-api` `artifactId` and the
`pluginRepositories` element.

Set the `S1AS_HOME` environment variable to the installation root
directory before running the `mvn clean verify` command.

[[gjlfe]][[GSESG00040]][[changing-log-levels-in-embedded-glassfish-server]]

=== Changing Log Levels in Embedded GlassFish Server

To change log levels in Embedded GlassFish Server, you can follow the
steps in this section or you can use the Embedded Server API as shown in
link:#gjlfm[Example 1-11]. For more information about GlassFish Server
logging, see "link:../administration-guide/logging.html#GSADG00010[Administering the Logging Service]" in
Eclipse GlassFish Server Administration Guide.

You can change log levels in Embedded GlassFish Server in either of the
following ways:

* Using the GlassFish Server Embedded Server API
* Creating a custom logging configuration file

Both these ways use logger names. For a list of logger names, use the
link:../reference-manual/list-log-levels.html#GSRFM00183[`list-log-levels`] subcommand.

[[GSESG00019]][[gkrhh]]
Example 1-15 Using the GlassFish Server Embedded Server API

This example shows how to set log levels using the `getLogger` method in
the API.

[source,java]
----
import org.glassfish.embeddable.*;

// Create Embedded GlassFish
GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish();

// Set the log levels. For example, set 'deployment' and 'server' log levels to FINEST
Logger.getLogger("").getHandlers()[0].setLevel(Level.FINEST);
Logger.getLogger("jakarta.enterprise.system.tools.deployment").setLevel(Level.FINEST);
Logger.getLogger("jakarta.enterprise.system").setLevel(Level.FINEST);

// Start Embedded GlassFish and deploy an application.
// You will see all the FINEST logs printed on the console.
glassfish.start();
glassfish.getDeployer().deploy(new File("sample.war"));

// Dispose Embedded GlassFish
glassfish.dispose();
----

[[GSESG00020]][[gkrgw]]
Example 1-16 Creating a Custom Logging Configuration File

This example shows the contents of a custom logging configuration file,
`customlogging.properties`.

[source]
----
handlers= java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level = FINEST
jakarta.enterprise.system.tools.deployment.level = FINEST
jakarta.enterprise.system.level = FINEST
----

Pass the name of this custom logging configuration file to the `java`
command when you invoke Embedded GlassFish Server. For example:

[source]
----
java -Djava.util.logging.config.file=customlogging.properties MyEmbeddedGlassFish
----

[[gksmw]][[GSESG00041]][[default-java-persistence-data-source-for-embedded-glassfish-server]]

=== Default Java Persistence Data Source for Embedded GlassFish Server

The `jdbc/__default` Java DB database is preconfigured with Embedded
GlassFish Server. It is used when an application is deployed in Embedded
GlassFish Server that uses Java Persistence but doesn't specify a data
source. Embedded GlassFish Server uses the embedded Java DB database
created in a temporary domain that is destroyed when Embedded GlassFish
Server is stopped. You can use a Java DB database configured with
nonembedded GlassFish Server if you explicitly specify the instance root
directory or the configuration file.

By default, weaving is enabled when the GlassFish Server Embedded Server
API is used. To disable weaving, set the
`org.glassfish.persistence.embedded.weaving.enabled` property to
`false`.

[[gihxf]][[GSESG00042]][[restrictions-for-embedded-glassfish-server]]

=== Restrictions for Embedded GlassFish Server

The `glassfish-embedded-web.jar` file for embedded GlassFish Server
supports only these features of nonembedded GlassFish Server:

* The following web technologies of the Jakarta EE platform:

** Java Servlet API

** JavaServer Pages (JSP) technology

** JavaServer Faces technology
* JDBC-technology connection pooling
* Java Persistence API
* Java Transaction API
* Java Transaction Service

The `glassfish-embedded-all.jar` and
`glassfish-embedded-static-shell.jar` files support all features of
nonembedded GlassFish Server with these exceptions:

* Installers
* Administration Console
* Update Tool
* Apache Felix OSGi framework
* The Maven plug-in for embedded GlassFish Server does not support
application clients.
* Applications that require ports for communication, such as remote EJB
components, do not work with the EJB 3.1 Embeddable API running with
embedded GlassFish Server if a nonembedded GlassFish Server is running
in parallel.

Embedded GlassFish Server requires no installation or configuration. As
a result, the following files and directories are absent from the file
system until embedded GlassFish Server is started:

* `default-web.xml` file
* `domain.xml` file
* Applications directory
* Instance root directory

When embedded GlassFish Server is started, the base installation
directory that GlassFish Server uses depends on the options with which
GlassFish Server is started. If necessary, embedded GlassFish Server
creates a base installation directory. Embedded GlassFish Server then
copies the following directories and their contents from the Java
archive (JAR) file in which embedded GlassFish Server is distributed:

* `domains`
* `lib`

If necessary, GlassFish Server also creates an instance root directory.
