示例#1
0
  public final ServerStarter start(Stage stage, Consumer<ServerBuilder> consumer) {
    notNull(consumer, "Null ServerBuilder consumer");

    /* Create a new injector and set up the module */
    final Injector injector =
        Guice.createInjector(stage, (binder) -> consumer.accept(new ServerBuilder(binder)));

    /* Get a hold on our HttpServer instance */
    final HttpServer server = injector.getInstance(HttpServer.class);
    final String serverName = server.getServerConfiguration().getName();

    /* Attempt to start our server */
    try {
      log.info("Starting server %s", serverName);
      server.start();
    } catch (IOException exception) {
      log.error(exception, "Exception starting server %s", serverName);
      System.exit(1);
    }

    /* Add a shutdown hook terminating the server on exit */
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                log.info("Shutting down server %s", serverName);
                server.shutdown();
              }
            });

    /* Return self for chaining */
    this.server = server;
    return this;
  }
 @Inject
 private void setup(Injector injector, HttpServer server) {
   final ServerConfiguration configuration = server.getServerConfiguration();
   configuration.setDefaultErrorPageGenerator(
       generator != null ? generator : injector.getInstance(key));
   log.info("Configured default error page generator on server \"%s\"", configuration.getName());
 }
示例#3
0
  public final void stop() {
    if (server == null) throw new IllegalStateException("Not started");

    final String serverName = server.getServerConfiguration().getName();
    log.info("Shutting down server %s", serverName);
    server.shutdown();
    server = null;
  }
  @Inject
  private void setup(HttpServer server) {
    final ServerConfiguration configuration = server.getServerConfiguration();
    configuration.getMonitoringConfig().getWebServerConfig().addProbes(probe);

    log.info(
        "Configured access log writing to \"%s\" on server \"%s\"",
        accessLog, configuration.getName());
  }
 public CrateHttpService(PersistentStateStore crateState, Configuration conf) {
   ResourceConfig httpConf =
       new ResourceConfig()
           .register(new CrateRestResource(crateState, conf))
           .packages(PACKAGE_NAMESPACE);
   URI httpUri =
       UriBuilder.fromPath("/").scheme("http").host("0.0.0.0").port(conf.apiPort).build();
   server = GrizzlyHttpServerFactory.createHttpServer(httpUri, httpConf);
   server.getServerConfiguration().addHttpHandler(new StaticHttpHandler(getRoot()), "/static");
 }
  public void start() {
    // set up server handler and handlers strategy
    handler = new HTTPHandler(strategy);
    server.getServerConfiguration().addHttpHandler(handler, "/getwsurl");

    try {
      server.start();
      logger.info("HTTP Server started");
    } catch (IOException e) {
      logger.error("HTTP Server couldnt start : " + e);
    }
  }
示例#7
0
  /**
   * @param docRoot the document root, can be <code>null</code> when no static pages are needed
   * @param host the network port to which this listener will bind
   * @param range port range to attempt to bind to
   * @return a <code>HttpServer</code> configured to listen to requests on <code>host</code>:<code>
   *     [port-range]</code>, using the specified <code>docRoot</code> as the server's document root
   */
  public static HttpServer createSimpleServer(
      final String docRoot, final String host, final PortRange range) {

    final HttpServer server = new HttpServer();
    final ServerConfiguration config = server.getServerConfiguration();
    if (docRoot != null) {
      config.addHttpHandler(new StaticHttpHandler(docRoot), "/");
    }
    final NetworkListener listener = new NetworkListener("grizzly", host, range);
    server.addListener(listener);
    return server;
  }
示例#8
0
  public static void main(String[] args)
      throws IOException, URISyntaxException, InterruptedException {
    final int port = System.getenv("PORT") != null ? Integer.valueOf(System.getenv("PORT")) : 8080;
    final URI baseUri = UriBuilder.fromUri("http://0.0.0.0/").port(port).build();
    final Application application =
        Application.builder(
                ResourceConfig.builder().packages(BarServer.class.getPackage().getName()).build())
            .build();
    application.addModules(new JsonJacksonModule());
    final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, application);
    httpServer
        .getServerConfiguration()
        .addHttpHandler(new StaticHttpHandler("src/main/webapp"), CONTENT_PATH);

    for (NetworkListener networkListener : httpServer.getListeners()) {
      if (System.getenv("FILE_CACHE_ENABLED") == null) {
        networkListener.getFileCache().setEnabled(false);
      }
    }

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                httpServer.stop();
              }
            });

    MongoURI mongolabUri =
        new MongoURI(
            System.getenv("MONGOLAB_URI") != null
                ? System.getenv("MONGOLAB_URI")
                : "mongodb://127.0.0.1:27017/hello");
    Mongo m = new Mongo(mongolabUri);
    mongoDB = m.getDB(mongolabUri.getDatabase());
    if ((mongolabUri.getUsername() != null) && (mongolabUri.getPassword() != null)) {
      mongoDB.authenticate(mongolabUri.getUsername(), mongolabUri.getPassword());
    }

    contentUrl = System.getenv("CONTENT_URL") != null ? System.getenv("CONTENT_URL") : CONTENT_PATH;

    Thread.currentThread().join();
  }
