com.sun.grizzly.http.embed
Class GrizzlyWebServer

java.lang.Object
  extended by com.sun.grizzly.http.embed.GrizzlyWebServer

public class GrizzlyWebServer
extends Object

This class creates a WebServer that listen for http request. By default, creating an instance of this class can be used as it is to synchronously serve resources located under webResourcesPath. By default, the StaticResourcesAdapter is used when there is no GrizzlyAdapter specified. The StaticResourcesAdapter allow servicing of static resources like html files, images files, etc. The GrizzlyAdapter provides developers with a simple and consistent mechanism for extending the functionality of the Grizzly WebServer and for bridging existing http based technology like JRuby-on-Rail, Servlet, Bayeux Protocol or any http based protocol.

You can extend the GrizzlyWebServer by adding one or serveral GrizzlyAdapter. If more that one are used, the GrizzlyAdapterChain will be used to map the request to its associated GrizzlyAdapters, using a Mapper. A GrizzlyAdapter gets invoked as soon as the http request has been parsed and decoded. The GrizzlyAdapter.service(GrizzlyRequest, GrizzlyResponse) method is invoked with a GrizzlyRequest and GrizzlyResponse that can be used to extend the functionality of the Web Server. By default, all http requests are synchronously executed.

Asynchronous request processing is automatically enabled as soon as one or several AsyncFilter are added, using the addAsyncFilter(com.sun.grizzly.arp.AsyncFilter) method. AsyncFilter can be used when asynchronous operation are required, like suspending the current http request, delaying the invocation of GrizzlyAdapter etc. The state of the request processing can be managed using AsyncExecutor, like resuming the process so GrizzlyAdapters can be invoked.

The following picture describes how AsyncFilter and GrizzlyAdapter are invoked.


 ----------------------------------------------------------------------------
 - AsyncFilter.doFilter() ---> AsyncExecutor.execute()    -------|          -
 -                                                               |          -
 -                                                               |          -
 -                                                               |          -
 - AsyncFilter.doFilter() <-- GrizzlyAdapter2.service()   <------|          -
 ----------------------------------------------------------------------------
 

