@SuppressWarnings("deprecation")
 @After
 public void tearDown() throws Exception {
   if (server != null && server.isStarted()) {
     server.stop();
   }
 }
Ejemplo n.º 2
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;
  }
Ejemplo n.º 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;
  }
Ejemplo n.º 4
0
Archivo: App.java Proyecto: kiwiwin/gez
  public static void main(String[] args) throws IOException, InterruptedException {
    final HttpServer httpServer = startServer();

    while (true) {
      try {
        Thread.sleep(10000);
      } catch (InterruptedException e) {
        httpServer.shutdownNow();
      }
    }
  }
Ejemplo n.º 5
0
  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);
    }
  }
Ejemplo n.º 6
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;
  }
Ejemplo n.º 7
0
 /**
  * Main method.
  *
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
   final HttpServer server = startServer();
   log.info(
       String.format("Jersey app started with WADL available at %sapplication.wadl...", BASE_URI));
   Runtime.getRuntime()
       .addShutdownHook(
           new Thread(
               () -> {
                 log.info("Shutting down HTTP listener...");
                 server.shutdownNow();
                 log.info("HTTP listener shutdown complete");
               }));
 }
Ejemplo n.º 8
0
  /**
   * Create a HTTP proxy.
   *
   * @param host hostName or IP, where the proxy will listen.
   * @param port port, where the proxy will listen.
   */
  public GrizzlyModProxy(String host, int port) {
    server = HttpServer.createSimpleServer("/", host, port);
    proxyFilter = new ProxyFilter();
    server
        .getListener("grizzly")
        .registerAddOn(
            (networkListener, builder) -> {
              int httpServerFilterIdx = builder.indexOfType(HttpServerFilter.class);

              if (httpServerFilterIdx >= 0) {
                // Insert the WebSocketFilter right before HttpServerFilter
                builder.add(httpServerFilterIdx, proxyFilter);
              }
            });
  }
Ejemplo n.º 9
0
 @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());
 }
