org.glassfish.jersey.servlet.ServletContainer Java Examples

The following examples show how to use org.glassfish.jersey.servlet.ServletContainer. 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: JettyServerProvider.java    From browserup-proxy with Apache License 2.0 8 votes vote down vote up
@Inject
public JettyServerProvider(@Named("port") int port, @Named("address") String address, MitmProxyManager proxyManager) throws UnknownHostException {
    OpenApiResource openApiResource = new OpenApiResource();
    openApiResource.setConfigLocation(SWAGGER_CONFIG_NAME);

    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.packages(SWAGGER_PACKAGE);
    resourceConfig.register(openApiResource);
    resourceConfig.register(proxyManagerToHkBinder(proxyManager));
    resourceConfig.register(JacksonFeature.class);
    resourceConfig.register(ConstraintViolationExceptionMapper.class);
    resourceConfig.registerClasses(LoggingFilter.class);

    resourceConfig.property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    resourceConfig.property(ServerProperties.WADL_FEATURE_DISABLE, true);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    context.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));;
    context.addServlet(DefaultServlet.class, "/");
    context.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    server = new Server(new InetSocketAddress(InetAddress.getByName(address), port));
    server.setHandler(context);
}
 
Example #2
Source File: JerseyServerBenchmarks.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override protected void init(DeploymentInfo servletBuilder) {
  servletBuilder.addServlets(
    servlet("Unsampled", ServletContainer.class)
      .setLoadOnStartup(1)
      .addInitParam("javax.ws.rs.Application", Unsampled.class.getName())
      .addMapping("/unsampled"),
    servlet("Traced", ServletContainer.class)
      .setLoadOnStartup(1)
      .addInitParam("javax.ws.rs.Application", TracedApp.class.getName())
      .addMapping("/traced"),
    servlet("TracedBaggage", ServletContainer.class)
      .setLoadOnStartup(1)
      .addInitParam("javax.ws.rs.Application", TracedBaggageApp.class.getName())
      .addMapping("/tracedBaggage"),
    servlet("Traced128", ServletContainer.class)
      .setLoadOnStartup(1)
      .addInitParam("javax.ws.rs.Application", Traced128App.class.getName())
      .addMapping("/traced128"),
    servlet("App", ServletContainer.class)
      .setLoadOnStartup(1)
      .addInitParam("javax.ws.rs.Application", App.class.getName())
      .addMapping("/*")
  );
}
 
Example #3
Source File: WorkerServer.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public static ServletContextHandler newServletContextHandler(String contextPath, ResourceConfig config, WorkerService workerService, boolean requireAuthentication) {
    final ServletContextHandler contextHandler =
            new ServletContextHandler(ServletContextHandler.NO_SESSIONS);

    contextHandler.setAttribute(FunctionApiResource.ATTRIBUTE_FUNCTION_WORKER, workerService);
    contextHandler.setAttribute(WorkerApiV2Resource.ATTRIBUTE_WORKER_SERVICE, workerService);
    contextHandler.setAttribute(WorkerStatsApiV2Resource.ATTRIBUTE_WORKERSTATS_SERVICE, workerService);
    contextHandler.setContextPath(contextPath);

    final ServletHolder apiServlet =
            new ServletHolder(new ServletContainer(config));
    contextHandler.addServlet(apiServlet, "/*");
    if (workerService.getWorkerConfig().isAuthenticationEnabled() && requireAuthentication) {
        FilterHolder filter = new FilterHolder(new AuthenticationFilter(workerService.getAuthenticationService()));
        contextHandler.addFilter(filter, MATCH_ALL, EnumSet.allOf(DispatcherType.class));
    }

    return contextHandler;
}
 
Example #4
Source File: HeartbeatTest.java    From TeaStore with Apache License 2.0 6 votes vote down vote up
/**
 * Setup the test by deploying an embedded tomcat and adding the rest endpoints.
 * @throws Throwable Throws uncaught throwables for test to fail.
 */
@Before
public void setup() throws Throwable {
	registryTomcat = new Tomcat();
	registryTomcat.setPort(3000);
	registryTomcat.setBaseDir(testWorkingDir);
	Context context = registryTomcat.addWebapp(CONTEXT, testWorkingDir);
	context.addApplicationListener(RegistryStartup.class.getName());
	ResourceConfig restServletConfig = new ResourceConfig();
	restServletConfig.register(RegistryREST.class);
	restServletConfig.register(Registry.class);
	ServletContainer restServlet = new ServletContainer(restServletConfig);
	registryTomcat.addServlet(CONTEXT, "restServlet", restServlet);
	context.addServletMappingDecoded("/rest/*", "restServlet");
	registryTomcat.start();
}
 