Here is some examples:


 Synchronous Web Server servicing static resources
        GrizzlyWebServer ws = new GrizzlyWebServer("/var/www");
        try{
            ws.start();
        } catch (IOException ex){
            // Something when wrong.
        } 

 Synchronous Web Server servicing customized resources
        GrizzlyWebServer ws = new GrizzlyWebServer("/var/www");
        try{
            ws.addGrizzlyAdapter(new GrizzlyAdapter(){  

                public void service(GrizzlyRequest request, GrizzlyResponse response){
                    try {
                        response.getWriter().println("Grizzly is soon cool");
                    } catch (IOException ex) {                        
                    }
                }
            });
            ws.start();
        } catch (IOException ex){
            // Something when wrong.
        } 
 Synchronous Web Server servicing a Servlet

        GrizzlyWebServer ws = new GrizzlyWebServer("/var/www");
        try{
            ServletAdapter sa = new ServletAdapter();
            sa.setRootFolder("/Path/To/Exploded/War/File");
            sa.setServlet(new MyServlet());
            ws.addGrizzlyAdapter(sa);
            ws.start();
        } catch (IOException ex){
            // Something when wrong.
        } 
 Synchronous Web Server servicing two Servlet

        GrizzlyWebServer ws = new GrizzlyWebServer("/var/www");
        try{
            ServletAdapter sa = new ServletAdapter();
            sa.setRootFolder("/Path/To/Exploded/War/File");
            sa.setServlet(new MyServlet());
            ws.addGrizzlyAdapter(sa);

            ServletAdapter sa = new ServletAdapter();
            sa.setRootFolder("/Path/To/Exploded/War2/File");
            sa.setServlet(new MySecondServlet());
            ws.addGrizzlyAdapter(sa);

            ws.start();
        } catch (IOException ex){
            // Something when wrong.
        } 
 
 Asynchronous Web Server servicing customized resources
 The example below delay the request processing for 10 seconds, without holding 
 a thread.
 
        GrizzlyWebServer ws = new GrizzlyWebServer("/var/www");
        try{
            ws.addAsyncFilter(new AsyncFilter() {
                private final ScheduledThreadPoolExecutor scheduler = 
                        new ScheduledThreadPoolExecutor(1);
                public boolean doFilter(final AsyncExecutor asyncExecutor) {
                    //Throttle the request
                    scheduler.schedule(new Callable() {
                        public Object call() throws Exception {
                            asyncExecutor.execute();
                            asyncExecutor.postExecute();
                            return null;
                        }
                    }, 10, TimeUnit.SECONDS);

                    // Call the next AsyncFilter
                    return true;
                }
            });

            ws.addGrizzlyAdapter(new GrizzlyAdapter(){                  
                public void service(GrizzlyRequest request, GrizzlyResponse response){
                    try {
                        response.getWriter().println("Grizzly is soon cool");
                    } catch (IOException ex) {                        
                    }
                }
            });
            ws.start();
        } catch (IOException ex){
            // Something when wrong.
        } 
 Asynchronous Web Server servicing Servlet
 The example below delay the request processing for 10 seconds, without holding 
 a thread.
 
        GrizzlyWebServer ws = new GrizzlyWebServer("/var/www");
        try{
            ws.addAsyncFilter(new AsyncFilter() {
                private final ScheduledThreadPoolExecutor scheduler = 
                        new ScheduledThreadPoolExecutor(1);
                public boolean doFilter(final AsyncExecutor asyncExecutor) {
                    //Throttle the request
                    scheduler.schedule(new Callable() {
                        public Object call() throws Exception {
                            asyncExecutor.execute();
                            asyncExecutor.postExecute();
                            return null;
                        }
                    }, 10, TimeUnit.SECONDS);

                    // Call the next AsyncFilter
                    return true;
                }
            });

            ServletAdapter sa = new ServletAdapter();
            sa.setRootFolder("/Path/To/Exploded/War/File");
            sa.setServlet(new MyServlet());
            ws.addGrizzlyAdapter(sa);

            ws.start();
        } catch (IOException ex){
            // Something when wrong.
        }  
 Asynchronous Web Server servicing Servlet and supporting the Bayeux Protocol

        GrizzlyWebServer ws = new GrizzlyWebServer("/var/www");
        try{
            // Add Comet Support
            ws.addAsyncFilter(new CometAsyncFilter());

            //Add Bayeux support
            CometdAdapter cometdAdapter = new CometdAdapter();
            ws.addGrizzlyAdapter(cometdAdapter);

            ServletAdapter sa = new ServletAdapter();
            sa.setRootFolder("/Path/To/Exploded/War/File");
            sa.setServlet(new MyServlet());
            ws.addGrizzlyAdapter(sa);

            ws.start();
        } catch (IOException ex){
            // Something when wrong.
        } 
 Synchronous Web Server servicing static resources eand exposed using JMX Mbeans

        GrizzlyWebServer ws = new GrizzlyWebServer(path);    
        ws.enableJMX(new Management() {

            public void registerComponent(Object bean, ObjectName oname, String type) 
                    throws Exception{
                Registry.getRegistry().registerComponent(bean,oname,type);
            }

            public void unregisterComponent(ObjectName oname) throws Exception{
                Registry.getRegistry().
                        unregisterComponent(oname);
            }  
        });
        ws.start();
    }
}
 Synchronous Web Server servicing two Servlet
 
      GrizzlyWebServer ws = new GrizzlyWebServer(path);
        ServletAdapter sa = new ServletAdapter();
        sa.setRootFolder(".");
        sa.setServletInstance(new ServletTest("Adapter-1"));
        ws.addGrizzlyAdapter(sa, new String[]{"/Adapter-1"});

        ServletAdapter sa2 = new ServletAdapter();
        sa2.setRootFolder("/tmp");
        sa2.setServletInstance(new ServletTest("Adapter-2"));
        ws.addGrizzlyAdapter(sa2, new String[]{"/Adapter-2"});

        System.out.println("Grizzly WebServer listening on port 8080");
        ws.start();

  * Synchronous Web Server servicing two Servlet using SSL

      GrizzlyWebServer ws = new GrizzlyWebServer(443,path,5,true);
      SSlConfig sslConfig = new SSLConfig();
      sslConfig.setTrustStoreFile("Path-to-trustore");
      sslConfig.setKeyStoreFile("Path-to-Trustore");
      ws.setSSLConfig(sslConfig);

        ServletAdapter sa = new ServletAdapter();
        sa.setRootFolder(".");
        sa.setServletInstance(new ServletTest("Adapter-1"));
        ws.addGrizzlyAdapter(sa, new String[]{"/Adapter-1"});

        ServletAdapter sa2 = new ServletAdapter();
        sa2.setRootFolder("/tmp");
        sa2.setServletInstance(new ServletTest("Adapter-2"));
        ws.addGrizzlyAdapter(sa2, new String[]{"/Adapter-2"});

        System.out.println("Grizzly WebServer listening on port 8080");
        ws.start();
 

