Java Code Examples for org.glassfish.jersey.servlet.ServletContainer

The following are top voted examples for showing how to use org.glassfish.jersey.servlet.ServletContainer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: traccar-service   File: WebServer.java   View source code 7 votes vote down vote up
private void initApi() {
    ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletHandler.setContextPath("/api");
    servletHandler.getSessionHandler().setSessionManager(sessionManager);

    servletHandler.addServlet(new ServletHolder(new AsyncSocketServlet()), "/socket");

    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.registerClasses(JacksonFeature.class, ObjectMapperProvider.class, ResourceErrorHandler.class);
    resourceConfig.registerClasses(SecurityRequestFilter.class, CorsResponseFilter.class);
    resourceConfig.packages(ServerResource.class.getPackage().getName());

    servletHandler.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    handlers.addHandler(servletHandler);
}
 
Example 2
Project: security-mgr-sample-plugin   File: SecurityManagerServletDelegate.java   View source code 6 votes vote down vote up
@Activate
void activate() throws Exception {

    super.register(JacksonJaxbJsonProvider.class);
    super.property(ServerProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);

    Properties props = new Properties();
    props.setProperty(JDBC_URL, "jdbc:h2:./ismPlugin");
    props.setProperty(JDBC_USER, "admin");
    props.setProperty(JDBC_PASSWORD, "abc12345");

    DataSource ds = this.jdbcFactory.createDataSource(props);

    this.em = this.resourceFactory
            .getProviderFor(this.builder, singletonMap("javax.persistence.nonJtaDataSource", (Object) ds), null)
            .getResource(this.txControl);

    this.domainApis.init(this.em, this.txControl);
    this.deviceApis.init(this.em, this.txControl);
    this.securityGroupApis.init(this.em, this.txControl);
    this.securityGroupInterfaceApis.init(this.em, this.txControl);

    super.registerInstances(this.domainApis, this.deviceApis, this.securityGroupApis,
            this.securityGroupInterfaceApis);
    this.container = new ServletContainer(this);
}
 
Example 3
Project: Pet-Supply-Store   File: HeartbeatTest.java   View source code 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 4
Project: gitplex-mit   File: RestModule.java   View source code 6 votes vote down vote up
@Override
protected void configure() {
	super.configure();
	
	bind(ResourceConfig.class).toProvider(ResourceConfigProvider.class).in(Singleton.class);
	bind(ServletContainer.class).to(DefaultServletContainer.class);
	
	contribute(FilterChainConfigurator.class, new FilterChainConfigurator() {

		@Override
		public void configure(FilterChainManager filterChainManager) {
			filterChainManager.createChain("/rest/**", "noSessionCreation, authcBasic");
		}
		
	});
	
	contribute(JerseyConfigurator.class, new JerseyConfigurator() {
		
		@Override
		public void configure(ResourceConfig resourceConfig) {
			resourceConfig.packages(RestModule.class.getPackage().getName());
		}
		
	});
	
}
 
Example 5
Project: lyre   File: Lyre.java   View source code 6 votes vote down vote up
@Bean
public ServletRegistrationBean jerseyServletRegistration(
    JerseyProperties jerseyProperties, ResourceConfig config) {

    ServletRegistrationBean registration = new ServletRegistrationBean(
        new ServletContainer(config));

    for (Map.Entry<String, String> entry : jerseyProperties.getInit().entrySet()) {
        registration.addInitParameter(entry.getKey(), entry.getValue());
    }

    registration.addUrlMappings("/" +
        (StringUtils.isEmpty(lyreProperties.getApplicationPath()) ? "api" : lyreProperties.getApplicationPath())
        + "/*");
    registration.setName(APIx.class.getName());
    registration.setLoadOnStartup(1);
    return registration;

}
 
