org.glassfish.grizzly.http.server.NetworkListener Java Examples
The following examples show how to use
org.glassfish.grizzly.http.server.NetworkListener.
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 |
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: VanillaExtract.java From osm-lib with BSD 2-Clause "Simplified" License | 5 votes |
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 #3
Source File: WebServer.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void setup(final NetworkListener networkListener, final FilterChainBuilder builder) { final int fcIdx = builder.indexOfType(FileCacheFilter.class); if (fcIdx != -1) { builder.remove(fcIdx); } final int itIdx = builder.indexOfType(IdleTimeoutFilter.class); if (itIdx != -1) { builder.remove(itIdx); } }
Example #4
Source File: WebServer.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static void main(String[] args) { try { final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, createApp(), false); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { server.shutdownNow(); } })); // Some modifications NetworkListener defaultListener = server.getListener("grizzly"); defaultListener.getKeepAlive().setIdleTimeoutInSeconds(-1); defaultListener.getKeepAlive().setMaxRequestsCount(-1); defaultListener.getFileCache().setEnabled(false); defaultListener.registerAddOn(new SimplifyAddOn()); defaultListener.registerAddOn(new HttpPipelineOptAddOn()); final TCPNIOTransport transport = defaultListener.getTransport(); transport.setWorkerThreadPoolConfig(null); // force to not // initialize worker // thread pool transport.setSelectorRunnersCount(Runtime.getRuntime().availableProcessors() * 2); transport.setMemoryManager(new PooledMemoryManager()); server.start(); System.out.println(String .format("TFBApplication started.%nStop the application using CTRL+C")); Thread.currentThread().join(); } catch (IOException | InterruptedException ex) { Logger.getLogger(WebServer.class.getName()).log(Level.SEVERE, null, ex); } }
Example #5
Source File: Server.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void setup(final NetworkListener networkListener, final FilterChainBuilder builder) { final int fcIdx = builder.indexOfType(FileCacheFilter.class); if (fcIdx != -1) { builder.remove(fcIdx); } final int itIdx = builder.indexOfType(IdleTimeoutFilter.class); if (itIdx != -1) { builder.remove(itIdx); } }
Example #6
Source File: ControllerAdminApiApplication.java From incubator-pinot with Apache License 2.0 | 5 votes |
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 #7
Source File: RestServer.java From Cheddar with Apache License 2.0 | 5 votes |
private void configureWorkerThreadPool(final NetworkListener networkListener, final int workerThreads) { final TCPNIOTransport transport = networkListener.getTransport(); if (transport.getWorkerThreadPoolConfig() == null) { transport.setWorkerThreadPoolConfig(ThreadPoolConfig.defaultConfig()); } transport.getWorkerThreadPoolConfig().setMaxPoolSize(workerThreads).setCorePoolSize(workerThreads); }
Example #8
Source File: AbstractAPI.java From clouditor with Apache License 2.0 | 5 votes |
/** Starts the API. */ public void start() { LOGGER.info("Starting {}...", this.getClass().getSimpleName()); this.httpServer = GrizzlyHttpServerFactory.createHttpServer( UriBuilder.fromUri( "http://" + NetworkListener.DEFAULT_NETWORK_HOST + "/" + this.contextPath) .port(this.port) .build(), this); LOGGER.info("{} successfully started.", this.getClass().getSimpleName()); // update the associated with the real port used, if port 0 was specified. if (this.port == 0) { component.setAPIPort(this.httpServer.getListener("grizzly").getPort()); } var config = new ResourceConfig(); config.register(OAuthResource.class); config.register(InjectionBridge.class); var context = new WebappContext("WebappContext", "/oauth2"); var registration = context.addServlet("OAuth2 Client", new ServletContainer(config)); registration.addMapping("/*"); context.deploy(httpServer); this.httpServer.getServerConfiguration().addHttpHandler(new StaticHttpHandler("html"), "/"); }
Example #9
Source File: GrizzlyApplication.java From micro-server with Apache License 2.0 | 5 votes |
private NetworkListener createSSLListener(int port, SSLProperties sslProperties) { SSLConfigurationBuilder sslBuilder = new SSLConfigurationBuilder(); NetworkListener listener = new NetworkListener("grizzly", "0.0.0.0", Integer.valueOf(port)); listener.getFileCache().setEnabled(false); listener.setSecure(true); listener.setSSLEngineConfig(sslBuilder.build(sslProperties)); return listener; }
Example #10
Source File: TintServer.java From tint with GNU General Public License v3.0 | 5 votes |
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 #11
Source File: RpcServerManager.java From nuls-v2 with MIT License | 5 votes |
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 #12
Source File: GrizzlyHttpServerITest.java From java-specialagent with Apache License 2.0 | 5 votes |
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 #13
Source File: HttpServerTest.java From java-specialagent with Apache License 2.0 | 5 votes |
@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 #14
Source File: GatfConfigToolMojo.java From gatf with Apache License 2.0 | 4 votes |
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 #15
Source File: GatfConfigToolUtil.java From gatf with Apache License 2.0 | 4 votes |
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 #16
Source File: RestServer.java From hugegraph with Apache License 2.0 | 4 votes |
private HttpServer configHttpServer(URI uri, ResourceConfig rc) { final HttpServer server; String protocol = this.conf.get(ServerOptions.SERVER_PROTOCOL); String keystoreServerFile = this.conf.get(ServerOptions.SERVER_KEYSTORE_FILE); String keystoreServerPassword = this.conf.get(ServerOptions.SERVER_KEYSTORE_PASSWORD); if (protocol != null && protocol.equals("https")) { SSLContextConfigurator sslContext = new SSLContextConfigurator(); // set up security context sslContext.setKeyStoreFile(keystoreServerFile); sslContext.setKeyStorePass(keystoreServerPassword); SSLEngineConfigurator sslEngineConfigurator = new SSLEngineConfigurator(sslContext) .setClientMode(false) .setWantClientAuth(true); server = GrizzlyHttpServerFactory.createHttpServer(uri, rc, true, sslEngineConfigurator); } else { server = GrizzlyHttpServerFactory.createHttpServer(uri, rc, false); } Collection<NetworkListener> listeners = server.getListeners(); E.checkState(listeners.size() > 0, "Http Server should have some listeners, but now is none"); NetworkListener listener = listeners.iterator().next(); // Option max_worker_threads int maxWorkerThreads = this.conf.get(ServerOptions.MAX_WORKER_THREADS); listener.getTransport() .getWorkerThreadPoolConfig() .setCorePoolSize(maxWorkerThreads) .setMaxPoolSize(maxWorkerThreads); // Option keep_alive int idleTimeout = this.conf.get(ServerOptions.CONN_IDLE_TIMEOUT); int maxRequests = this.conf.get(ServerOptions.CONN_MAX_REQUESTS); listener.getKeepAlive().setIdleTimeoutInSeconds(idleTimeout); listener.getKeepAlive().setMaxRequestsCount(maxRequests); // Option transaction timeout int transactionTimeout = this.conf.get(ServerOptions.REQUEST_TIMEOUT); listener.setTransactionTimeout(transactionTimeout); return server; }
Example #17
Source File: Server.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 4 votes |
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 #18
Source File: GrizzlyHttpService.java From linstor-server with GNU General Public License v3.0 | 4 votes |
private void initGrizzly(final String bindAddress, final String httpsBindAddress) { if (keyStoreFile != null) { final URI httpsUri = URI.create(String.format("https://%s", httpsBindAddress)); // only install a redirect handler for http httpServer = GrizzlyHttpServerFactory.createHttpServer( URI.create(String.format("http://%s", bindAddress)), false ); addHTTPSRedirectHandler(httpServer, httpsUri.getPort()); httpsServer = GrizzlyHttpServerFactory.createHttpServer( httpsUri, restResourceConfig, false ); SSLContextConfigurator sslCon = new SSLContextConfigurator(); sslCon.setSecurityProtocol("TLS"); sslCon.setKeyStoreFile(keyStoreFile.toString()); sslCon.setKeyStorePass(keyStorePassword); boolean hasClientAuth = trustStoreFile != null; if (hasClientAuth) { sslCon.setTrustStoreFile(trustStoreFile.toString()); sslCon.setTrustStorePass(trustStorePassword); } for (NetworkListener netListener : httpsServer.getListeners()) { netListener.setSecure(true); SSLEngineConfigurator ssle = new SSLEngineConfigurator(sslCon); ssle.setWantClientAuth(hasClientAuth); ssle.setClientMode(false); ssle.setNeedClientAuth(hasClientAuth); netListener.setSSLEngineConfig(ssle); } enableCompression(httpsServer); } else { httpsServer = null; httpServer = GrizzlyHttpServerFactory.createHttpServer( URI.create(String.format("http://%s", bindAddress)), restResourceConfig, false ); } // configure access logging if (restAccessLogMode == null) { errorReporter.logWarning("Unknown rest_access_log_mode set, fallback to append"); restAccessLogMode = LinstorConfig.RestAccessLogMode.APPEND; } if (restAccessLogMode != LinstorConfig.RestAccessLogMode.NO_LOG) { final Path accessLogPath = restAccessLogPath.isAbsolute() ? restAccessLogPath : errorReporter.getLogDirectory().resolve(restAccessLogPath); final AccessLogBuilder builder = new AccessLogBuilder(accessLogPath.toFile()); switch (restAccessLogMode) { case ROTATE_HOURLY: errorReporter.logDebug("Rest-access log set to rotate hourly."); builder.rotatedHourly(); break; case ROTATE_DAILY: errorReporter.logDebug("Rest-access log set to rotate daily."); builder.rotatedDaily(); break; case APPEND: case NO_LOG: default: } if (httpServer != null) { builder.instrument(httpServer.getServerConfiguration()); } if (httpsServer != null) { builder.instrument(httpsServer.getServerConfiguration()); } } else { errorReporter.logDebug("Rest-access log turned off."); } if (httpServer != null) { enableCompression(httpServer); } }