Java org.glassfish.grizzly.http.server.HttpServer 代码实例

・18 分钟阅读

以下是展示如何使用org.glassfish.grizzly.http.server.HttpServer的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


private static void runHttpServer() throws IOException, InterruptedException {
        logger.info("Http Server starting");
        final HttpServer server = HttpServer.createSimpleServer("/",10024);
        final ServerConfiguration config = server.getServerConfiguration();
        config.addHttpHandler(new UpdateLocationApi(), "/yelli/update");
        config.addHttpHandler(new CreateTrackerApi(), "/yelli/create");
        config.addHttpHandler(new TestServelet(), "/yelli/test");
        config.setJmxEnabled(true);
        server.start();
}
 

实例 2


/**
 * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
 * @return Grizzly HTTP server.
 */
private static HttpServer startServer(String baseUri) throws IOException {
    final ResourceConfig rc = new ResourceConfig().packages("se252.jan15.calvinandhobbes.project0");       
    System.out.println("Trying to starting service at: " + baseUri);
    HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(URI.create(baseUri), rc, false);
    TCPNIOTransport transport = getListener(httpServer).getTransport();
    ThreadPoolConfig config = ThreadPoolConfig.defaultConfig()
            .setPoolName("worker-thread-").setCorePoolSize(20).setMaxPoolSize(20)
            .setQueueLimit(-1)/* same as default */;
    transport.configureBlocking(false);
    transport.setSelectorRunnersCount(3);
    transport.setWorkerThreadPoolConfig(config);
    transport.setIOStrategy(WorkerThreadIOStrategy.getInstance());
    transport.setTcpNoDelay(true);
    httpServer.start();
    System.out.println("Blocking Transport(T/F): "+transport.isBlocking());
    System.out.println("Num SelectorRunners: "+transport.getSelectorRunnersCount());
    System.out.println("Num WorkerThreads: "+transport.getWorkerThreadPoolConfig().getCorePoolSize());
    return httpServer;
}
 

实例 3


private static HttpServer createHttpServer(final URI uri,
                                           final GrizzlyHttpContainer handler,
                                           final boolean secure,
                                           final SSLEngineConfigurator sslEngineConfigurator,
                                           final int poolSize,
                                           final boolean enableSpdy)
        throws ProcessingException {
    final String host = (uri.getHost() == null) ? NetworkListener.DEFAULT_NETWORK_HOST
            : uri.getHost();
    final int port = (uri.getPort() == -1) ? 80 : uri.getPort();
    final HttpServer server = new HttpServer();
    final NetworkListener listener = new NetworkListener("grizzly", host, port);
    listener.setSecure(secure);
    if(sslEngineConfigurator != null) {
        listener.setSSLEngineConfig(sslEngineConfigurator);
    }
    if (poolSize > 0) {
        TCPNIOTransport transport = listener.getTransport();
        transport.getKernelThreadPoolConfig().setMaxPoolSize(poolSize);
    }
    if (enableSpdy) {
        SpdyAddOn spdyAddOn = new SpdyAddOn(SpdyMode.NPN);
        System.out.printf("SPDY: max conc. streams: %d%n", spdyAddOn.getMaxConcurrentStreams());
        listener.registerAddOn(spdyAddOn);
    }
    listener.setSecure(secure);
    server.addListener(listener);
    // Map the path to the processor.
    final ServerConfiguration config = server.getServerConfiguration();
    if (handler != null) {
        config.addHttpHandler(handler, uri.getPath());
    }
    config.setPassTraceRequest(true);
    try {
        // Start the server.
        server.start();
    } catch (IOException ex) {
        throw new ProcessingException("IOException thrown when trying to start grizzly server", ex);
    }
    return server;
}
 

实例 4