Example #5
Source File: WebServerModule.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideJersey() {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      // REST API that requires authentication
      ServletHolder protectedRest = new ServletHolder(new ServletContainer());
      protectedRest.setInitParameter(
          ServerProperties.PROVIDER_PACKAGES, SWAGGER_PACKAGE + "," +
          RestAPI.class.getPackage().getName()
      );
      protectedRest.setInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, RestAPIResourceConfig.class.getName());
      context.addServlet(protectedRest, "/rest/*");

      RJson.configureRJsonForSwagger(Json.mapper());

      // REST API that it does not require authentication
      ServletHolder publicRest = new ServletHolder(new ServletContainer());
      publicRest.setInitParameter(ServerProperties.PROVIDER_PACKAGES, PublicRestAPI.class.getPackage().getName());
      publicRest.setInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, RestAPIResourceConfig.class.getName());
      context.addServlet(publicRest, "/public-rest/*");
    }
  };
}
 
Example #6
Source File: OrderService.java    From qcon-microservices with Apache License 2.0 6 votes vote down vote up
Server startJetty(int port, Object binding) {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    Server jettyServer = new Server(port);
    jettyServer.setHandler(context);

    ResourceConfig rc = new ResourceConfig();
    rc.register(binding);
    rc.register(JacksonFeature.class);

    ServletContainer sc = new ServletContainer(rc);
    ServletHolder holder = new ServletHolder(sc);
    context.addServlet(holder, "/*");

    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    log.info("Listening on " + jettyServer.getURI());
    return jettyServer;
}
 
Example #7
Source File: SamzaRestService.java    From samza with Apache License 2.0 5 votes vote down vote up
/**
 * Command line interface to run the server.
 *
 * @param args arguments supported by {@link org.apache.samza.util.CommandLine}.
 *             In particular, --config job.config.loader.properties.path and
 *             --config job.config.loader.factory are used to read the Samza REST config file.
 * @throws Exception if the server could not be successfully started.
 */
public static void main(String[] args)
    throws Exception {
  ScheduledExecutorSchedulingProvider schedulingProvider = null;
  try {
    SamzaRestConfig config = parseConfig(args);
    ReadableMetricsRegistry metricsRegistry = new MetricsRegistryMap();
    log.info("Creating new SamzaRestService with config: {}", config);
    MetricsConfig metricsConfig = new MetricsConfig(config);
    Map<String, MetricsReporter> metricsReporters =
        MetricsReporterLoader.getMetricsReporters(metricsConfig, Util.getLocalHost().getHostName());
    SamzaRestService restService = new SamzaRestService(new Server(config.getPort()), metricsRegistry, metricsReporters,
        new ServletContextHandler(ServletContextHandler.SESSIONS));

    // Add applications
    SamzaRestApplication samzaRestApplication = new SamzaRestApplication(config);
    ServletContainer container = new ServletContainer(samzaRestApplication);
    restService.addServlet(container, "/*");

    // Schedule monitors to run
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true)
                                                            .setNameFormat("MonitorThread-%d")
                                                            .build();
    ScheduledExecutorService schedulingService = Executors.newScheduledThreadPool(1, threadFactory);
    schedulingProvider = new ScheduledExecutorSchedulingProvider(schedulingService);
    SamzaMonitorService monitorService = new SamzaMonitorService(config,
        metricsRegistry,
        schedulingProvider);
    monitorService.start();

    restService.runBlocking();
    monitorService.stop();
  } catch (Throwable t) {
    log.error("Exception in main.", t);
  } finally {
    if (schedulingProvider != null) {
      schedulingProvider.stop();
    }
  }
}
 
Example #8
Source File: RaftJettyServer.java    From barge with Apache License 2.0 5 votes vote down vote up
public RaftJettyServer start(int port) {
  ServerConnector connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);

  // Setup the basic application "context" for this application at "/"
  // This is also known as the handler tree (in jetty speak)
  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath("/");
  server.setHandler(context);

  // Add a websocket to a specific path spec
  ServletHolder holderEvents = new ServletHolder("ws-events", new EventServlet(events));
  context.addServlet(holderEvents, "/events/*");

  // Add Raft REST services endpoints
  context.addServlet(new ServletHolder(new ServletContainer(raftApplication.makeResourceConfig())), "/raft/*");

  try {
    events.start();
    server.start();

    return this;
  } catch (Throwable t) {
    throw new RuntimeException(t);
  }
}
 
