Java Code Examples for org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory#createHttpServer()

The following examples show how to use org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory#createHttpServer() . 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: RESTServer.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Start REST service.
 */
@Override
protected void startUp() {
    long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "startUp");
    try {
        log.info("Starting REST server listening on port: {}", this.restServerConfig.getPort());
        if (restServerConfig.isTlsEnabled()) {
            SSLContextConfigurator contextConfigurator = new SSLContextConfigurator();
            contextConfigurator.setKeyStoreFile(restServerConfig.getKeyFilePath());
            contextConfigurator.setKeyStorePass(JKSHelper.loadPasswordFrom(restServerConfig.getKeyFilePasswordPath()));
            httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true,
                    new SSLEngineConfigurator(contextConfigurator, false, false, false));
        } else {
            httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true);
        }
    } finally {
        LoggerHelpers.traceLeave(log, this.objectId, "startUp", traceId);
    }
}
 
Example 2
Source File: RestManager.java    From cep with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Starts the HTTP server exposing the resources defined in the RestRules class.
 * It takes a reference to an object that implements the RestListener interface,
 * which will be notified every time the REST API receives a request of some type.
 *
 * @param wsUri The base URL of the HTTP REST API
 * @param rl The RestListener object that will be notified when a user sends
 *           an HTTP request to the API
 * @see RestRules
 * @see RestListener
 */

public static void startServer(String wsUri, RestListener rl) {
    // Create a resource config that scans for JAX-RS resources and providers
    ResourceConfig rc = new ResourceConfig()
            .register(RestRules.class)
            .register(JacksonFeature.class);

    // Set the listener for the petitions
    listener = rl;

    // Create a new instance of grizzly http server
    // exposing the Jersey application at BASE_URI
    server = GrizzlyHttpServerFactory.createHttpServer(URI.create(wsUri), rc);

    // start the server
    try {
        server.start();
    } catch (IOException e) {
        log.error(e.getMessage());
    }

    log.info("HTTP server started");
}
 
Example 3
Source File: CubeResourceGeneralTest.java    From cubedb with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  //create ResourceConfig from Resource class
  ResourceConfig rc = new ResourceConfig();
  cube = new MultiCubeImpl(null);
  rc.registerInstances(new CubeResource(cube));
  rc.register(JsonIteratorConverter.class);

  //create the Grizzly server instance
  httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);
  //start the server
  httpServer.start();

  //configure client with the base URI path
  Client client = ClientBuilder.newClient();
  client.register(JsonIteratorConverter.class);
  webTarget = client.target(baseUri);
}
 
Example 4
Source File: ToolboxService.java    From chipster with MIT License 6 votes vote down vote up
/**
 * 
 * @param enableStatsAndAdminServer
 * @throws IOException
 * @throws URISyntaxException
 */
public void startServerOldChipster() throws IOException, URISyntaxException {
	this.toolResource = new ToolResource(this.toolbox);
	this.moduleResource = new ModuleResource(toolbox);

	final ResourceConfig rc = RestUtils.getResourceConfig().register(this.toolResource).register(moduleResource);
	// .register(new LoggingFilter())

	// create and start a new instance of grizzly http server
	// exposing the Jersey application at BASE_URI
	URI baseUri = URI.create(this.url);
	this.httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);

	this.httpServer.start();
	logger.info("toolbox service running at " + baseUri);
}
 
Example 5
Source File: ControllerAdminApiApplication.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public void start(List<ListenerConfig> listenerConfigs, boolean advertiseHttps) {
  // ideally greater than reserved port but then port 80 is also valid
  Preconditions.checkNotNull(listenerConfigs);
  
  // The URI is irrelevant since the default listener will be manually rewritten.
  _httpServer = GrizzlyHttpServerFactory.createHttpServer(URI.create("http://0.0.0.0/"), this, false);
  
  // Listeners cannot be configured with the factory. Manual overrides is required as instructed by Javadoc.
  _httpServer.removeListener("grizzly");

  listenerConfigs.forEach(listenerConfig->configureListener(listenerConfig, _httpServer));
  
  try {
    _httpServer.start();
  } catch (IOException e) {
    throw new RuntimeException("Failed to start Http Server", e);
  }
  
  setupSwagger(_httpServer, advertiseHttps);

  ClassLoader classLoader = ControllerAdminApiApplication.class.getClassLoader();

  // This is ugly from typical patterns to setup static resources but all our APIs are
  // at path "/". So, configuring static handler for path "/" does not work well.
  // Configuring this as a default servlet is an option but that is still ugly if we evolve
  // So, we setup specific handlers for static resource directory. index.html is served directly
  // by a jersey handler

  _httpServer.getServerConfiguration()
      .addHttpHandler(new CLStaticHttpHandler(classLoader, "/static/query/"), "/query/");
  _httpServer.getServerConfiguration().addHttpHandler(new CLStaticHttpHandler(classLoader, "/static/css/"), "/css/");
  _httpServer.getServerConfiguration().addHttpHandler(new CLStaticHttpHandler(classLoader, "/static/js/"), "/js/");
  // without this explicit request to /index.html will not work
  _httpServer.getServerConfiguration().addHttpHandler(new CLStaticHttpHandler(classLoader, "/static/"), "/index.html");

  LOGGER.info("Admin API started on ports: {}", listenerConfigs.stream().map(ListenerConfig::getPort)
      .map(port -> port.toString()).collect(Collectors.joining(",")));
}
 
