Search in sources :

Example 1 with HttpServer

use of org.glassfish.grizzly.http.server.HttpServer in project jersey by jersey.

the class GrizzlyHttpServerFactory method createHttpServer.

/**
     * Create new {@link HttpServer} instance.
     *
     * @param uri                   uri on which the {@link ApplicationHandler} will be deployed. Only first path
     *                              segment will be used as context path, the rest will be ignored.
     * @param handler               {@link HttpHandler} instance.
     * @param secure                used for call {@link NetworkListener#setSecure(boolean)}.
     * @param sslEngineConfigurator Ssl settings to be passed to {@link NetworkListener#setSSLEngineConfig}.
     * @param start                 if set to false, server will not get started, this allows end users to set
     *                              additional properties on the underlying listener.
     * @return newly created {@code HttpServer}.
     * @throws ProcessingException in case of any failure when creating a new {@code HttpServer} instance.
     * @see GrizzlyHttpContainer
     */
public static HttpServer createHttpServer(final URI uri, final GrizzlyHttpContainer handler, final boolean secure, final SSLEngineConfigurator sslEngineConfigurator, final boolean start) {
    final String host = (uri.getHost() == null) ? NetworkListener.DEFAULT_NETWORK_HOST : uri.getHost();
    final int port = (uri.getPort() == -1) ? (secure ? Container.DEFAULT_HTTPS_PORT : Container.DEFAULT_HTTP_PORT) : uri.getPort();
    final NetworkListener listener = new NetworkListener("grizzly", host, port);
    listener.getTransport().getWorkerThreadPoolConfig().setThreadFactory(new ThreadFactoryBuilder().setNameFormat("grizzly-http-server-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    listener.setSecure(secure);
    if (sslEngineConfigurator != null) {
        listener.setSSLEngineConfig(sslEngineConfigurator);
    }
    final HttpServer server = new HttpServer();
    server.addListener(listener);
    // Map the path to the processor.
    final ServerConfiguration config = server.getServerConfiguration();
    if (handler != null) {
        final String path = uri.getPath().replaceAll("/{2,}", "/");
        final String contextPath = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
        config.addHttpHandler(handler, HttpHandlerRegistration.bulder().contextPath(contextPath).build());
    }
    config.setPassTraceRequest(true);
    config.setDefaultQueryEncoding(Charsets.UTF8_CHARSET);
    if (start) {
        try {
            // Start the server.
            server.start();
        } catch (final IOException ex) {
            server.shutdownNow();
            throw new ProcessingException(LocalizationMessages.FAILED_TO_START_SERVER(ex.getMessage()), ex);
        }
    }
    return server;
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ServerConfiguration(org.glassfish.grizzly.http.server.ServerConfiguration) HttpServer(org.glassfish.grizzly.http.server.HttpServer) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) IOException(java.io.IOException) NetworkListener(org.glassfish.grizzly.http.server.NetworkListener) ProcessingException(javax.ws.rs.ProcessingException)

Example 2 with HttpServer

use of org.glassfish.grizzly.http.server.HttpServer in project jersey by jersey.

the class GrizzlyWebContainerFactory method create.

private static HttpServer create(URI u, Class<? extends Servlet> c, Servlet servlet, Map<String, String> initParams, Map<String, String> contextInitParams) throws IOException {
    if (u == null) {
        throw new IllegalArgumentException("The URI must not be null");
    }
    String path = u.getPath();
    if (path == null) {
        throw new IllegalArgumentException("The URI path, of the URI " + u + ", must be non-null");
    } else if (path.isEmpty()) {
        throw new IllegalArgumentException("The URI path, of the URI " + u + ", must be present");
    } else if (path.charAt(0) != '/') {
        throw new IllegalArgumentException("The URI path, of the URI " + u + ". must start with a '/'");
    }
    path = String.format("/%s", UriComponent.decodePath(u.getPath(), true).get(1).toString());
    WebappContext context = new WebappContext("GrizzlyContext", path);
    ServletRegistration registration;
    if (c != null) {
        registration = context.addServlet(c.getName(), c);
    } else {
        registration = context.addServlet(servlet.getClass().getName(), servlet);
    }
    registration.addMapping("/*");
    if (contextInitParams != null) {
        for (Map.Entry<String, String> e : contextInitParams.entrySet()) {
            context.setInitParameter(e.getKey(), e.getValue());
        }
    }
    if (initParams != null) {
        registration.setInitParameters(initParams);
    }
    HttpServer server = GrizzlyHttpServerFactory.createHttpServer(u);
    context.deploy(server);
    return server;
}
Also used : ServletRegistration(org.glassfish.grizzly.servlet.ServletRegistration) WebappContext(org.glassfish.grizzly.servlet.WebappContext) HttpServer(org.glassfish.grizzly.http.server.HttpServer) Map(java.util.Map)

Example 3 with HttpServer

use of org.glassfish.grizzly.http.server.HttpServer in project jersey by jersey.

the class ExtendedWadlWebappOsgiTest method testWadlOptionsMethod.

@Test
public void testWadlOptionsMethod() throws Exception {
    // TODO - temporary workaround
    // This is a workaround related to issue JERSEY-2093; grizzly (1.9.5) needs to have the correct context
    // class loader set
    ClassLoader myClassLoader = this.getClass().getClassLoader();
    for (Bundle bundle : bundleContext.getBundles()) {
        if ("webapp".equals(bundle.getSymbolicName())) {
            myClassLoader = bundle.loadClass("org.glassfish.jersey.examples.extendedwadl.resources.MyApplication").getClassLoader();
            break;
        }
    }
    Thread.currentThread().setContextClassLoader(myClassLoader);
    // END of workaround; The entire block can be removed after grizzly is migrated to more recent version
    final ResourceConfig resourceConfig = createResourceConfig();
    final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);
    final Client client = ClientBuilder.newClient();
    String wadl = client.target(baseUri).path("items").queryParam(WadlUtils.DETAILED_WADL_QUERY_PARAM, "true").request(MediaTypes.WADL_TYPE).options(String.class);
    assertTrue("Generated wadl is of null length", !wadl.isEmpty());
    assertTrue("Generated wadl doesn't contain the expected text", wadl.contains("This is a paragraph"));
    checkWadl(wadl, baseUri);
    server.shutdownNow();
}
Also used : Bundle(org.osgi.framework.Bundle) CoreOptions.mavenBundle(org.ops4j.pax.exam.CoreOptions.mavenBundle) HttpServer(org.glassfish.grizzly.http.server.HttpServer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) Client(javax.ws.rs.client.Client) Test(org.junit.Test)

Example 4 with HttpServer

use of org.glassfish.grizzly.http.server.HttpServer in project jersey by jersey.

the class ExtendedWadlWebappOsgiTest method testExtendedWadl.

/**
     * Test checks that the WADL generated using the WadlGenerator api doesn't
     * contain the expected text.
     *
     * @throws java.lang.Exception in case of a test error.
     */
@Test
public void testExtendedWadl() throws Exception {
    // TODO - temporary workaround
    // This is a workaround related to issue JERSEY-2093; grizzly (1.9.5) needs to have the correct context
    // class loader set
    ClassLoader myClassLoader = this.getClass().getClassLoader();
    for (Bundle bundle : bundleContext.getBundles()) {
        if ("webapp".equals(bundle.getSymbolicName())) {
            myClassLoader = bundle.loadClass("org.glassfish.jersey.examples.extendedwadl.resources.MyApplication").getClassLoader();
            break;
        }
    }
    Thread.currentThread().setContextClassLoader(myClassLoader);
    // END of workaround - the entire block can be deleted after grizzly is updated to recent version
    // List all the OSGi bundles
    StringBuilder sb = new StringBuilder();
    sb.append("-- Bundle list -- \n");
    for (Bundle b : bundleContext.getBundles()) {
        sb.append(String.format("%1$5s", "[" + b.getBundleId() + "]")).append(" ").append(String.format("%1$-70s", b.getSymbolicName())).append(" | ").append(String.format("%1$-20s", b.getVersion())).append(" |");
        try {
            b.start();
            sb.append(" STARTED  | ");
        } catch (BundleException e) {
            sb.append(" *FAILED* | ").append(e.getMessage());
        }
        sb.append(b.getLocation()).append("\n");
    }
    sb.append("-- \n\n");
    LOGGER.fine(sb.toString());
    final ResourceConfig resourceConfig = createResourceConfig();
    final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);
    final Client client = ClientBuilder.newClient();
    final Response response = client.target(baseUri).path("application.wadl").request(MediaTypes.WADL_TYPE).buildGet().invoke();
    String wadl = response.readEntity(String.class);
    LOGGER.info("RESULT = " + wadl);
    assertTrue("Generated wadl is of null length", !wadl.isEmpty());
    assertTrue("Generated wadl doesn't contain the expected text", wadl.contains("This is a paragraph"));
    assertFalse(wadl.contains("application.wadl/xsd0.xsd"));
    server.shutdownNow();
}
Also used : Response(javax.ws.rs.core.Response) Bundle(org.osgi.framework.Bundle) CoreOptions.mavenBundle(org.ops4j.pax.exam.CoreOptions.mavenBundle) HttpServer(org.glassfish.grizzly.http.server.HttpServer) BundleException(org.osgi.framework.BundleException) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) Client(javax.ws.rs.client.Client) Test(org.junit.Test)