Example #9
Source File: SoaBundle.java    From soabase with Apache License 2.0 5 votes vote down vote up
private void initJerseyAdmin(SoaConfiguration configuration, SoaFeaturesImpl features, Ports ports, final Environment environment, AbstractBinder binder)
{
    if ( (configuration.getAdminJerseyPath() == null) || !ports.adminPort.hasPort() )
    {
        return;
    }

    String jerseyRootPath = configuration.getAdminJerseyPath();
    if ( !jerseyRootPath.endsWith("/*") )
    {
        if ( jerseyRootPath.endsWith("/") )
        {
            jerseyRootPath += "*";
        }
        else
        {
            jerseyRootPath += "/*";
        }
    }

    DropwizardResourceConfig jerseyConfig = new DropwizardResourceConfig(environment.metrics());
    jerseyConfig.setUrlPattern(jerseyRootPath);

    JerseyContainerHolder jerseyServletContainer = new JerseyContainerHolder(new ServletContainer(jerseyConfig));
    environment.admin().addServlet("soa-admin-jersey", jerseyServletContainer.getContainer()).addMapping(jerseyRootPath);

    JerseyEnvironment jerseyEnvironment = new JerseyEnvironment(jerseyServletContainer, jerseyConfig);
    features.putNamed(jerseyEnvironment, JerseyEnvironment.class, SoaFeatures.ADMIN_NAME);
    jerseyEnvironment.register(SoaApis.class);
    jerseyEnvironment.register(DiscoveryApis.class);
    jerseyEnvironment.register(DynamicAttributeApis.class);
    jerseyEnvironment.register(LoggingApis.class);
    jerseyEnvironment.register(binder);
    jerseyEnvironment.setUrlPattern(jerseyConfig.getUrlPattern());
    jerseyEnvironment.register(new JacksonMessageBodyProvider(environment.getObjectMapper()));

    checkCorsFilter(configuration, environment.admin());
    checkAdminGuiceFeature(environment, jerseyEnvironment);
}
 
Example #10
Source File: ApiService.java    From Qora with MIT License 5 votes vote down vote up
public ApiService()
{
	//CREATE CONFIG
	Set<Class<?>> s = new HashSet<Class<?>>();
       s.add(QoraResource.class);     
       s.add(SeedResource.class);  
       s.add(PeersResource.class);    
       s.add(TransactionsResource.class);
       s.add(BlocksResource.class);
       s.add(AddressesResource.class);
       s.add(WalletResource.class);
       s.add(PaymentResource.class);
       s.add(NamesResource.class);
       s.add(NameSalesResource.class);
       s.add(PollsResource.class);
       s.add(ArbitraryTransactionsResource.class);
       ResourceConfig config = new ResourceConfig(s);
	
       //CREATE CONTAINER
       ServletContainer container = new ServletContainer(config);
	
	//CREATE CONTEXT
       ServletContextHandler context = new ServletContextHandler();
       context.setContextPath("/");
       context.addServlet(new ServletHolder(container),"/*");
       
       //CREATE WHITELIST
       IPAccessHandler accessHandler = new IPAccessHandler();
       accessHandler.setWhite(Settings.getInstance().getRpcAllowed());
       accessHandler.setHandler(context);
       
       //CREATE RPC SERVER
     	this.server = new Server(Settings.getInstance().getRpcPort());
     	this.server.setHandler(accessHandler);
}
 
Example #11
Source File: ApiServer.java    From lancoder with GNU General Public License v3.0 5 votes vote down vote up
private ContextHandler buildServletContextHandler() throws Exception {
	WebApi webapp = new WebApi(master, master.getMasterEventCatcher());
	final ResourceConfig app = new ResourceConfig()
               .packages("jersey.jetty.embedded")
               .register(webapp);

       ServletHolder servletHolder = new ServletHolder(new ServletContainer(app));
	ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
	servletContextHandler.setSessionHandler(new SessionHandler());
	servletContextHandler.addServlet(servletHolder, "/*");
	return servletContextHandler;
}
 