Example 6
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 7
Source File: Server.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public static void startServer(final int port) throws Exception {
    final URI baseUri = URI.create("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + port + "/selenium");
    final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, new ServerConfiguration());

    System.in.read();
    server.shutdown();
}
 
Example 8
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 9
Source File: AdminApiApplication.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public boolean start(int httpPort) {
  if (httpPort <= 0) {
    LOGGER.warn("Invalid admin API port: {}. Not starting admin service", httpPort);
    return false;
  }

  baseUri = URI.create("http://0.0.0.0:" + Integer.toString(httpPort) + "/");
  httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, this);
  setupSwagger(httpServer);
  started = true;
  return true;
}
 
Example 10
Source File: AbstractAPI.java    From clouditor with Apache License 2.0 5 votes vote down vote up
/** 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 11
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 12
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 13
Source File: JaxrsTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws IOException {
  httpServer = GrizzlyHttpServerFactory.createHttpServer(
      SERVER_URI,
      createResourceConfig(),
      false);

  httpServer.start();

  client = ClientBuilder.newBuilder()
      .register(GsonMessageBodyProvider.class)
      .register(PURE_GSON_TEXT_PLAIN)
      .build();
}
 
Example 14
Source File: EmbeddedHttpServer.java    From tutorials with MIT License 4 votes vote down vote up
public static HttpServer startServer() {
    final ResourceConfig rc = new ResourceConfig().packages("com.baeldung.jersey.server");
    return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI.toString()), rc);
}
 
Example 15
Source File: BooksEndpointTest.java    From Test-Driven-Java-Development-Second-Edition with MIT License 4 votes vote down vote up
@Before
public void setUp() throws IOException {
    ResourceConfig resourceConfig = new MyApplication();
    server = GrizzlyHttpServerFactory.createHttpServer(FULL_PATH, resourceConfig);
    server.start();
}
 
Example 16
Source File: RestServer.java    From ThriftBook with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), 
                new ResourceConfig().registerClasses(RestServer.class));
}
 
Example 17
Source File: Main.java    From Jax-RS-Performance-Comparison with Apache License 2.0 4 votes vote down vote up
public static HttpServer startServer(String host, int port) {
    final ResourceConfig rc = ResourceConfig.forApplicationClass(MyApplication.class);
    URI baseUri = UriBuilder.fromUri(BASE_URI).host(host).port(port).build();
    return GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);
}
 
Example 18
Source File: Main.java    From RestExpress-Examples with Apache License 2.0 4 votes vote down vote up
public static HttpServer startServer()
{
	final ResourceConfig rc = new ResourceConfig().packages("com.example");
	return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
 
Example 19
Source File: ExoPlatformLocator.java    From exo-demo with MIT License 4 votes vote down vote up
/**
 * Initializes Grizzly-based REST interfaces as defined in the messaging config.  This method will
 * allow for REST endpoints using HTTPS by defining keystore information in exo-config.json.
 * Enabling REST will automatically expose the endpoints service and generate an ANNOUNCE_NODE message.
 * @param restConfig
 */
public static void initREST(MessagingConfig restConfig) {
	URI baseUri = UriBuilder.fromUri("http://0.0.0.0").port(restConfig.port).build();
	ResourceConfig config = new ResourceConfig()
			.packages("com.txmq.exo.messaging.rest")
			.register(new CORSFilter())
			.register(JacksonFeature.class)
			.register(MultiPartFeature.class);
	
	for (String pkg : restConfig.handlers) {
		config.packages(pkg);
	}
	
	System.out.println("Attempting to start Grizzly on " + baseUri);
	HttpServer grizzly = null;
	if (restConfig.secured == true) {
		SSLContextConfigurator sslContext = new SSLContextConfigurator();
		sslContext.setKeyStoreFile(restConfig.serverKeystore.path);
		sslContext.setKeyStorePass(restConfig.serverKeystore.password);
		sslContext.setTrustStoreFile(restConfig.serverTruststore.path);
		sslContext.setTrustStorePass(restConfig.serverTruststore.password);
		
		grizzly = GrizzlyHttpServerFactory.createHttpServer(
			baseUri, 
			config, 
			true, 
			new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(false)
		);
	} else {
		grizzly = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
	}
	
	//Track Grizzly instances so they can be shut down later
	if (grizzly != null) {
		httpServers.add(grizzly);
	}
	
	//Publish available Exo API endpoints to the HG.
	try {
		String externalUrl = baseUri.toString();
		if (platform != null) {
			externalUrl = "http://";
			byte[] rawAddress = platform.getAddress().getAddressExternalIpv4();
			for (int ptr = 0;  ptr < rawAddress.length;  ptr++) {
				int i = rawAddress[ptr] & 0xFF;
				externalUrl += Integer.toString(i);
				if (ptr < rawAddress.length - 1) {
					externalUrl += ".";
				}
			}
			externalUrl += ":" + restConfig.port;
			
			System.out.println("Reporting available REST API at " + externalUrl);
		} else {
			
		}
		createTransaction(
			new ExoMessage(
				new ExoTransactionType(ExoTransactionType.ANNOUNCE_NODE),
				externalUrl
			)
		);
				
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
}
 
Example 20
Source File: Engine.java    From acs-demos with MIT License 2 votes vote down vote up
/**
 * Start the API server.
 * 
 * @param players
 * @return
 */
public static HttpServer startServer(int players) {
	TournamentAPI api = new TournamentAPI(new Tournament(players));
	final ResourceConfig rc = new ResourceConfig().register(api);
	return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}