Ejemplo n.º 10
0
  /**
   * Main method.
   *
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {

    if (args.length > 1) {
      host = args[0];
      port = args[1];
    }

    final HttpServer server = startServer();
    System.out.println(
        String.format(
            "Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...",
            BASE_URI));
    System.in.read();
    server.stop();
  }
Ejemplo n.º 11
0
  @Rank(Integer.MAX_VALUE)
  @Singleton
  @Override
  public Client provide() {
    if (!httpServer.isStarted()) {
      throw new TestException("test server not started");
    }

    Object testInstance = testContext.getTestInstance();
    Class<? extends Object> testClass = testInstance.getClass();

    Optional<ClientConfig> optional =
        of(testClass.getDeclaredMethods())
            .filter(p -> p.getDeclaredAnnotation(Config.class) != null)
            .filter(p -> p.getParameterCount() == 0)
            .filter(p -> p.getReturnType().isAssignableFrom(ClientConfig.class))
            .findFirst()
            .map(p -> reflectionUtil.invokeMethod(testInstance, p))
            .map(ClientConfig.class::cast);

    ClientConfig clientConfig = optional.orElseGet(ClientConfig::new);

    JerseyTest jerseyTest =
        testContext.getTestInstance().getClass().getAnnotation(JerseyTest.class);

    if (jerseyTest.logTraffic() && !clientConfig.isRegistered(LoggingFilter.class)) {
      clientConfig.register(new LoggingFilter(log, jerseyTest.dumpEntity()));
    }

    return ClientBuilder.newClient(clientConfig);
  }
Ejemplo n.º 12
0
  public static void main(String[] args) {
    try {
      System.out.println("System Properties Jersey Example App");

      final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, createApp());

      System.out.println(
          String.format(
              "Application started.%n" + "Try out %s%n" + "Hit enter to stop it...",
              BASE_URI + "/properties"));
      System.in.read();
      server.shutdownNow();
    } catch (IOException ex) {
      Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 13
0
  @SuppressWarnings({"ResultOfMethodCallIgnored"})
  public static void main(String[] args) {
    try {
      System.out.println("JSONP Jersey Example App");

      final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, createApp());

      System.out.println(
          String.format(
              "Application started.%nTry out %s%s%nHit enter to stop it...", BASE_URI, ROOT_PATH));
      System.in.read();
      server.stop();
    } catch (IOException ex) {
      Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 14
0
  /**
   * Main application entry point.
   *
   * @param args application arguments.
   */
  public static void main(String[] args) {
    try {
      System.out.println("Clipboard Jersey Example App");

      final ResourceConfig config = createProgrammaticClipboardApp();
      final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, config);

      System.out.println(
          String.format(
              "Application started.%n" + "Try out %s%s%n" + "Hit enter to stop it...",
              BASE_URI, ROOT_PATH));
      System.in.read();
      server.stop();
    } catch (IOException ex) {
      Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 15
0
Archivo: Server.java Proyecto: lnx/dcos
 private static void start() {
   try {
     System.setProperty("file.encoding", encoding);
     String url = "http://" + ip;
     URI uri = UriBuilder.fromUri(url).port(port).build();
     ResourceConfig rc = new PackagesResourceConfig(packages);
     rc.add(new ApplicationHandler());
     HttpServer hs = GrizzlyServerFactory.createHttpServer(uri, rc);
     Log.info("Listening " + url + ":" + port);
     Log.info("Press enter key to exit...");
     System.in.read();
     hs.stop();
     Log.info("Bye!");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 16
0
  @Test
  public void testMultiPartResource() throws Exception {
    final ResourceConfig resourceConfig =
        new ResourceConfig(MultiPartResource.class).addBinders(new MultiPartBinder());
    final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);

    Client c = ClientFactory.newClient(new ClientConfig().binders(new MultiPartClientBinder()));
    final Response response =
        c.target(baseUri).path("/multipart-simple").request().buildGet().invoke();

    MultiPart result = response.readEntity(MultiPart.class);
    System.out.println("RESULT = " + result);

    checkEntity(
        "This is the only segment", (BodyPartEntity) result.getBodyParts().get(0).getEntity());

    server.stop();
  }
  public static void main(String[] args) throws Exception {

    HttpServer server = HttpServer.createSimpleServer("/", 8080);
    WebappContext ctx = new WebappContext("api");
    ServletRegistration jerseyServlet =
        ctx.addServlet("jersey", org.glassfish.jersey.servlet.ServletContainer.class);
    jerseyServlet.addMapping("/api/*");
    jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "com.resource");
    jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
    ctx.deploy(server);
    try {
      server.start();
      System.out.println("Press any key to stop the server....");
      System.in.read();
    } finally {
      server.shutdownNow();
    }
  }
Ejemplo n.º 18
0
  @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());
  }
Ejemplo n.º 19
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();
  }
Ejemplo n.º 20
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;
  }
 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");
 }
Ejemplo n.º 22
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();
  }
Ejemplo n.º 23
0
 @Override
 @After
 public void tearDown() throws Exception {
   super.tearDown();
   if (httpServer != null) {
     httpServer.shutdownNow();
   }
   if (wiser != null) {
     wiser.stop();
   }
 }
  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();
    }
  }
Ejemplo n.º 25
0
  // TODO: the test is unreliable, the server returns null occasionally
  @Ignore
  @Test
  public void testJson() throws Exception {

    final ResourceConfig resourceConfig =
        new ResourceConfig(JsonResource.class).addModules(new JsonJacksonModule());
    final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);

    Client c = ClientFactory.newClient();

    // TODO: enable JSON on the client side once JERSEY-1083 gets resolved
    //        c.configuration().register(new JsonJacksonFeature());

    final Response response =
        c.target(baseUri).path("/json").request(MediaType.APPLICATION_JSON).buildGet().invoke();
    String result = response.readEntity(String.class);
    System.out.println("RESULT = " + result);

    assertTrue(result.contains("Jim"));

    server.stop();
  }
