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

The following examples show how to use org.glassfish.grizzly.http.server.HttpServer#start() . 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: EmbeddedHttpServer.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    try {
        final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new ViewApplicationConfig(), false);

        Runtime.getRuntime()
            .addShutdownHook(new Thread(() -> {
                server.shutdownNow();
            }));

        server.start();

        System.out.println(String.format("Application started.\nTry out %s\nStop the application using CTRL+C", BASE_URI + "fruit"));
    } catch (IOException ex) {
        Logger.getLogger(EmbeddedHttpServer.class.getName())
            .log(Level.SEVERE, null, ex);
    }

}
 
Example 2
Source File: JerseyServerBootstrap.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
private void setupServer(Application application) {
  ResourceConfig rc = ResourceConfig.forApplication(application);

  Properties serverProperties = readProperties();
  int port = Integer.parseInt(serverProperties.getProperty(PORT_PROPERTY));
  URI serverUri = UriBuilder.fromPath(ROOT_RESOURCE_PATH).scheme("http").host("localhost").port(port).build();

  final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(serverUri, rc);
  try {
    grizzlyServer.start();
  } catch (IOException e) {
    e.printStackTrace();
  }

  server = grizzlyServer;

}
 
Example 3
Source File: Main.java    From minie with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) {
    try {
        System.out.println("MinIE Service");

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

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

        Thread.currentThread().join();
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

}
 
Example 4
Source File: DefaultWebhook.java    From TelegramBots with MIT License 6 votes vote down vote up
public void startServer() throws TelegramApiRequestException {
    ResourceConfig rc = new ResourceConfig();
    rc.register(restApi);
    rc.register(JacksonFeature.class);

    final HttpServer grizzlyServer;
    if (keystoreServerFile != null && keystoreServerPwd != null) {
        SSLContextConfigurator sslContext = new SSLContextConfigurator();

        // set up security context
        sslContext.setKeyStoreFile(keystoreServerFile); // contains server keypair
        sslContext.setKeyStorePass(keystoreServerPwd);

        grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc, true,
                new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(false));
    } else {
        grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
    }

    try {
        grizzlyServer.start();
    } catch (IOException e) {
        throw new TelegramApiRequestException("Error starting webhook server", e);
    }
}
 
Example 5
Source File: WebServer.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 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: WeatherServer.java    From training with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    try {
        System.out.println("Starting Weather App local testing server: " + BASE_URL);
        System.out.println("Not for production use");

        final ResourceConfig resourceConfig = new ResourceConfig();
        resourceConfig.register(RestWeatherCollectorEndpoint.class);
        resourceConfig.register(RestWeatherQueryEndpoint.class);
        final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URL), resourceConfig, false);

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                server.shutdownNow();
            }
        }));

        HttpServerProbe probe = new HttpServerProbe.Adapter() {
            public void onRequestReceiveEvent(HttpServerFilter filter, Connection connection, Request request) {
                System.out.println(request.getRequestURI());
            }
        };

        server.getServerConfiguration().getMonitoringConfig().getWebServerConfig().addProbes(probe);
        System.out.println(format("Weather Server started.\n url=%s\n", BASE_URL));
        server.start();

        Thread.currentThread().join();
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(WeatherServer.class.getName()).log(Level.SEVERE, null, ex);
    }

}
 
Example 8
Source File: SimpleBankServer.java    From reladomo-kata with Apache License 2.0 5 votes vote down vote up
public void start() throws IOException
{
    initResources();
    URI baseUri = UriBuilder.fromUri("http://localhost/").port(9998).build();
    HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
    server.start();
}
 
Example 9
Source File: BitemporalBankServer.java    From reladomo-kata with Apache License 2.0 5 votes vote down vote up
public void start() throws IOException
{
    initResources();
    URI baseUri = UriBuilder.fromUri("http://localhost/").port(9998).build();
    HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
    server.start();
}
 
Example 10
Source File: CubeApplication.java    From cubedb with GNU General Public License v3.0 5 votes vote down vote up
public static void runWithConfig(ServerConfiguration config) throws Exception {
  URI baseUri = UriBuilder.fromUri("http://0.0.0.0/").port(config.port).build();
  // ResourceConfig rConfig = new
  // ResourceConfig(QueryResource.class).register;

  MultiCube cube = new MultiCubeImpl(new File(config.path).getAbsolutePath());
  cube.load(cube.getPath());
  CubeApplication rConfig = new CubeApplication(config, cube);
  registerStuff(rConfig);
  HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, rConfig);
  Log.info("Starting server");
  server.start();
  Thread.currentThread().join();
  Log.info("Shutting down");
}
 
Example 11
Source File: RestDaemon.java    From cloudml with GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 12
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 13
Source File: App.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
	final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new JerseyApplication());
	server.start();

	Thread.sleep(50);
	System.out.println("\n\nopen http://localhost:8080 in your browser\n\n");
}
 
Example 14
Source File: ServerMock.java    From javaee8-cookbook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        final ResourceConfig resourceConfig = new ResourceConfig(SseResource.class);

        final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(CONTEXT, resourceConfig, false);
        server.start();

        System.out.println(String.format("Mock Server started at %s%s", CONTEXT, BASE_PATH));

        Thread.currentThread().join();
    } catch (IOException | InterruptedException ex) {
        System.out.println(ex.getMessage());
    }
}
 
Example 15
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 16
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 17
Source File: KafkaStreamsAppBootstrap.java    From kafka-streams-example with Apache License 2.0 4 votes vote down vote up
private static void bootstrap() throws IOException {

        Random rnd = new Random();
        String portPart = String.valueOf(rnd.nextInt(10));
        String port = Optional.ofNullable(System.getenv("PORT")).orElse("808" + portPart);

        //Start Grizzly container
        URI baseUri = UriBuilder.fromUri("http://" + HOSTNAME + "/").port(Integer.parseInt(port)).build();
        ResourceConfig config = new ResourceConfig(MetricsResource.class)
                                            .register(MoxyJsonFeature.class); //to-from JSON (using JAXB)
        HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
        server.start();
        Logger.getLogger(KafkaStreamsAppBootstrap.class.getName()).log(Level.INFO, "Application accessible at {0}", baseUri.toString());

        GlobalAppState.getInstance()
                .hostPortInfo(Utils.getHostIPForDiscovery(), port);

        //Start Kafka Streams component
        KafkaStreams theStream = new CPUMetricStreamHandler().startPipeline();
        GlobalAppState.getInstance().streams(theStream);

        Logger.getLogger(KafkaStreamsAppBootstrap.class.getName()).log(Level.INFO, "Kafka Streams application discovery info {0}",
                GlobalAppState.getInstance().getHostPortInfo());

        //gracefully exit
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                LOGGER.log(Level.INFO, "Exiting......");
                try {
                    theStream.close();
                    LOGGER.log(Level.INFO, "Kafka Stream services stopped");

                    server.shutdownNow();
                    LOGGER.log(Level.INFO, "Jersey REST services stopped");
                    
                    Utils.closeRESTClient();
                    LOGGER.log(Level.INFO, "REST client closed");
                    
                } catch (Exception ex) {
                    //log & continue....
                    LOGGER.log(Level.SEVERE, ex, ex::getMessage);
                }

            }
        }));
    }
 
Example 18
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 19
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 20
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();
	}
}