Author:
Jeanfrancois Arcand

Nested Class Summary
static class GrizzlyWebServer.PROTOCOL
           
 
Constructor Summary
GrizzlyWebServer()
          Create a default GrizzlyWebServer
GrizzlyWebServer(int port)
          Create a WebServer that listen on port
GrizzlyWebServer(int port, int maxThreads)
          Deprecated. use setMaxThreads(int) to set maximum number of threads in a thread pool
GrizzlyWebServer(int port, int maxThreads, String webResourcesPath)
          Deprecated. use setMaxThreads(int) to set maximum number of threads in a thread pool
GrizzlyWebServer(int port, int maxThreads, String webResourcesPath, boolean secure)
          Deprecated. use setMaxThreads(int) to set maximum number of threads in a thread pool
GrizzlyWebServer(int port, String webResourcesPath)
          Create a WebServer that listen on port
GrizzlyWebServer(int port, String webResourcesPath, boolean secure)
          Create a WebServer that listen for secure tls/https requests
GrizzlyWebServer(String webResourcesPath)
          Create a WebServer which server files from webResourcesPath
 
Method Summary
 void addAsyncFilter(AsyncFilter asyncFilter)
          Add an AsyncFilter.
 void addGrizzlyAdapter(GrizzlyAdapter grizzlyAdapter)
          Deprecated. - Use addGrizzlyAdapter(GrizzlyAdapter, String[])
 void addGrizzlyAdapter(GrizzlyAdapter grizzlyAdapter, String[] mapping)
          Add a GrizzlyAdapter with its associated mapping.
<T extends Deployable,V extends DeploymentConfiguration>
DeploymentID
deploy(T toDeploy, Deployer<T,V> deployer, V configuration)
          Deploy given deployable using provided deployer.
<T extends Deployable,V extends DeploymentConfiguration>
DeploymentID
deploy(URI fromURI, FromURIDeployer<T,V> deployer, V configuration)
          Deploy from given uri using provided deployer.
 void enableJMX(Management jmxManagement)
          Enable JMX Management by configuring the Management
 void enableProtocol(GrizzlyWebServer.PROTOCOL p)
          Enable support for protocol like HTTP or AJP (Apache Java Protocol like mod_jk)
 SelectorThread getSelectorThread()
          Return the underlying SelectorThread.
 Statistics getStatistics()
          Return a Statistics instance that can be used to gather statistics.