Example 6
Project: mycore   File: MCRJerseyTest.java   View source code 6 votes vote down vote up
@Override
public void start() {
    System.out.println("Starting GrizzlyTestContainer...");
    try {
        this.server = GrizzlyHttpServerFactory.createHttpServer(uri, rc);

        // Initialize and register Jersey Servlet
        WebappContext context = new WebappContext("WebappContext", "");
        ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
        registration.setInitParameter("javax.ws.rs.Application", rc.getClass().getName());
        // Add an init parameter - this could be loaded from a parameter in the constructor
        registration.setInitParameter("myparam", "myvalue");

        registration.addMapping("/*");
        context.deploy(server);
    } catch (ProcessingException e) {
        throw new TestContainerException(e);
    }
}
 
Example 7
Project: app-runner-router   File: WebServer.java   View source code 6 votes vote down vote up
private Handler createRestService() {
    ResourceConfig rc = new ResourceConfig();
    localRestResources.forEach(rc::register);
    rc.register(JacksonFeature.class);
    rc.register(CORSFilter.class);
    rc.addProperties(new HashMap<String,Object>() {{
        // Turn off buffering so results can be streamed
        put(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0);
    }});

    ServletHolder holder = new ServletHolder(new ServletContainer(rc));

    ServletContextHandler sch = new ServletContextHandler();
    sch.setContextPath("/api/v1");
    sch.addServlet(holder, "/*");

    return sch;
}
 
Example 8
Project: app-runner   File: WebServer.java   View source code 6 votes vote down vote up
private Handler createRestService() {
    ResourceConfig rc = new ResourceConfig();
    rc.register(systemResource);
    rc.register(appResource);
    rc.register(JacksonFeature.class);
    rc.register(CORSFilter.class);
    SwaggerDocs.registerSwaggerJsonResource(rc);
    rc.addProperties(new HashMap<String,Object>() {{
        // Turn off buffering so results can be streamed
        put(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0);
    }});

    ServletHolder holder = new ServletHolder(new ServletContainer(rc));

    ServletContextHandler sch = new ServletContextHandler();
    sch.setContextPath("/api/v1");
    sch.addServlet(holder, "/*");

    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.setHandler(sch);
    return gzipHandler;
}
 
Example 9
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: JerseyAutoConfigurationServletContainerTests.java   View source code 6 votes vote down vote up
@Bean
public TomcatEmbeddedServletContainerFactory tomcat() {
	return new TomcatEmbeddedServletContainerFactory() {

		@Override
		protected void postProcessContext(Context context) {
			Wrapper jerseyServlet = context.createWrapper();
			String servletName = Application.class.getName();
			jerseyServlet.setName(servletName);
			jerseyServlet.setServletClass(ServletContainer.class.getName());
			jerseyServlet.setServlet(new ServletContainer());
			jerseyServlet.setOverridable(false);
			context.addChild(jerseyServlet);
			context.addServletMapping("/*", servletName);
		}

	};
}
 
Example 10
Project: dcos-commons   File: SchedulerApiServer.java   View source code 6 votes vote down vote up
public SchedulerApiServer(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();

    // Metrics + Prometheus
    Metrics.configureMetricsEndpoints(context, "/v1/metrics", "/v1/metrics/prometheus");

    // Resources
    ResourceConfig resourceConfig = new ResourceConfig(MultiPartFeature.class)
            .registerInstances(new HashSet<>(resources));
    ServletHolder resourceHolder = new ServletHolder(new ServletContainer(resourceConfig));
    context.addServlet(resourceHolder, "/*");

    final InstrumentedHandler handler = new InstrumentedHandler(Metrics.getRegistry());
    handler.setHandler(context);
    server.setHandler(handler);
}
 