Example 5 with HttpServer

use of org.glassfish.grizzly.http.server.HttpServer in project jersey by jersey.

the class App method main.

public static void main(String[] args) {
    try {
        System.out.println("JAXB Jersey Example App");
        final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, createApp(), false);
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

            @Override
            public void run() {
                server.shutdownNow();
            }
        }));
        server.start();
        System.out.println(String.format("Application started.%nTry out %s%nStop the application using CTRL+C", BASE_URI));
        Thread.currentThread().join();
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : HttpServer(org.glassfish.grizzly.http.server.HttpServer) IOException(java.io.IOException)

Aggregations

HttpServer (org.glassfish.grizzly.http.server.HttpServer)57 IOException (java.io.IOException)33 ResourceConfig (org.glassfish.jersey.server.ResourceConfig)21 Test (org.junit.Test)11 Client (javax.ws.rs.client.Client)10 ServerConfiguration (org.glassfish.grizzly.http.server.ServerConfiguration)6 ProcessingException (javax.ws.rs.ProcessingException)5 Response (javax.ws.rs.core.Response)5 NetworkListener (org.glassfish.grizzly.http.server.NetworkListener)5 URI (java.net.URI)4 HashMap (java.util.HashMap)3 GrizzlyHttpContainer (org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer)3 CLStaticHttpHandler (org.glassfish.grizzly.http.server.CLStaticHttpHandler)2 SSLContextConfigurator (org.glassfish.grizzly.ssl.SSLContextConfigurator)2 SSLEngineConfigurator (org.glassfish.grizzly.ssl.SSLEngineConfigurator)2 ClientConfig (org.glassfish.jersey.client.ClientConfig)2 CoreOptions.mavenBundle (org.ops4j.pax.exam.CoreOptions.mavenBundle)2 Bundle (org.osgi.framework.Bundle)2 InstrumentedExecutorService (com.codahale.metrics.InstrumentedExecutorService)1 JsonFactory (com.fasterxml.jackson.core.JsonFactory)1