static GrizzlyWebServer newConfiguredInstance(String path)
          Return an already configured GrizzlyWebServer that can serves static resources.
 boolean removeGrizzlyAdapter(GrizzlyAdapter grizzlyAdapter)
          Remove a GrizzlyAdapter return true of the operation was successful.
 void setCoreThreads(int coreThreads)
          Set the initial number of threads in a thread pool.
 void setMaxThreads(int maxThreads)
          Set the maximum number of threads in a thread pool.
 void setSSLConfig(SSLConfig sslConfig)
          Set the SSLConfig instance used when https is required
 void start()
          Start the GrizzlyWebServer and start listening for http requests.
 void stop()
          Stop the GrizzlyWebServer.
<T extends Deployable,V extends DeploymentConfiguration>
void
undeploy(DeploymentID deploymentId, Deployer<T,V> deployer)
          Undeploy deploymentId using provided deployer.
 void useAsynchronousWrite(boolean asyncWrite)
          Set to true if you want to use asynchronous write operations.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

GrizzlyWebServer

public GrizzlyWebServer()
Create a default GrizzlyWebServer


GrizzlyWebServer

public GrizzlyWebServer(int port)
Create a WebServer that listen on port

Parameters:
port - The port opened

GrizzlyWebServer

public GrizzlyWebServer(String webResourcesPath)
Create a WebServer which server files from webResourcesPath

Parameters:
webResourcesPath - the path to the web resource (ex: /var/www)

GrizzlyWebServer

public GrizzlyWebServer(int port,
                        int maxThreads)
Deprecated. use setMaxThreads(int) to set maximum number of threads in a thread pool

Create a WebServer that listen on port

Parameters:
port - The port opened

GrizzlyWebServer

public GrizzlyWebServer(int port,
                        String webResourcesPath)
Create a WebServer that listen on port

Parameters:
port - The port opened
webResourcesPath - the path to the web resource (ex: /var/www)

GrizzlyWebServer

public GrizzlyWebServer(int port,
                        int maxThreads,
                        String webResourcesPath)
Deprecated. use setMaxThreads(int) to set maximum number of threads in a thread pool

Create a WebServer that listen on port

Parameters:
port - The port opened
maxThreads - The maximum number of Thread created
webResourcesPath - the path to the web resource (ex: /var/www)

GrizzlyWebServer

public GrizzlyWebServer(int port,
                        String webResourcesPath,
                        boolean secure)
Create a WebServer that listen for secure tls/https requests

Parameters:
port - The port opened
webResourcesPath - the path to the web resource (ex: /var/www)
secure - true if https needs to be used.

GrizzlyWebServer

public GrizzlyWebServer(int port,
                        int maxThreads,
                        String webResourcesPath,
                        boolean secure)
Deprecated. use setMaxThreads(int) to set maximum number of threads in a thread pool

Create a WebServer that listen for secure tls/https requests

Parameters:
port - The port opened
maxThreads - The maximum number of Thread created
webResourcesPath - the path to the web resource (ex: /var/www)
secure - true if https needs to be used.
Method Detail

getSelectorThread

public SelectorThread getSelectorThread()
Return the underlying SelectorThread. Only advanced users should manipulate that class.

Returns:
SelectorThread

addAsyncFilter

public void addAsyncFilter(AsyncFilter asyncFilter)
Add an AsyncFilter. Adding AsyncFilter automatically enable Grizzly Asynchronous Request Processing mode. AsyncFilters are always invoked before GrizzlyAdapter

Parameters:
asyncFilter - An AsyncFilter

addGrizzlyAdapter

public void addGrizzlyAdapter(GrizzlyAdapter grizzlyAdapter)
Deprecated. - Use addGrizzlyAdapter(GrizzlyAdapter, String[])

Add a GrizzlyAdapter. GrizzlyAdapter will be invoked by Grizzly in the order they are added, e.g the first added is always the first invoked. GrizzlyAdapters are always invoked after AsyncFilter

Parameters:
grizzlyAdapter - a GrizzlyAdapter