Example 11
Project: storytime-backend   File: StartServer.java   View source code 6 votes vote down vote up
/**
 * 
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
	context.setContextPath("/");
	Logger mainLogger = Logger.getInstance();
	mainLogger.out(Level.INFORMATIVE, "Main", "Starting server");
	Server server = new Server(8080);
	mainLogger.out(Level.INFORMATIVE, "Main", "Set handler");
	server.setHandler(context);

	ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
	jerseyServlet.setInitOrder(0);

	jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
	jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "view");

	server.start();
	server.join();
	mainLogger.out(Level.INFORMATIVE, "Main", "Server started");
}
 
Example 12
Project: jvm-assembler   File: AssemblerServer.java   View source code 6 votes vote down vote up
public void start() {
    workingDir.mkdirs();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
    jerseyServlet.setInitOrder(0);
    jerseyServlet.setInitParameter("javax.ws.rs.Application", AssemblerApp.class.getCanonicalName());

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

    try {
        jettyServer.start();
        int runningPort = getPort(jettyServer);
        System.out.printf("Server started successfully and is running on port %s.\n", runningPort);
        writePort(runningPort);
        jettyServer.join();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        jettyServer.destroy();
    }
}
 
Example 13
Project: parsec   File: ParsecWebListener.java   View source code 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    ServletContainer servlet = new ServletContainer(new DefaultApplication());
    ServletRegistration.Dynamic defaultWebapp = context.addServlet(DEFAULT_WEBAPP, servlet);

    if (null != defaultWebapp) {
        defaultWebapp.addMapping("/*");
        defaultWebapp.setLoadOnStartup(1);
    }

    ParsecWrapperServlet swaggerServlet = new ParsecWrapperServlet();
    ServletRegistration.Dynamic swagger = context.addServlet(SWAGGER_UI, swaggerServlet);

    if (null != swagger) {
        swagger.addMapping("/static/*");
    }
}
 
Example 14
Project: step   File: Grid.java   View source code 6 votes vote down vote up
private void initializeServer() {
	ResourceConfig resourceConfig = new ResourceConfig();
	resourceConfig.packages(GridServices.class.getPackage().getName());
	resourceConfig.register(JacksonJaxbJsonProvider.class);
	final Grid grid = this;
	
	resourceConfig.register(new AbstractBinder() {	
		@Override
		protected void configure() {
			bind(grid).to(Grid.class);
			bind(fileManager).to(FileProvider.class);
		}
	});
	ServletContainer servletContainer = new ServletContainer(resourceConfig);
			
	ServletHolder sh = new ServletHolder(servletContainer);
	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
	context.setContextPath("/");
	context.addServlet(sh, "/*");

	server = new Server(port);
	
	ContextHandlerCollection contexts = new ContextHandlerCollection();
       contexts.setHandlers(new Handler[] { context});
	server.setHandler(contexts);
}
 
Example 15
Project: spring-boot-concourse   File: JerseyAutoConfigurationServletContainerTests.java   View source code 6 votes vote down vote up
@Bean
public TomcatEmbeddedServletContainerFactory tomcat() {
	return new TomcatEmbeddedServletContainerFactory() {

		@Override
		protected void postProcessContext(Context context) {
			Wrapper jerseyServlet = context.createWrapper();
			String servletName = Application.class.getName();
			jerseyServlet.setName(servletName);
			jerseyServlet.setServletClass(ServletContainer.class.getName());
			jerseyServlet.setServlet(new ServletContainer());
			jerseyServlet.setOverridable(false);
			context.addChild(jerseyServlet);
			context.addServletMapping("/*", servletName);
		}

	};
}
 
Example 16
Project: ensemble   File: RestServer.java   View source code 6 votes vote down vote up
public void start(Controller controller) throws Exception {
    this.controller = controller;

    Server server = new Server(REST_SERVICE_PORT);

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("");
    servletContextHandler.addServlet(new ServletHolder(new ServletContainer(resourceConfig(controller))), "/*");
    server.setHandler(servletContextHandler);

    try {
        server.start();
        server.join();
    } finally {
        server.destroy();
    }
}
 
Example 17
Project: docker-stats-cloudwatch   File: DockerStatsDaemon.java   View source code 6 votes vote down vote up
public static void main(String... args) throws Exception {

        Server server = new Server(9999);
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

        ServletContainer servletContainer = new ServletContainer();
        ServletHolder servletHolder = new ServletHolder(servletContainer);
        servletHolder.setInitParameter(ServerProperties.PROVIDER_PACKAGES, "zanox.docker.rest");
        servletHolder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
                "com.sun.jersey.api.core.PackagesResourceConfig");

        context.addServlet(servletHolder, "/*");
        server.start();

        HttpClient httpClient = new HttpClient();
        httpClient.start();

        ContentResponse response = httpClient
                .GET("http://127.0.0.1:9999/docker-stats/start");

    }
 
Example 18
Project: jersey2-guice-embedded-jetty-poc   File: Main.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    // todo: resource handler

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

    ServletHolder servletHolder = new ServletHolder(new ServletContainer());
    servletHolder.setInitParameter("javax.ws.rs.Application", MyApplication.class.getCanonicalName());
    context.addServlet(servletHolder, "/*");

    server.start();
    server.join();
}
 
Example 19
Project: scouter   File: WebAppMain.java   View source code 6 votes vote down vote up
private static ServletContextHandler setWebHttpApiHandler () {
    ConfigureAdaptor conf = ConfigureManager.getConfigure();

    String providerPackages = "scouterx.webapp";
    if (conf.isNetHttpApiSwaggerEnabled()) {
        providerPackages += ",io.swagger.jaxrs.listing";
    }

    final ServletHolder jerseyHolder = new ServletHolder(ServletContainer.class);
    jerseyHolder.setInitParameter("javax.ws.rs.Application", "scouterx.webapp.main.WebAppMain");
    jerseyHolder.setInitParameter("jersey.config.server.provider.packages", providerPackages);
    jerseyHolder.setInitOrder(1);

    final ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setSessionHandler(new SessionHandler());
    servletContextHandler.getSessionHandler().setMaxInactiveInterval(conf.getNetHttpApiSessionTimeout());
    servletContextHandler.setContextPath("/");

    servletContextHandler.addServlet(jerseyHolder, "/scouter/*");
    servletContextHandler.addServlet(setStaticContentHandler(), "/*");
    servletContextHandler.addServlet(setSwaggerBootstrapHandler(), "/swagger");

    addFilter(servletContextHandler);

    return servletContextHandler;
}
 
Example 20
Project: elide   File: Main.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final Server server = new Server(4080);
    final ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("/");
    server.setHandler(servletContextHandler);

    final ServletHolder servletHolder = servletContextHandler.addServlet(ServletContainer.class, "/*");
    servletHolder.setInitOrder(1);
    servletHolder.setInitParameter("jersey.config.server.provider.packages",
            JsonApiEndpoint.class.getPackage().getName());
    servletHolder.setInitParameter("javax.ws.rs.Application",
            ElideResourceConfig.class.getCanonicalName());

    log.info("Web service starting...");
    server.start();

    log.info("Web service running...");
    server.join();
    server.destroy();
}
 
Example 21
Project: elide   File: Main.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final Server server = new Server(4080);
    final ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("/");
    server.setHandler(servletContextHandler);

    final ServletHolder servletHolder = servletContextHandler.addServlet(ServletContainer.class, "/*");
    servletHolder.setInitOrder(1);
    servletHolder.setInitParameter("jersey.config.server.provider.packages",
            JsonApiEndpoint.class.getPackage().getName());
    servletHolder.setInitParameter("javax.ws.rs.Application",
            ElideResourceConfig.class.getCanonicalName());

    log.info("Web service starting...");
    server.start();

    log.info("Web service running...");
    server.join();
    server.destroy();
}
 
Example 22
Project: datacollector   File: DisconnectedSSOManager.java   View source code 6 votes vote down vote up
public void registerResources(ServletContextHandler handler) {
  ServletHolder jerseyServlet = new ServletHolder(ServletContainer.class);
  jerseyServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES, getClass().getPackage().getName());
  jerseyServlet.setInitParameter(
      ServletProperties.JAXRS_APPLICATION_CLASS,
      DisconnectedResourceConfig.class.getName()
  );
  handler.addServlet(jerseyServlet, SECURITY_RESOURCES);

  AuthenticationResourceHandler authenticationResourceHandler =
      new AuthenticationResourceHandler(getAuthentication(), false);

  handler.setAttribute(DISCONNECTED_SSO_AUTHENTICATION_HANDLER_ATTR, authenticationResourceHandler);

  handler.setAttribute(DISCONNECTED_SSO_SERVICE_ATTR, getSsoService());

  ServletHolder login = new ServletHolder(new DisconnectedLoginServlet((DisconnectedSSOService) getSsoService()));
  handler.addServlet(login, DisconnectedLoginServlet.URL_PATH);

  ServletHolder logout = new ServletHolder(new DisconnectedLogoutServlet((DisconnectedSSOService) getSsoService()));
  handler.addServlet(logout, DisconnectedLogoutServlet.URL_PATH);
}
 
Example 23
Project: datacollector   File: WebServerModule.java   View source code 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/*");

      // 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 24
Project: datacollector   File: HttpClientSourceIT.java   View source code 6 votes vote down vote up
@Override
protected DeploymentContext configureDeployment() {
  return ServletDeploymentContext.forServlet(
      new ServletContainer(
          new ResourceConfig(
              Sets.newHashSet(
                  StreamResource.class,
                  NewlineStreamResource.class,
                  TextStreamResource.class,
                  SlowTextStreamResource.class,
                  XmlStreamResource.class,
                  PreemptiveAuthResource.class,
                  AuthResource.class,
                  HeaderRequired.class,
                  AlwaysUnauthorized.class,
                  HttpStageTestUtil.TestPostCustomType.class,
                  StreamTokenResetResource.class,
                  Auth2Resource.class,
                  Auth2ResourceOwnerWithIdResource.class,
                  Auth2BasicResource.class,
                  Auth2JWTResource.class
              )
          )
      )
  ).build();
}
 
Example 25
Project: bagri   File: BagriRestServer.java   View source code 6 votes vote down vote up
public void start() {
    logger.debug("start.enter; Starting rest server");
    jettyServer = createServer();
    ResourceConfig config = buildConfig();
    ServletHolder servlet = new ServletHolder(new ServletContainer(config));
    ServletContextHandler context = new ServletContextHandler(jettyServer, "/*");
    context.addServlet(servlet, "/*");
    bildSwaggerConfig();
    
    try {
        jettyServer.start();
        //jettyServer.join();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    logger.debug("start.exit; Rest server is started");
}
 
Example 26
Project: hbase   File: RESTServer.java   View source code 6 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");
    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 27
Project: jersey2-guice-example   File: ServerBuilder.java   View source code 6 votes vote down vote up
public Server build() {
  ServiceLocator locator = BootstrapUtils.newServiceLocator();
  Injector injector = BootstrapUtils.newInjector(locator, Arrays.asList(new ServletModule(), new MyModule()));

  BootstrapUtils.install(locator);

  Server server = new Server(port);

  ResourceConfig config = ResourceConfig.forApplication(new MyApplication());

  ServletContainer servletContainer = new ServletContainer(config);

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

  FilterHolder filterHolder = new FilterHolder(GuiceFilter.class);
  context.addFilter(filterHolder, "/*",
                    EnumSet.allOf(DispatcherType.class));

  context.addServlet(sh, "/*");
  server.setHandler(context);
  return server;
}
 
Example 28
Project: MIB   File: JettyUtils.java   View source code 6 votes vote down vote up
/**
 * Initializes an embedded Jetty instance. The instance is runnable out of
 * the box, but won't detect your jax-rs services unless you provide the
 * packages to scan for additional resources.
 * 
 * @param options
 *            The command line options from the caller.
 * @param additionalPackagesToScan
 *            The packages to scan for webservice implementations (jax-rs
 *            classes).
 * @return The configured Jetty instance.
 */