Example #12
Source File: JerseyContainerConfigurator.java    From hammock with Apache License 2.0 5 votes vote down vote up
@Produces
public ServletDescriptor jerseyServlet() {
    String urlPattern = restServerConfiguration.getRestServletMapping();
    if (!applicationInstance.isUnsatisfied() && !applicationInstance.isAmbiguous()) {
        ApplicationPath annotation = ClassUtils.getAnnotation(applicationInstance.get().getClass(), ApplicationPath.class);
        if(annotation != null) {
            String path = annotation.value();
            urlPattern = path.endsWith("/") ? path + "*" : path + "/*";
        }
    }
    return new ServletDescriptor(SERVLET_NAME, null, new String[] { urlPattern }, 1, null, true, ServletContainer.class);
}
 
Example #13
Source File: DependencyResourceTest.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@Override
protected DeploymentContext configureDeployment() {
    return ServletDeploymentContext.forServlet(new ServletContainer(
            new ResourceConfig(DependencyResource.class)
                    .register(AuthenticationFilter.class)))
            .build();
}
 
Example #14
Source File: HttpServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Add a Jersey resource package.
 * @param packageName The Java package name containing the Jersey resource.
 * @param pathSpec The path spec for the servlet
 */
public void addJerseyResourcePackage(final String packageName,
    final String pathSpec) {
  LOG.info("addJerseyResourcePackage: packageName=" + packageName
      + ", pathSpec=" + pathSpec);

  ResourceConfig application = new ResourceConfig().packages(packageName);
  final ServletHolder sh = new ServletHolder(new ServletContainer(application));
  webAppContext.addServlet(sh, pathSpec);
}
 
Example #15
Source File: ITTracingApplicationEventListener.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void init(ServletContextHandler handler) {
  ResourceConfig config = new ResourceConfig();
  config.register(new TestResource(httpTracing));
  config.register(TracingApplicationEventListener.create(httpTracing));
  ServletHolder servlet = new ServletHolder(new ServletContainer(config));
  servlet.setAsyncSupported(true);
  handler.addServlet(servlet, "/*");
}
 
Example #16
Source File: RESTServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
private static Pair<FilterHolder, Class<? extends ServletContainer>> loginServerPrincipal(
  UserProvider userProvider, Configuration conf) throws Exception {
  Class<? extends ServletContainer> containerClass = ServletContainer.class;
  if (userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled()) {
    String machineName = Strings.domainNamePointerToHostName(
      DNS.getDefaultHost(conf.get(REST_DNS_INTERFACE, "default"),
        conf.get(REST_DNS_NAMESERVER, "default")));
    String keytabFilename = conf.get(REST_KEYTAB_FILE);
    Preconditions.checkArgument(keytabFilename != null && !keytabFilename.isEmpty(),
      REST_KEYTAB_FILE + " should be set if security is enabled");
    String principalConfig = conf.get(REST_KERBEROS_PRINCIPAL);
    Preconditions.checkArgument(principalConfig != null && !principalConfig.isEmpty(),
      REST_KERBEROS_PRINCIPAL + " should be set if security is enabled");
    // Hook for unit tests, this will log out any other user and mess up tests.
    if (!conf.getBoolean(SKIP_LOGIN_KEY, false)) {
      userProvider.login(REST_KEYTAB_FILE, REST_KERBEROS_PRINCIPAL, machineName);
    }
    if (conf.get(REST_AUTHENTICATION_TYPE) != null) {
      containerClass = RESTServletContainer.class;
      FilterHolder authFilter = new FilterHolder();
      authFilter.setClassName(AuthFilter.class.getName());
      authFilter.setName("AuthenticationFilter");
      return new Pair<>(authFilter,containerClass);
    }
  }
  return new Pair<>(null, containerClass);
}
 
Example #17
Source File: Starter.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void start() {

		Server server = new Server(9080);
		ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
		servletContextHandler.setContextPath("/");
		servletContextHandler.setResourceBase("src/main/webapp");

		final String webAppDirectory = JumbuneInfo.getHome() + "modules/webapp";
		final ResourceHandler resHandler = new ResourceHandler();
		resHandler.setResourceBase(webAppDirectory);
		final ContextHandler ctx = new ContextHandler("/");
		ctx.setHandler(resHandler);
		servletContextHandler.setSessionHandler(new SessionHandler());

		ServletHolder servletHolder = servletContextHandler.addServlet(ServletContainer.class, "/apis/*");
		servletHolder.setInitOrder(0);
		servletHolder.setAsyncSupported(true);
		servletHolder.setInitParameter("jersey.config.server.provider.packages", "org.jumbune.web.services");
		servletHolder.setInitParameter("jersey.config.server.provider.classnames",
				"org.glassfish.jersey.media.multipart.MultiPartFeature");

		try {
			server.insertHandler(servletContextHandler);
			server.insertHandler(resHandler);
			server.start();
			server.join();
		} catch (Exception e) {
			LOGGER.error("Error occurred while starting Jetty", e);
			System.exit(1);
		}
	}
 