Ejemplo n.º 26
0
  public static void main(String[] args) {
    try {
      System.out.println("Jersey Entity Data Filtering Example.");

      final HttpServer server =
          GrizzlyHttpServerFactory.createHttpServer(
              BASE_URI, new EntityFilteringApplication(), false);
      Runtime.getRuntime()
          .addShutdownHook(
              new Thread(
                  new Runnable() {
                    @Override
                    public void run() {
                      server.shutdownNow();
                    }
                  }));
      server.start();

      System.out.println("Application started.\nTry out one of these URIs:");
      for (final String path :
          new String[] {
            "projects",
            "projects/detailed",
            "users",
            "users?detailed=true",
            "tasks",
            "tasks/detailed"
          }) {
        System.out.println(BASE_URI + path);
      }
      System.out.println("Stop the application using CTRL+C");

      Thread.currentThread().join();
    } catch (IOException | InterruptedException ex) {
      Logger.getLogger(App.class.getName())
          .log(Level.SEVERE, "I/O error occurred during reading from an system input stream.", ex);
    }
  }
Ejemplo n.º 27
0
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();

    clientUtil = new ClientUtil(target());

    wiser = new Wiser();
    wiser.setPort(2500);
    wiser.start();

    // Force shutdown
    DBIF.reset();

    String httpRoot =
        URLDecoder.decode(
            new File(getClass().getResource("/").getFile()).getAbsolutePath(), "utf-8");
    httpServer = HttpServer.createSimpleServer(httpRoot, "localhost", getPort());
    WebappContext context = new WebappContext("GrizzlyContext", "/music");
    context
        .addFilter("requestContextFilter", RequestContextFilter.class)
        .addMappingForUrlPatterns(null, "/*");
    context
        .addFilter("tokenBasedSecurityFilter", TokenBasedSecurityFilter.class)
        .addMappingForUrlPatterns(null, "/*");
    ServletRegistration reg = context.addServlet("jerseyServlet", ServletContainer.class);
    reg.setInitParameter(
        "jersey.config.server.provider.packages", "com.sismics.music.rest.resource");
    reg.setInitParameter(
        "jersey.config.server.provider.classnames",
        "org.glassfish.jersey.media.multipart.MultiPartFeature");
    reg.setInitParameter("jersey.config.server.response.setStatusOverSendError", "true");
    reg.setLoadOnStartup(1);
    reg.addMapping("/*");
    reg.setAsyncSupported(true);
    context.deploy(httpServer);
    httpServer.start();
  }
Ejemplo n.º 28
0
  public static void main(String[] args) throws IOException {
    try {
      System.out.println("JSON with MOXy Jersey Example App");

      final HttpServer server =
          GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), createAppConfig());
      Runtime.getRuntime()
          .addShutdownHook(
              new Thread(
                  new Runnable() {
                    @Override
                    public void run() {
                      server.shutdownNow();
                    }
                  }));
      server.start();

      System.out.println(String.format("Application started.%nStop the application using CTRL+C"));

      Thread.currentThread().join();
    } catch (IOException | InterruptedException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 29
0
  public static void main(String[] args) throws Exception {

    BufferedReader br = null;
    String line = null;

    SocketServer socketServer = new SocketServer();

    HttpServer server = HttpServer.createSimpleServer();
    server.getListener("grizzly").registerAddOn(new WebSocketAddOn());
    WebSocketEngine.getEngine().register("/", socketServer);
    server.start();

    List<WebSocket> sockets = socketServer.getSockets();
    br = new BufferedReader(new InputStreamReader(System.in));

    while ((line = br.readLine()) != null) {
      // desde el servidor al los browsers
      for (WebSocket webSocket : sockets) {
        webSocket.send(line);
      }
    }

    server.stop();
  }
Ejemplo n.º 30
0
  @Override
  public void startServer() throws Exception {
    server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI));

    AtmosphereServlet atmoServlet = new AtmosphereServlet();

    WebappContext context = new WebappContext("Chatty", "/chatty");

    ServletRegistration atmosphereRegistration = context.addServlet("Atmosphere", atmoServlet);
    atmosphereRegistration.addMapping("/atmos/*");

    ServletContainer jerseyContainer = new ServletContainer(resourceConfig);
    ServletRegistration jerseyRegistration = context.addServlet("Jersey", jerseyContainer);
    jerseyRegistration.addMapping("/api/*");

    context.deploy(server);

    server.start();
  }