public static Server initializeJetty(CLI options, String... additionalPackagesToScan) {
	Server server = createServer(options);
	ServletContextHandler context = createServletContext(server);

	//length + 1 to make place for the genson package.
	String [] packagesToScan = Arrays.copyOf(additionalPackagesToScan, additionalPackagesToScan.length + 1);
	packagesToScan[packagesToScan.length - 1] = "com.owlike.genson.ext.jaxrs";
	ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
	// Package scan is used to detect resources. This implies that all
	// services we write are placed in the
	// "package mib.api.gateway.service".
	// "com.owlike.genson.ext.jaxrs" adds the genson library as provider for
	// MessageBodyWriter and MessageBodyReader.
	jerseyServlet.setInitParameter("jersey.config.server.provider.packages", StringUtils.join(packagesToScan, ','));
	return server;
}
 
Example 29
Project: smaph   File: ServerMain.java   View source code 5 votes vote down vote up
/**
 * Starts Grizzly HTTP server exposing SMAPH JAX-RS resources.
 * 
 * @throws URISyntaxException
 * @throws ProcessingException
 */
public static void startServer(String serverUri, Path storageBase, String watGcubeToken) throws ProcessingException, URISyntaxException {
	LOG.info("Initializing SMAPH services.");
	LOG.info("Storage path: {}", storageBase.toAbsolutePath());

	HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(new URI(serverUri));
	httpServer.getServerConfiguration().addHttpHandler(new StaticHttpHandler("src/main/webapp/"), "/*");

	WebappContext context = new WebappContext("smaph");
	ResourceConfig rc = new ResourceConfig().packages("it.unipi.di.acube.smaph.servlet");
	ServletRegistration registration = context.addServlet("ServletContainer", new ServletContainer(rc));
	registration.addMapping("/smaph/*");
	context.addListener(SmaphContextListener.class);
	context.setInitParameter(SmaphContextListener.WIKI_PAGES_DB, storageBase.resolve("mapdb/wikipedia_pages.db").toString());
	context.setInitParameter(SmaphContextListener.FREEBASE_DIR, storageBase.resolve("mapdb/freebase.db").toString());
	context.setInitParameter(SmaphContextListener.ENTITY_TO_ANCHORS_DB, storageBase.resolve("mapdb/e2a.db").toString());
	context.setInitParameter(SmaphContextListener.WAT_GCUBE_TOKEN, watGcubeToken);
	context.deploy(httpServer);
	try {
		httpServer.start();
		LOG.info("Smaph started with WADL available at " + "{}application.wadl\nPress CTRL^C (SIGINT) to terminate.",
		        serverUri);
		Thread.currentThread().join();
		LOG.info("Shutting server down..");
	} catch (Exception e) {
		LOG.error("There was an error while starting Grizzly HTTP server.", e);
	}
}
 