Example #18
Source File: TestHttpTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
protected DeploymentContext configureDeployment() {
  forceSet(TestProperties.CONTAINER_PORT, String.valueOf(NetworkUtils.getRandomPort()));
  ResourceConfig resourceConfig = new ResourceConfig(MockServer.class);
  resourceConfig.register(SnappyReaderInterceptor.class);
  return ServletDeploymentContext.forServlet(
    new ServletContainer(resourceConfig)
  ).build();
}
 
Example #19
Source File: HttpServer.java    From heroic with Apache License 2.0 5 votes vote down vote up
private HandlerCollection setupHandler() throws Exception {
    final ResourceConfig resourceConfig = setupResourceConfig();
    final ServletContainer servlet = new ServletContainer(resourceConfig);

    final ServletHolder jerseyServlet = new ServletHolder(servlet);
    // Initialize and register Jersey ServletContainer

    jerseyServlet.setInitOrder(1);

    // statically provide injector to jersey application.
    final ServletContextHandler context =
        new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");

    GzipHandler gzip = new GzipHandler();
    gzip.setIncludedMethods("POST");
    gzip.setMinGzipSize(860);
    gzip.setIncludedMimeTypes("application/json");
    context.setGzipHandler(gzip);

    context.addServlet(jerseyServlet, "/*");
    context.addFilter(new FilterHolder(new ShutdownFilter(stopping, mapper)), "/*", null);
    context.setErrorHandler(new JettyJSONErrorHandler(mapper));

    final RequestLogHandler requestLogHandler = new RequestLogHandler();

    requestLogHandler.setRequestLog(new Slf4jRequestLog());

    final RewriteHandler rewrite = new RewriteHandler();
    makeRewriteRules(rewrite);

    final HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{rewrite, context, requestLogHandler});

    return handlers;
}
 
Example #20
Source File: BomResourceTest.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@Override
protected DeploymentContext configureDeployment() {
    return ServletDeploymentContext.forServlet(new ServletContainer(
            new ResourceConfig(BomResource.class)
                    .register(AuthenticationFilter.class)
                    .register(MultiPartFeature.class)))
            .build();
}
 
Example #21
Source File: CamundaBpmWebappInitializer.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private ServletRegistration registerServlet(final String servletName, final Class<?> applicationClass, final String... urlPatterns) {
  ServletRegistration servletRegistration = servletContext.getServletRegistration(servletName);

  if (servletRegistration == null) {
    servletRegistration = servletContext.addServlet(servletName, ServletContainer.class);
    servletRegistration.addMapping(urlPatterns);
    servletRegistration.setInitParameters(singletonMap(JAXRS_APPLICATION_CLASS, applicationClass.getName()));

    log.debug("Servlet {} for URL {} registered.", servletName, urlPatterns);
  }

  return servletRegistration;
}
 
Example #22
Source File: CamundaBpmWebappInitializer.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
private ServletRegistration registerServlet(final String servletName, final Class<?> applicationClass, final String... urlPatterns) {
  ServletRegistration servletRegistration = servletContext.getServletRegistration(servletName);

  if (servletRegistration == null) {
    servletRegistration = servletContext.addServlet(servletName, ServletContainer.class);
    servletRegistration.addMapping(urlPatterns);
    servletRegistration.setInitParameters(singletonMap(JAXRS_APPLICATION_CLASS, applicationClass.getName()));

    log.debug("Servlet {} for URL {} registered.", servletName, urlPatterns);
  }

  return servletRegistration;
}
 
Example #23
Source File: WebServer.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void addRestResources(String basePath, String javaPackages, String attribute, Object attributeValue) {
    ResourceConfig config = new ResourceConfig();
    config.packages("jersey.config.server.provider.packages", javaPackages);
    config.register(JsonMapperProvider.class);
    ServletHolder servletHolder = new ServletHolder(new ServletContainer(config));
    servletHolder.setAsyncSupported(true);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath(basePath);
    context.addServlet(servletHolder, "/*");
    context.setAttribute(attribute, attributeValue);
    handlers.add(context);
}
 