addGrizzlyAdapter

public void addGrizzlyAdapter(GrizzlyAdapter grizzlyAdapter,
                              String[] mapping)
Add a GrizzlyAdapter with its associated mapping. A request will be dispatched to a GrizzlyAdapter based on its mapping value.

Parameters:
grizzlyAdapter - a GrizzlyAdapter
mapping - An array contains the context path mapping information.

removeGrizzlyAdapter

public boolean removeGrizzlyAdapter(GrizzlyAdapter grizzlyAdapter)
Remove a GrizzlyAdapter return true of the operation was successful.


setSSLConfig

public void setSSLConfig(SSLConfig sslConfig)
Set the SSLConfig instance used when https is required


useAsynchronousWrite

public void useAsynchronousWrite(boolean asyncWrite)
Set to true if you want to use asynchronous write operations. Asynchronous write operations may significantly improve performance under high load, but may also consume more memory. Default is set to false.

Parameters:
asyncWrite - true to enabled asynchronous write I/O operations.

start

public void start()
           throws IOException
Start the GrizzlyWebServer and start listening for http requests. Calling this method several time has no effect once GrizzlyWebServer has been started.

Throws:
IOException - If can't startup.

enableJMX

public void enableJMX(Management jmxManagement)
Enable JMX Management by configuring the Management

Parameters:
jmxManagement - An instance of the Management interface

getStatistics

public Statistics getStatistics()
Return a Statistics instance that can be used to gather statistics. By default, the Statistics object is not gathering statistics. Invoking Statistics.startGatheringStatistics() will do it.


setCoreThreads

public void setCoreThreads(int coreThreads)
Set the initial number of threads in a thread pool.

Parameters:
coreThreads - the initial number of threads in a thread pool.

setMaxThreads

public void setMaxThreads(int maxThreads)
Set the maximum number of threads in a thread pool.

Parameters:
maxThreads - the maximum number of threads in a thread pool.

stop

public void stop()
Stop the GrizzlyWebServer.


newConfiguredInstance

public static final GrizzlyWebServer newConfiguredInstance(String path)
Return an already configured GrizzlyWebServer that can serves static resources.

Parameters:
path - the directory to serve static resource from.
Returns:
a ready to use GrizzlyWebServer that listen on port 8080

enableProtocol

public void enableProtocol(GrizzlyWebServer.PROTOCOL p)
Enable support for protocol like HTTP or AJP (Apache Java Protocol like mod_jk)

Parameters:
p - the GrizzlyWebServer.PROTOCOL

deploy

public <T extends Deployable,V extends DeploymentConfiguration> DeploymentID deploy(T toDeploy,
                                                                                    Deployer<T,V> deployer,
                                                                                    V configuration)
                    throws DeployException
Deploy given deployable using provided deployer.

Parameters:
toDeploy - Deployable to deploy.
deployer - to be used for deployment.
configuration - Deployment configuration.
Returns:
Deployment identification.
Throws:
DeployException - Deployment failed.

deploy

public <T extends Deployable,V extends DeploymentConfiguration> DeploymentID deploy(URI fromURI,
                                                                                    FromURIDeployer<T,V> deployer,
                                                                                    V configuration)
                    throws DeployException
Deploy from given uri using provided deployer.

Parameters:
fromURI - uri to deploy from.
deployer - to be used for deployment.
configuration - Deployment configuration.
Returns:
Deployment identification.
Throws:
DeployException - Deployment failed.

undeploy

public <T extends Deployable,V extends DeploymentConfiguration> void undeploy(DeploymentID deploymentId,
                                                                              Deployer<T,V> deployer)
Undeploy deploymentId using provided deployer.

Type Parameters:
T - Type of object to be deployed.
V - Deployment configuration type.
Parameters:
deploymentId - Deployment identification to be undeployed.
deployer - to be used for undeployng.


Copyright © 2012 Oracle Corporation. All Rights Reserved.