Example 30
Project: streamsx.jmxclients   File: RestServer.java   View source code 5 votes vote down vote up
public HttpServer startServer() throws IOException {
    	HttpServer theServer;
    	
//        String[] packages = { "streams.prometheus.exporter.rest.resources",
//                "streams.prometheus.exporter.rest.errorhandling",
//                "streams.prometheus.exporter.rest.serializers" };

        //final ResourceConfig rc = new ResourceConfig().packages(packages);
        // Enable JSON media conversions
        //rc.register(JacksonFeature.class);
        
        WebappContext context = new WebappContext("WebappContext","");
        ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
        registration.setInitParameter("jersey.config.server.provider.packages",
        		"streams.metric.exporter.rest.resources;streams.metric.exporter.rest.errorhandling;streams.metric.exporter.rest.serializers");
        registration.addMapping("/*");
        
       //if (this.serverProtocol.equalsIgnoreCase("https")) {
        if (this.serverProtocol == Protocol.HTTPS) {

        	LOGGER.debug("Using https protocol");
        	theServer = createHttpsServer();
        } else {
        	LOGGER.debug("Using http protcol");
        	theServer = createHttpServer();
        }
        // Prometheus servlet
        // FUTURE: if we go with plugin this needs to be variant if it is created or not
        //ServletRegistration prometheus = context.addServlet("PrometheusContainer",new MetricsServlet());
        //prometheus.addMapping("/prometheus");
        
        context.deploy(theServer);
        
        theServer.start();
 
        return theServer;
    }
 
