Oracle GlassFish Server 3.0.1 Embedded Server Guide

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


Example 3 Starting an Embedded GlassFish Server

This example shows code for setting the port of an embedded GlassFish Server. This example also includes the code from Example 1 for creating Server.Builder and Server objects.

...
import org.glassfish.api.embedded.*;
...
    Server.Builder builder = new Server.Builder("test");
    ...
    Server server = builder.build();
    server.createPort(8080);
...

Starting an Embedded GlassFish Server From an Application

To start an embedded GlassFish Server, invoke the start method of the Server 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 Server.Builder and Server objects.

...
import org.glassfish.api.embedded.*;
...
    Server.Builder builder = new Server.Builder("test");
    ...
    Server server = builder.build();
    server.createPort(8080);
    server.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 Server 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. When a user presses Enter, the application undeploys any deployed applications before stopping the server. For more information about undeploying applications, see Undeploying an Application. Code for creating a Server object is not shown in this example. For an example of code for creating a Server object, see Example 1.

...
import java.io.BufferedReader;
...
import org.glassfish.api.embedded.*;
...
    EmbeddedDeployer deployer = server.getDeployer();
    ...
    System.out.println("Press Enter to stop server");
        // wait for Enter
    new BufferedReader(new java.io.InputStreamReader(System.in)).readLine();
    deployer.undeployAll();
    server.stop();
...