示例#9
0
  private HttpServer createHttpServer() {
    final HttpServer server = new HttpServer();

    final int requestSize = (int) currentConfig.getMaxRequestSize();
    final ServerConfiguration serverConfig = server.getServerConfiguration();
    serverConfig.setMaxBufferedPostSize(requestSize);
    serverConfig.setMaxFormPostSize(requestSize);
    serverConfig.setDefaultQueryEncoding(Charsets.UTF8_CHARSET);

    if (keepStats()) {
      setHttpStatsProbe(server);
    }

    // Configure the network listener
    final NetworkListener listener =
        new NetworkListener(
            "Rest2LDAP", NetworkListener.DEFAULT_NETWORK_HOST, initConfig.getListenPort());
    server.addListener(listener);

    // Configure the network transport
    final TCPNIOTransport transport = listener.getTransport();
    transport.setReuseAddress(currentConfig.isAllowTCPReuseAddress());
    transport.setKeepAlive(currentConfig.isUseTCPKeepAlive());
    transport.setTcpNoDelay(currentConfig.isUseTCPNoDelay());
    transport.setWriteTimeout(currentConfig.getMaxBlockedWriteTimeLimit(), TimeUnit.MILLISECONDS);

    final int bufferSize = (int) currentConfig.getBufferSize();
    transport.setReadBufferSize(bufferSize);
    transport.setWriteBufferSize(bufferSize);
    transport.setIOStrategy(SameThreadIOStrategy.getInstance());

    final int numRequestHandlers =
        getNumRequestHandlers(currentConfig.getNumRequestHandlers(), friendlyName);
    transport.setSelectorRunnersCount(numRequestHandlers);
    transport.setServerConnectionBackLog(currentConfig.getAcceptBacklog());

    // Configure SSL
    if (sslEngineConfigurator != null) {
      listener.setSecure(true);
      listener.setSSLEngineConfig(sslEngineConfigurator);
    }

    return server;
  }
示例#10
0
  public static void main(String[] args) throws Exception {
    final Server server = new DefaultServer();
    server.socketAction(
        new Action<ServerSocket>() {
          @Override
          public void on(final ServerSocket socket) {
            System.out.println("on socket: " + socket.uri());
            socket.on(
                "echo",
                new Action<Object>() {
                  @Override
                  public void on(Object data) {
                    System.out.println("on echo event: " + data);
                    socket.send("echo", data);
                  }
                });
            socket.on(
                "chat",
                new Action<Object>() {
                  @Override
                  public void on(Object data) {
                    System.out.println("on chat event: " + data);
                    server.all().send("chat", data);
                  }
                });
          }
        });

    HttpTransportServer httpTransportServer = new HttpTransportServer().transportAction(server);
    WebSocketTransportServer wsTransportServer =
        new WebSocketTransportServer().transportAction(server);

    HttpServer httpServer = HttpServer.createSimpleServer();
    ServerConfiguration config = httpServer.getServerConfiguration();
    config.addHttpHandler(new VibeHttpHandler().httpAction(httpTransportServer), "/vibe");
    NetworkListener listener = httpServer.getListener("grizzly");
    listener.registerAddOn(new WebSocketAddOn());
    WebSocketEngine.getEngine()
        .register("", "/vibe", new VibeWebSocketApplication().wsAction(wsTransportServer));
    httpServer.start();
    System.in.read();
  }
  public static void main(String[] args) {

    // create a basic server that listens on port 8080.
    final HttpServer server = HttpServer.createSimpleServer();

    final ServerConfiguration config = server.getServerConfiguration();

    // Map the path, /echo, to the NonBlockingEchoHandler
    config.addHttpHandler(new NonBlockingEchoHandler(), "/echo");

    try {
      server.start();
      Client client = new Client();
      client.run();
    } catch (IOException ioe) {
      LOGGER.log(Level.SEVERE, ioe.toString(), ioe);
    } finally {
      server.shutdownNow();
    }
  }
示例#12
0
 private MonitoringConfig<HttpProbe> getHttpConfig(HttpServer server) {
   return server.getServerConfiguration().getMonitoringConfig().getHttpConfig();
 }