Example 31
Project: osgi-starterkit   File: Config.java   View source code 5 votes vote down vote up
public Config() throws URISyntaxException, ClassNotFoundException{
	ResourceConfig rc = new ResourceConfig();
	
	//rc.packages() not working properly atm..., add all classes manually here
	//rc.registerClasses(Status.class /*, AnotherResource.class, ...*/);
	
	String[] packages = {"com.demo.app.restapi.impl"};
	ClassLoader cl = getClass().getClassLoader();
	boolean recur = false;
   	OsgiRegistry reg = ReflectionHelper.getOsgiRegistryInstance();
       logger.info("Created! OSGI runtime? " + (reg == null? "No" : "Yes"));
       
       //CompositeResourceFinder finder = new CompositeResourceFinder();
       //BundleSchemeResourceFinderFactory f = new BundleSchemeResourceFinderFactory(); until it is made public...
       
       for(String p: packages){
       	p = p.replace('.', '/');
       	Enumeration<URL> list = reg.getPackageResources(p, cl, recur);
           while(list.hasMoreElements()){
           	URL url = list.nextElement();
           	String path = url.getPath();
           	String cls = (OsgiRegistry.bundleEntryPathToClassName(path, "") + "class").replace(".class", "");
           	logger.info("Found(" + url.toURI().getScheme() + "):" + path + "-->" + cls);
           	
           	rc.registerClasses(reg.classForNameWithException(cls));
           	//finder.push(f.create(url.toURI(), recur));
           }
       }
       //rc.registerFinder(finder);

	//rc.registerFinder(new PackageNamesScanner(cl, packages, false)); !bundleentry is not bundle...
       //INFO: Found(bundleentry):/com/demo/app/restapi/impl/Status.class-->com.demo.app.restapi.impl.Status.
	
       //////////////////////////////////////////////////////////////////////////
	this.sc = new ServletContainer(rc);
}
 
