Java Code Examples for org.glassfish.grizzly.http.server.HttpServer#addListener()

The following examples show how to use org.glassfish.grizzly.http.server.HttpServer#addListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Main.java    From http-server-benchmarks with MIT License 6 votes vote down vote up
public static HttpServer startServer() {
    HttpServer server = new HttpServer();
    server.addListener(new NetworkListener("grizzly", "0.0.0.0", 8080));

    final TCPNIOTransportBuilder transportBuilder = TCPNIOTransportBuilder.newInstance();
    //transportBuilder.setIOStrategy(WorkerThreadIOStrategy.getInstance());
    transportBuilder.setIOStrategy(SameThreadIOStrategy.getInstance());
    server.getListener("grizzly").setTransport(transportBuilder.build());
    final ResourceConfig rc = new ResourceConfig().packages("xyz.muetsch.jersey");
    rc.register(JacksonFeature.class);
    final ServerConfiguration config = server.getServerConfiguration();
    config.addHttpHandler(RuntimeDelegate.getInstance().createEndpoint(rc, GrizzlyHttpContainer.class), "/rest/todo/");

    try {
        server.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return server;
}
 
Example 2
Source File: HttpServerTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Before
public void before(final MockTracer tracer) throws IOException {
  // clear traces
  tracer.reset();

  httpServer = new HttpServer();
  NetworkListener listener = new NetworkListener("grizzly", DEFAULT_NETWORK_HOST, PORT);
  httpServer.addListener(listener);
  httpServer.start();
}
 
Example 3
Source File: GrizzlyHttpServerITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws IOException {
  final HttpServer server = new HttpServer();
  final NetworkListener listener = new NetworkListener("grizzly", DEFAULT_NETWORK_HOST, 18906);
  server.addListener(listener);
  server.start();

  server.getServerConfiguration().addHttpHandler(new HttpHandler() {
    @Override
    public void service(final Request request, final Response response) {
      TestUtil.checkActiveSpan();
      response.setStatus(200);
    }
  });

  int responseCode = -1;
  try {
    final URL url = new URL("http://localhost:18906/");
    final HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("GET");
    responseCode = connection.getResponseCode();
    connection.disconnect();
  }
  finally {
    server.shutdownNow();

    if (200 != responseCode)
      throw new AssertionError("ERROR: response: " + responseCode);

    TestUtil.checkSpan(true, new ComponentSpanCount("java-grizzly-http-server", 1), new ComponentSpanCount("http-url-connection", 1));
  }
}
 
Example 4
Source File: RpcServerManager.java    From nuls-v2 with MIT License 5 votes vote down vote up
public void startServer(String ip, int port) {
    URI serverURI = UriBuilder.fromUri("http://" + ip).port(port).build();
    // Create test web application context.
    WebappContext webappContext = new WebappContext("NULS-V2-SDK-PROVIDER-SERVER", "/");

    ServletRegistration servletRegistration = webappContext.addServlet("jersey-servlet", ServletContainer.class);
    servletRegistration.setInitParameter("javax.ws.rs.Application", "io.nuls.provider.api.config.NulsResourceConfig");
    servletRegistration.addMapping("/*");

    httpServer = new HttpServer();
    NetworkListener listener = new NetworkListener("grizzly2", ip, port);
    TCPNIOTransport transport = listener.getTransport();
    ThreadPoolConfig workerPool = ThreadPoolConfig.defaultConfig()
            .setCorePoolSize(4)
            .setMaxPoolSize(4)
            .setQueueLimit(1000)
            .setThreadFactory((new ThreadFactoryBuilder()).setNameFormat("grizzly-http-server-%d").build());
    transport.configureBlocking(false);
    transport.setSelectorRunnersCount(2);
    transport.setWorkerThreadPoolConfig(workerPool);
    transport.setIOStrategy(WorkerThreadIOStrategy.getInstance());
    transport.setTcpNoDelay(true);
    listener.setSecure(false);
    httpServer.addListener(listener);

    ServerConfiguration config = httpServer.getServerConfiguration();
    config.setDefaultQueryEncoding(Charsets.UTF8_CHARSET);

    webappContext.deploy(httpServer);

    try {
        ClassLoader loader = this.getClass().getClassLoader();
        httpServer.start();
        Log.info("http restFul server is started!url is " + serverURI.toString());
    } catch (IOException e) {
        Log.error(e);
        httpServer.shutdownNow();
    }
}
 
Example 5
Source File: TintServer.java    From tint with GNU General Public License v3.0 5 votes vote down vote up
public TintServer(String host, Integer port, @Nullable File configFile,
            @Nullable Properties additionalProperties) {
        LOGGER.info("starting " + host + "\t" + port + " (" + new Date() + ")...");

        int timeoutInSeconds = -1;

        try {
            // Load the pipeline
            TintPipeline pipeline = new TintPipeline();
            pipeline.loadDefaultProperties();
            pipeline.loadPropertiesFromFile(configFile);
            pipeline.addProperties(additionalProperties);

            // todo: parametrize this!
//            pipeline.loadSerializers();

            pipeline.load();

            LOGGER.info("Pipeline loaded");

            final HttpServer httpServer = new HttpServer();
            NetworkListener nl = new NetworkListener("tint-server", host, port);
            httpServer.addListener(nl);

            TintHandler tintHandler = new TintHandler(pipeline);
            tintHandler.setRequestURIEncoding(Charset.forName("UTF-8"));

            httpServer.getServerConfiguration().setSessionTimeoutSeconds(timeoutInSeconds);
            httpServer.getServerConfiguration().setMaxPostSize(4194304);
            httpServer.getServerConfiguration().addHttpHandler(tintHandler, "/tint");

            httpServer.start();
            Thread.currentThread().join();
        } catch (Exception e) {
            LOGGER.error("error running " + host + ":" + port);
            e.printStackTrace();
        }
    }
 
Example 6
Source File: VanillaExtract.java    From osm-lib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {

        OSM osm = new OSM(args[0]);

        if (args.length > 1 && args[1].startsWith("--load")) {
            osm.intersectionDetection = true;
            osm.tileIndexing = true;
            if (args[1].equalsIgnoreCase("--loadurl")) {
                osm.readFromUrl(args[2]);
            } else {
                osm.readFromFile(args[2]);
            }
            // TODO catch writing exceptions here and shut down properly, closing OSM database.
            LOG.info("Done populating OSM database.");
            osm.close();
            return;
        }

        Thread updateThread = Updater.spawnUpdateThread(osm);

        LOG.info("Starting VEX HTTP server on port {} of interface {}", PORT, BIND_ADDRESS);
        HttpServer httpServer = new HttpServer();
        httpServer.addListener(new NetworkListener("vanilla_extract", BIND_ADDRESS, PORT));
        // Bypass Jersey etc. and add a low-level Grizzly handler.
        // As in servlets, * is needed in base path to identify the "rest" of the path.
        httpServer.getServerConfiguration().addHttpHandler(new VexHttpHandler(osm), "/*");
        try {
            httpServer.start();
            LOG.info("VEX server running.");
            Thread.currentThread().join();
            updateThread.interrupt();
        } catch (BindException be) {
            LOG.error("Cannot bind to port {}. Is it already in use?", PORT);
        } catch (IOException ioe) {
            LOG.error("IO exception while starting server.");
        } catch (InterruptedException ie) {
            LOG.info("Interrupted, shutting down.");
        }
        httpServer.shutdown();
    }
 
Example 7
Source File: ControllerAdminApiApplication.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private void configureListener(ListenerConfig listenerConfig, HttpServer httpServer) {
  final NetworkListener listener = new NetworkListener(listenerConfig.getName() + "-" + listenerConfig.getPort(),
      listenerConfig.getHost(), listenerConfig.getPort());

  listener.getTransport().getWorkerThreadPoolConfig()
      .setThreadFactory(new ThreadFactoryBuilder().setNameFormat("grizzly-http-server-%d")
          .setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());

  listener.setSecure(listenerConfig.getTlsConfiguration() != null);
  if (listener.isSecure()) {
    listener.setSSLEngineConfig(buildSSLEngineConfigurator(listenerConfig.getTlsConfiguration()));
  }
  httpServer.addListener(listener);
}
 
Example 8
Source File: GatfConfigToolMojo.java    From gatf with Apache License 2.0 4 votes vote down vote up
public void execute() throws MojoExecutionException, MojoFailureException {
	HttpServer server = new HttpServer();

	final String mainDir = rootDir + SystemUtils.FILE_SEPARATOR + "gatf-config-tool";
	InputStream resourcesIS = GatfConfigToolMojo.class.getResourceAsStream("/gatf-config-tool.zip");
       if (resourcesIS != null)
       {
       	ReportHandler.unzipZipFile(resourcesIS, rootDir);
       }
       
       final GatfConfigToolMojo mojo = this;
       
       GatfConfigToolUtil.createConfigFileIfNotExists(mojo, true, null);
       
       GatfConfigToolUtil.createConfigFileIfNotExists(mojo, false, null);
       
       GatfConfigToolUtil.createServerApiAndIssueTrackingApiFilesIfNotExists(mojo);
       
       server.addListener(new NetworkListener("ConfigServer", ipAddress, port));
       
       GatfConfigToolUtil.handleRootContext(server, mainDir, mojo);
       
       Function<String, GatfPlugin> f = new Function<String, GatfPlugin>() {
		@Override
		public GatfPlugin apply(String type) {
			GatfPlugin gp = null;
			if(type.equals("executor"))
			{
				gp = new GatfTestCaseExecutorMojo();
			}
			else
			{
				gp = new GatfTestGeneratorMojo();
			}
			gp.setProject(project);
			return gp;
		}
	};
       
       server.getServerConfiguration().addHttpHandler(new GatfConfigurationHandler(mojo, f), "/configure");
       
       server.getServerConfiguration().addHttpHandler(new GatfReportsHandler(mojo, f), "/reports");
       
       server.getServerConfiguration().addHttpHandler(new GatfMiscHandler(mojo), "/misc");
       
       server.getServerConfiguration().addHttpHandler(new GatfTestCaseFilesHandler(mojo), "/testcasefiles");
       
       server.getServerConfiguration().addHttpHandler(new GatfTestCaseHandler(mojo), "/testcases");
	
       server.getServerConfiguration().addHttpHandler(new GatfPluginExecutionHandler(mojo, f), "/execute");
       
       server.getServerConfiguration().addHttpHandler(new GatfProfileHandler(mojo, f), "/profile");
	
	try {
	    server.start();
	    System.out.println("Press any key to stop the server...");
	    System.in.read();
	} catch (Exception e) {
	    System.err.println(e);
	}
}
 
Example 9
Source File: GatfConfigToolUtil.java    From gatf with Apache License 2.0 4 votes vote down vote up
public void execute() throws Exception {
	HttpServer server = new HttpServer();

	final String mainDir = rootDir + SystemUtils.FILE_SEPARATOR + "gatf-config-tool";
	InputStream resourcesIS = GatfConfigToolUtil.class.getResourceAsStream("/gatf-config-tool.zip");
       if (resourcesIS != null)
       {
       	ReportHandler.unzipZipFile(resourcesIS, rootDir);
       }
       
       final GatfConfigToolUtil mojo = this;
       
       createConfigFileIfNotExists(mojo, true, null);
       
       createConfigFileIfNotExists(mojo, false, null);
       
       createServerApiAndIssueTrackingApiFilesIfNotExists(mojo);
       
       server.addListener(new NetworkListener("ConfigServer", ipAddress, port));
       
       handleRootContext(server, mainDir, mojo);
       
       Function<String, GatfPlugin> f = new Function<String, GatfPlugin>() {
		@Override
		public GatfPlugin apply(String type) {
			GatfPlugin gp = null;
			if(type.equals("executor"))
			{
				gp = new GatfTestCaseExecutorUtil();
			}
			else
			{
				gp = new GatfTestGeneratorUtil();
			}
			return gp;
		}
	};
       
       server.getServerConfiguration().addHttpHandler(new GatfConfigurationHandler(mojo, f), "/configure");
       
       server.getServerConfiguration().addHttpHandler(new GatfReportsHandler(mojo, f), "/reports");
       
       server.getServerConfiguration().addHttpHandler(new GatfMiscHandler(mojo), "/misc");
       
       server.getServerConfiguration().addHttpHandler(new GatfTestCaseFilesHandler(mojo), "/testcasefiles");
       
       server.getServerConfiguration().addHttpHandler(new GatfTestCaseHandler(mojo), "/testcases");
	
       server.getServerConfiguration().addHttpHandler(new GatfPluginExecutionHandler(mojo, f), "/execute");
       
       server.getServerConfiguration().addHttpHandler(new GatfProfileHandler(mojo, f), "/profile");
	
	try {
	    server.start();
	    System.out.println("Press any key to stop the server...");
	    System.in.read();
	} catch (Exception e) {
	    System.err.println(e);
	}
}
 
Example 10
Source File: Server.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	final int port = args.length > 0 ? Integer.parseInt(args[0]) : 8080;

	final HttpServer httpServer = new HttpServer();

	final NetworkListener networkListener = new NetworkListener("http-listener", "0.0.0.0",
			port);
	final TCPNIOTransport transport = networkListener.getTransport();

	// force to not initialize worker thread pool
	transport.setWorkerThreadPoolConfig(null);
	transport.setSelectorRunnersCount(Runtime.getRuntime().availableProcessors() * 2);

	// set PooledMemoryManager
	transport.setMemoryManager(new PooledMemoryManager());

	// always keep-alive
	networkListener.getKeepAlive().setIdleTimeoutInSeconds(-1);
	networkListener.getKeepAlive().setMaxRequestsCount(-1);

	// disable transaction timeout
	networkListener.setTransactionTimeout(-1);

	// remove the features we don't need
	networkListener.registerAddOn(new SimplifyAddOn());
	// add HTTP pipeline optimization
	networkListener.registerAddOn(new HttpPipelineOptAddOn());

	// disable file-cache
	networkListener.getFileCache().setEnabled(false);

	httpServer.addListener(networkListener);

	httpServer.getServerConfiguration().addHttpHandler(new RootHttpHandler(), "/");

	try {
		httpServer.start();
		// This can't be done before the call to start(). Also note the
		// positions
		httpServer.getListener("http-listener").getFilterChain().add(3, new HeadersFilter());
		synchronized (Server.class) {
			Server.class.wait();
		}
	} finally {
		httpServer.shutdown();
	}
}
 
Example 11
Source File: GrizzlyApplication.java    From micro-server with Apache License 2.0 3 votes vote down vote up
private void addSSL(HttpServer httpServer) {

	        try {

                    SSLProperties sslProperties = serverData.getRootContext().getBean(SSLProperties.class);
                    if (sslProperties != null) {
                        httpServer.addListener(this.createSSLListener(serverData.getPort(), sslProperties));
                    }

            }catch(BeanNotOfRequiredTypeException e){

            }

	}