Example #24
Source File: AmforeasJetty.java    From amforeas with GNU General Public License v3.0 5 votes vote down vote up
private void setupJerseyServlet (final AmforeasConfiguration conf, final Server server) {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");

    ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, conf.getServerRoot());
    jerseyServlet.setInitOrder(0);
    jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "amforeas.rest, amforeas.filter");

    server.setHandler(context);
}
 
Example #25
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 #26
Source File: LicenseResourceTest.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@Override
protected DeploymentContext configureDeployment() {
    return ServletDeploymentContext.forServlet(new ServletContainer(
            new ResourceConfig(LicenseResource.class)
                    .register(AuthenticationFilter.class)))
            .build();
}
 
Example #27
Source File: ExecutionContainerModule.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Jetty server instance for the Flux Execution API endpoint.
 * @return Jetty Server instance
 */
@Named("ExecutionAPIJettyServer")
@Provides
@Singleton
Server getExecutionAPIJettyServer(@Named("Execution.Node.Api.service.port") int port,
                         @Named("ExecutionAPIResourceConfig")ResourceConfig resourceConfig,
                         @Named("Execution.Node.Api.service.acceptors") int acceptorThreads,
                         @Named("Execution.Node.Api.service.selectors") int selectorThreads,
                         @Named("Execution.Node.Api.service.workers") int maxWorkerThreads,
                         ObjectMapper objectMapper, MetricRegistry metricRegistry) throws URISyntaxException, UnknownHostException {
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    provider.setMapper(objectMapper);
    resourceConfig.register(provider);
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxWorkerThreads);
    Server server = new Server(threadPool);
    ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
    http.setPort(port);
    server.addConnector(http);
    ServletContextHandler context = new ServletContextHandler(server, "/*");
    ServletHolder servlet = new ServletHolder(new ServletContainer(resourceConfig));
    context.addServlet(servlet, "/*");

    final InstrumentedHandler handler = new InstrumentedHandler(metricRegistry);
    handler.setHandler(context);
    server.setHandler(handler);

    server.setStopAtShutdown(true);
    return server;
}
 
Example #28
Source File: ApiServer.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
ApiServer(SchedulerConfig schedulerConfig, Collection<Object> resources) {
  this.port = schedulerConfig.getApiServerPort();
  this.server = JettyHttpContainerFactory.createServer(
      UriBuilder.fromUri("http://0.0.0.0/").port(this.port).build(),
      new ResourceConfig(MultiPartFeature.class).registerInstances(new HashSet<>(resources)),
      false /* don't start yet. wait for start() call below. */);
  this.startTimeout = schedulerConfig.getApiServerInitTimeout();

  ServletContextHandler context = new ServletContextHandler();

  // Serve metrics registry content at these paths:
  Metrics.configureMetricsEndpoints(
      context,
      "/v1/metrics",
      "/v1/metrics/prometheus");
  // Serve resources at their declared paths relative to root:
  context
      .addServlet(
          new ServletHolder(
              new ServletContainer(
                  new ResourceConfig(MultiPartFeature.class)
                      .registerInstances(new HashSet<>(resources))
              )
          ),
          "/*");

  // Passthru handler: Collect basic metrics on queries, and store those metrics in the registry
  // TODO(nickbp): reimplement InstrumentedHandler with better/more granular metrics
  // (e.g. resource being queried)
  final InstrumentedHandler instrumentedHandler = new InstrumentedHandler(Metrics.getRegistry());
  instrumentedHandler.setHandler(context);

  server.setHandler(instrumentedHandler);
}
 
Example #29
Source File: Main.java    From wingtips with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler generateServletContextHandler() throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setContextPath("/");

    ResourceConfig rc = new ResourceConfig();
    rc.register(new SampleResource());
    rc.register(SpanCustomizingApplicationEventListener.create());
    contextHandler.addServlet(new ServletHolder(new ServletContainer(rc)), "/*");
    contextHandler.addFilter(RequestTracingFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    return contextHandler;
}
 
Example #30
Source File: SearchResourceTest.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@Override
protected DeploymentContext configureDeployment() {
    return ServletDeploymentContext.forServlet(new ServletContainer(
            new ResourceConfig(SearchResource.class)
                    .register(AuthenticationFilter.class)))
            .build();
}