Example 32
Project: sdn-controller-nsc-plugin   File: SampleSdnServletDelegate.java   View source code 5 votes vote down vote up
@Activate
void activate() throws Exception {

    super.register(JacksonJaxbJsonProvider.class);
    super.property(ServerProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
    super.registerInstances(this.inspectionPortApis, this.portApis, this.inspectionHookApis);
    this.container = new ServletContainer(this);
}
 
Example 33
Project: Pet-Supply-Store   File: RegistryTest.java   View source code 5 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 {
	testTomcat = new Tomcat();
	testTomcat.setPort(0);
	testTomcat.setBaseDir(testWorkingDir);
	Context context = testTomcat.addWebapp(CONTEXT, testWorkingDir);
	ResourceConfig restServletConfig = new ResourceConfig();
	restServletConfig.register(RegistryREST.class);
	restServletConfig.register(Registry.class);
	ServletContainer restServlet = new ServletContainer(restServletConfig);
	testTomcat.addServlet(CONTEXT, "restServlet", restServlet);
	context.addServletMappingDecoded("/rest/*", "restServlet");
	testTomcat.start();
}
 
Example 34
Project: Pet-Supply-Store   File: CRUDClientServerTest.java   View source code 5 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 {
	testTomcat = new Tomcat();
	testTomcat.setPort(0);
	testTomcat.setBaseDir(testWorkingDir);
	Context context = testTomcat.addWebapp(CONTEXT, testWorkingDir);
	ResourceConfig restServletConfig = new ResourceConfig();
	restServletConfig.register(TestEntityEndpoint.class);
	ServletContainer restServlet = new ServletContainer(restServletConfig);
	testTomcat.addServlet(CONTEXT, "restServlet", restServlet);
	context.addServletMappingDecoded("/rest/*", "restServlet");
	testTomcat.start();
}
 
Example 35
Project: jobson   File: CustomAuthenticatorConfigTest.java   View source code 5 votes vote down vote up
private static AuthenticationBootstrap createTypicalAuthBootstrap() {
    final UserDAO userDAO = mock(UserDAO.class);
    final Server s = new Server(0);
    final Servlet se = new ServletContainer();
    final JerseyEnvironment env = new JerseyEnvironment(new JerseyContainerHolder(se), new DropwizardResourceConfig());

    return new AuthenticationBootstrap(env, userDAO);
}
 
Example 36
Project: osc-core   File: ApiServletDelegate.java   View source code 5 votes vote down vote up
@Activate
void activate() {
    //Json feature
    super.register(JacksonJaxbJsonProvider.class);

    //Auth Filters
    super.registerInstances(this.oscAuthFilter, this.localHostAuthFilter);

    //Exception mappers
    super.register(BadRequestExceptionMapper.class);
    super.register(InternalServerErrorExceptionMapper.class);
    super.register(JsonProcessingExceptionMapper.class);
    super.register(NotFoundExceptionMapper.class);
    super.register(PathParamExceptionMapper.class);
    super.register(XMLParseExceptionMapper.class);

    //Properties
    super.property(ServerProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);

    // agent & server apis
    super.registerInstances(this.alarmApis, this.alertApis, this.applianceApis, this.distributedApplianceApis,
            this.distributedApplianceInstanceApis, this.jobApis, this.managerApis, this.managerConnectorApis,
            this.nsmMgrApis, this.serverDebugApis, this.serverMgmtApis, this.virtualSystemApis,
            this.virtualizationConnectorApis);

    this.container = new ServletContainer(this);
}
 
Example 37
Project: karate   File: MockJerseyServlet.java   View source code 5 votes vote down vote up
/**
 * this zero-arg constructor will be invoked if you use the 'configure
 * httpClientClass' option refer to the MockJerseyServletFactory for how you
 * can construct this manually and have full control over
 * dependency-injection specific to your environment
 *
 * @throws Exception
 */
public MockJerseyServlet() throws Exception {
    logger.info("auto construction of mock http servlet");
    ServletConfig servletConfig = new MockServletConfig();
    servletContext = new MockServletContext();
    ResourceConfig resourceConfig = new ResourceConfig(HelloResource.class);
    servlet = new ServletContainer(resourceConfig);
    servlet.init(servletConfig);
}
 
Example 38
Project: gitplex-mit   File: ProductServletConfigurator.java   View source code 5 votes vote down vote up
@Inject
public ProductServletConfigurator(ServerConfig serverConfig, ShiroFilter shiroFilter, GitFilter gitFilter, 
		GitPreReceiveCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet, 
		WicketServlet wicketServlet, WebSocketManager webSocketManager, ServletContainer jerseyServlet) {
	this.serverConfig = serverConfig;
	this.shiroFilter = shiroFilter;
       this.gitFilter = gitFilter;
	this.preReceiveServlet = preReceiveServlet;
	this.postReceiveServlet = postReceiveServlet;
	this.wicketServlet = wicketServlet;
	this.webSocketManager = webSocketManager;
	this.jerseyServlet = jerseyServlet;
}
 
Example 39
Project: jersey-jwt   File: ArquillianTest.java   View source code 5 votes vote down vote up
@Deployment(testable = false)
public static Archive<WebArchive> createDeployment() {

    return ShrinkWrap.create(UndertowWebArchive.class).from(
            deployment()
                    .setClassLoader(Application.class.getClassLoader())
                    .setContextPath("/")
                    .addListeners(listener(Listener.class))
                    .addServlets(
                            Servlets.servlet("jerseyServlet", ServletContainer.class)
                                    .setLoadOnStartup(1)
                                    .addInitParam("javax.ws.rs.Application", JerseyConfig.class.getName())
                                    .addMapping("/api/*"))
                    .setDeploymentName("application.war"));
}
 
Example 40
Project: uavstack   File: JerseyConfig.java   View source code 5 votes vote down vote up
@Bean
public ServletRegistrationBean jerseyServlet() {

    ServletRegistrationBean registration = new ServletRegistrationBean(new ServletContainer(), "/rest/*");
    // our rest resources will be available in the path /rest/*
    registration.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyConfig.class.getName());
    return registration;
}