public static void main(String[] args){
    int port = 9002;
    if(args.length >= 1)
        port = Integer.parseInt(args[0]);
    if(Coordinator.SINGLE_INSTANCE == null){
        Coordinator coord = new Coordinator();
        coord.setModelRepo(new FacadeBridge());
        Coordinator.SINGLE_INSTANCE = coord;
        coord.start();
        //Only for test purpose
        coord.process("!extended { name : LoadDeployment, params : ['sample://sensapp'] }", commonStub);
    }
    URI uri = UriBuilder.fromUri("http://0.0.0.0/").port(port).build();
    ResourceConfig resourceConfig = new ResourceConfig(QueryResource.class);
    resourceConfig.register(UniversalResource.class);
    resourceConfig.register(CommitResource.class);
    HttpServer server = GrizzlyHttpServerFactory.createHttpServer(uri, resourceConfig);
    try {
        server.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
    while(true){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            Logger.getLogger(RestDaemon.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
 

实例 5


private HttpServer startHttpServer(int port, HttpHandler httpHandler) throws IOException {
    HttpServer httpServer = createHttpServer(port);
    httpServer.getServerConfiguration().addHttpHandler(httpHandler, CONTEXT_ROOT + "/echo");
    httpServer.start();
    return httpServer;
}
 

实例 6


public static void main(String[] args) {
    try{
        URI baseUri = UriBuilder.fromUri("http://127.0.0.1/rest").port(9998).build();
        final ResourceConfig resourceConfig = new ResourceConfig(LPRESTService.class);
        HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri,resourceConfig, false);
        server.start();
    }catch(Exception ex){ex.printStackTrace(); Utils.log(ex);}
}
 

实例 7


private static void startServer() {
        HttpServer server = HttpServer.createSimpleServer("", Integer.parseInt(port));
        try {
                addServlet(server, new TestConnectionServlet(), "testConnection");
                addServlet(server, new CsInstrumentServlet(), URL_PATH_INSTRUMENTATION + "/instrument");
                addServlet(server, new CsUninstrumentServlet(), URL_PATH_INSTRUMENTATION + "/uninstrument");
                addServlet(server, new GetStateServlet(), URL_PATH_INSTRUMENTATION + "/getState");
                addServlet(server, new GetSupportedExtensionsServlet(), URL_PATH_INSTRUMENTATION
                                + "/getSupportedExtensions");
                addServlet(server, new EnableMeasurementServlet(), URL_PATH_MEASUREMENT + "/enable");
                addServlet(server, new DisableMeasurementServlet(), URL_PATH_MEASUREMENT + "/disable");
                addServlet(server, new GetDataServlet(), URL_PATH_MEASUREMENT + "/getdata");
                addServlet(server, new CurrentTimeServlet(), URL_PATH_MEASUREMENT + "/currentTime");
                addServlet(server, new MeasureOverheadServlet(), URL_PATH_MEASUREMENT + "/measureOverhead");
                addServlet(server, new MeasurementStateServlet(), URL_PATH_MEASUREMENT + "/monitoringState");
                server.start();
                getLogger().info("Started Instrumentation Agent Server: {}.", getAddress());
        } catch (IllegalArgumentException iae) {
                getLogger().error("Illegal Argument Exception happend in main method of ServerLauncher: {}",
                                iae.getMessage());
        } catch (IOException ioe) {
                getLogger().error("IO Exception happend in main method of ServerLauncher: {}", ioe.getMessage());
        }
}
 

实例 8


public static void main(String[] args) {
    try {
        System.out.println("${projectName}");
        final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new MyApplication(), false);
        Runtime.getRuntime().addShutdownHook(new Thread(server::shutdownNow));
        server.start();
        System.out.println(String.format(
                "Application started.${symbol_escape}n"
                        + "Try out %s%s${symbol_escape}n"
                        + "Stop the application using CTRL+C",
                BASE_URI, ROOT_PATH));
        Thread.currentThread().join();
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 

实例 9


public static void main(String[] args) throws IOException {
        if(args.length != 1 && args.length !=2){
                System.out.println("Please pass the public IP or public hostname of the local machine/VM as parameter. e.g. ec2-54-254-184-72.ap-southeast-1.compute.amazonaws.com");
                System.out.println("You can also optionally pass a port number for the REST service. 8081 is used by default.");
                return;
        }
        int port = args.length == 2 ? Integer.parseInt(args[1]) : 8081;
        String baseUri = "http://" + args[0] + ":" + port + "/cloud_project";
    final HttpServer server = startServer(baseUri);
    System.out.println(String.format("Jersey app started with WADL available at "
            + "%s/application.wadlnHit enter to stop it...", baseUri));
    System.in.read();
    server.shutdownNow();
}
 

实例 10


public static void main(String[] args) throws IOException {
        if(args.length != 2 && args.length !=3){
                System.out.println("Please pass the URL of the REST service, and the public IP/hostname of the local VM as parameters. e.g. http://ec2-54-254-184-72.ap-southeast-1.compute.amazonaws.com:8080/project0/  ec2-54-254-184-72.ap-southeast-1.compute.amazonaws.com");
                System.out.println("You can also optionally pass a port number for the web form server. 8080 is used by default.");
                return;
        }
        int port = args.length == 3 ? Integer.parseInt(args[2]) : 8080;
        String webBaseUri = "http://" + args[1] + ":" + port + "/cloud_project";
        restBaseUri = args[0];
    final HttpServer server = startServer(webBaseUri);
    System.out.println(String.format("Jersey app started with WADL available at "
            + "%s/application.wadlnHit enter to stop it...", webBaseUri));
    System.in.read();
    server.shutdownNow();
}
 

实例 11


@Test(timeout = TIMEOUT)
public void testStartup() throws Exception {
    PortAssert.assertPortFree(port);
    HttpServer httpServer = ConverterServerBuilder.builder()
            .disable(MicrosoftWordBridge.class)
            .disable(MicrosoftExcelBridge.class)
            .enable(PseudoConverter.class)
            .baseUri(String.format("http://localhost:%d", port))
            .build();
    PortAssert.assertPortBusy(port);
    httpServer.shutdownNow();
    PortAssert.assertPortFree(port);
}
 

实例 12


/**
 * Starts a standalone conversion server. Detailed documentation can be retrieved by invoking
 * the application via the command line with the {@code -?} option.
 *
 * @param args The parameters for configuring this server.
 */
public static void main(String[] args) {
    try {
        ConverterServerBuilder builder = asBuilder(args);
        HttpServer httpServer = builder.build();
        Logger logger = LoggerFactory.getLogger(StandaloneServer.class);
        try {
            sayHello(builder, logger);
            System.out.println("The documents4j server is up and running. Hit the enter key to shut it down...");
            if (System.in.read() == -1) {
                logger.warn("Console read terminated without receiving user input");
            }
            sayGoodbye(builder, logger);
        } finally {
            httpServer.shutdownNow();
        }
        System.out.println("Shut down successful. Goodbye!");
    } catch (Exception e) {
        LoggerFactory.getLogger(StandaloneServer.class).error("The documents4j server terminated with an unexpected error", e);
        System.err.println(String.format("Error: %s", e.getMessage()));
        System.err.println("Use option -? to display a list of legal commands.");
        System.exit(-1);
    }
}
 

实例 13


/**
 * Main method.
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    String port = "8080";
    if(args.length > 0 ){
        port = args[0];
    }
    final HttpServer server = startServer(port);
    System.out.println(String.format("Jersey app started with WADL available at "
            + "%sapplication.wadlnHit enter to stop it...", uri));
    System.in.read();
    server.shutdownNow();
}
 

实例 14


public static void main(String[] args) throws IOException {
    final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new JerseyApplication());
    System.out.println("Press any key to close");
    System.in.read();
    server.shutdownNow();
}
 

实例 15


private void testRetryAfter(String retryAfter) throws DeploymentException, InterruptedException, IOException,
        AuthenticationException {
    HttpServer httpServer = null;
    try {
        httpServer = startHttpServer(
                REDIRECTION_PORT,
                new MultipleRetryAfterHandler(1, retryAfter, "ws://localhost:8025/retry-after-echo/echo"));
        final ClientManager client = ClientManager.createClient();
        final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
        final CountDownLatch messageLatch = new CountDownLatch(1);
        client.getProperties().put(ClientProperties.REDIRECT_ENABLED, true);
        client.getProperties().put(ClientProperties.RETRY_AFTER_SERVICE_UNAVAILABLE, true);
        client.connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig EndpointConfig) {
                try {
                    session.addMessageHandler(new MessageHandler.Whole<String>() {
                        @Override
                        public void onMessage(String message) {
                            System.out.println("received message: " + message);
                            assertEquals(message, "Do or do not, there is no try.");
                            messageLatch.countDown();
                        }
                    });
                    session.getBasicRemote().sendText("Do or do not, there is no try.");
                } catch (IOException e) {
                    // do nothing
                }
            }
        }, cec, URI.create("ws://localhost:8026/retry-after-echo/echo"));
        assertTrue("Message has not been received", messageLatch.await(1, TimeUnit.SECONDS));
    } finally {
        if (httpServer != null) {
            httpServer.shutdownNow();
        }
    }
}
 
讨论
淘淘あ西西 profile image