Java Code Examples for com.sun.jersey.api.core.PackagesResourceConfig

The following are top voted examples for showing how to use com.sun.jersey.api.core.PackagesResourceConfig. 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: AthenaX   File: WebServer.java   Source Code and License 6 votes vote down vote up
public WebServer(URI endpoint) throws IOException {
  this.server = GrizzlyServerFactory.createHttpServer(endpoint, new HttpHandler() {

    @Override
    public void service(Request rqst, Response rspns) throws Exception {
      rspns.setStatus(HttpStatus.NOT_FOUND_404.getStatusCode(), "Not found");
      rspns.getWriter().write("404: not found");
    }
  });

  WebappContext context = new WebappContext("WebappContext", BASE_PATH);
  ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
  registration.setInitParameter(ServletContainer.RESOURCE_CONFIG_CLASS,
      PackagesResourceConfig.class.getName());

  StringJoiner sj = new StringJoiner(",");
  for (String s : PACKAGES) {
    sj.add(s);
  }

  registration.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, sj.toString());
  registration.addMapping(BASE_PATH);
  context.deploy(server);
}
 
Example 2
Project: jersey-guice-bootstrap   File: BootstrapServletModule.java   Source Code and License 6 votes vote down vote up
@Override
protected void configureServlets() {
	super.configureServlets();
	
	//get the bootstrapping Properties file
	install(new BootstrapPropertiesModule());
	
	//Initialize Persistence JPA Unit of Work if present
	//install(new MyUnitOfWorkModule());
	//Initialize Apache Shiro if present
	//install(new YourShiroModule(getServletContext()));
	
	Map<String, String> params = new HashMap<String, String>();
       params.put(PackagesResourceConfig.PROPERTY_PACKAGES, propertyPackages);
       //if you had a Persistence Service like JPA Unit of Work you would need to add this PersistFilter also.
       //filter("/*").through(PersistFilter.class);
       //if you had a ShiroWebModule installed above you would need to add this GuiceShiroFilter also.
       //filter("/*").through(GuiceShiroFilter.class);
       serve("/rest/*").with(GuiceContainer.class, params);
       
}
 
Example 3
Project: secure-rest-webapp-archetype   File: BootstrapServletModule.java   Source Code and License 6 votes vote down vote up
@Override
protected void configureServlets() {
	super.configureServlets();
	
	//get the bootstrapping Properties file
	install(new BootstrapPropertiesModule());
	
	//Initialize Persistence JPA Unit of Work if present
	//install(new MyUnitOfWorkModule());
	//Initialize Apache Shiro if present
	install(new BootstrapShiroModule(getServletContext()));
	//This allows Shiro AOP Annotations http://shiro.apache.org/java-authorization-guide.html
	install(new ShiroAnnotationsModule());
	
	Map<String, String> params = new HashMap<String, String>();
       params.put(PackagesResourceConfig.PROPERTY_PACKAGES, propertyPackages);
       //if you had a Persistence Service like JPA Unit of Work you would need to add this PersistFilter also.
       //filter("/*").through(PersistFilter.class);
       //if you had a ShiroWebModule installed above you would need to add this GuiceShiroFilter also.
       filter("/*").through(GuiceShiroFilter.class);
       serve("/rest/*").with(GuiceContainer.class, params);
       
}
 
Example 4
Project: jersey-guice-bootstrap-archetype   File: BootstrapServletModule.java   Source Code and License 6 votes vote down vote up
@Override
protected void configureServlets() {
	super.configureServlets();
	
	//get the bootstrapping Properties file
	install(new BootstrapPropertiesModule());
	
	//Initialize Persistence JPA Unit of Work if present
	//install(new MyUnitOfWorkModule());
	//Initialize Apache Shiro if present
	//install(new YourShiroModule(getServletContext()));
	
	Map<String, String> params = new HashMap<String, String>();
       params.put(PackagesResourceConfig.PROPERTY_PACKAGES, propertyPackages);
       //if you had a Persistence Service like JPA Unit of Work you would need to add this PersistFilter also.
       //filter("/*").through(PersistFilter.class);
       //if you had a ShiroWebModule installed above you would need to add this GuiceShiroFilter also.
       //filter("/*").through(GuiceShiroFilter.class);
       serve("/rest/*").with(GuiceContainer.class, params);
       
}
 
Example 5
Project: fiware-cosmos-ambari   File: StartServer.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
  Map<String, String> mapArgs = parseArgs(args);
  System.out.println("Starting Ambari API server using the following properties: " + mapArgs);
  System.setProperty("ambariapi.dbfile", mapArgs.get("db"));

  ResourceConfig config = new PackagesResourceConfig("org.apache.ambari.server.api.services");
  System.out.println("Starting server: http://localhost:" + mapArgs.get("port") + '/');
  HttpServer server = HttpServerFactory.create("http://localhost:" + mapArgs.get("port") + '/', config);
  server.start();

  System.out.println("SERVER RUNNING: http://localhost:" + mapArgs.get("port") + '/');
  System.out.println("Hit return to stop...");
  System.in.read();
  System.out.println("Stopping server");
  server.stop(0);
  System.out.println("Server stopped");
}
 
Example 6
Project: shiro-guice-jersey-bootstrap   File: BootstrapServletModule.java   Source Code and License 6 votes vote down vote up
@Override
protected void configureServlets() {
	super.configureServlets();
	
	//get the bootstrapping Properties file
	install(new BootstrapPropertiesModule());
	
	//Initialize Persistence JPA Unit of Work if present
	//install(new MyUnitOfWorkModule());
	//Initialize Apache Shiro if present
	install(new BootstrapShiroModule(getServletContext()));
	//This allows Shiro AOP Annotations http://shiro.apache.org/java-authorization-guide.html
	install(new ShiroAnnotationsModule());
	
	Map<String, String> params = new HashMap<String, String>();
       params.put(PackagesResourceConfig.PROPERTY_PACKAGES, propertyPackages);
       //if you had a Persistence Service like JPA Unit of Work you would need to add this PersistFilter also.
       //filter("/*").through(PersistFilter.class);
       //if you had a ShiroWebModule installed above you would need to add this GuiceShiroFilter also.
       filter("/*").through(GuiceShiroFilter.class);
       serve("/rest/*").with(GuiceContainer.class, params);
       
}
 
Example 7
Project: appstart   File: AppServletModule.java   Source Code and License 6 votes vote down vote up
@Override
protected void configureServlets() {
	
	// filters
	// Objectify filter
	filter("/*").through(ObjectifyFilter.class);

	// servlets
	serve("/home").with(HomeServlet.class);
	
	// Jersey restful servlet
    HashMap<String, String> params = new HashMap<String, String>();
       params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "uk.co.inetria.appstart.frontend.rest");
       params.put(JSONConfiguration.FEATURE_POJO_MAPPING, "true");
       // speed up jersey startup under appengine
       params.put(ResourceConfig.FEATURE_DISABLE_WADL, "true");
       
       serve("/api/*").with(GuiceContainer.class, params);
	
	
}
 
Example 8
Project: ribbon   File: NettyClientTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass 
public static void init() throws Exception {
    PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.ribbon.test.resources");
    port = (new Random()).nextInt(1000) + 4000;
    SERVICE_URI = "http://localhost:" + port + "/";
    ExecutorService service = Executors.newFixedThreadPool(20);
    try{
        server = HttpServerFactory.create(SERVICE_URI, resourceConfig);           
        server.setExecutor(service);
        server.start();
    } catch(Exception e) {
        e.printStackTrace();
        fail("Unable to start server");
    }
    // LogManager.getRootLogger().setLevel(Level.DEBUG);
}
 
Example 9
Project: ribbon   File: ExampleAppWithLocalResource.java   Source Code and License 6 votes vote down vote up
@edu.umd.cs.findbugs.annotations.SuppressWarnings
public final void runApp() throws Exception {
    PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.ribbon.examples.server");
    ExecutorService service = Executors.newFixedThreadPool(50);
    try{
        server = HttpServerFactory.create(SERVICE_URI, resourceConfig);           
        server.setExecutor(service);
        server.start();
        run();
    } finally {
        System.err.println("Shut down server ...");
        if (server != null) {
            server.stop(1);
        }
        service.shutdownNow();
    }
    System.exit(0);
}
 
Example 10
Project: pi   File: HttpServerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testHttpServerStartStop() {
    // setup
    this.resourceConfig = new PackagesResourceConfig("com.bt.pi.sss.test");

    // act
    this.httpServer = new HttpServer(resourceConfig);
    this.httpServer.setPort("9090");
    this.httpServer.setApplicationContext(new StaticApplicationContext());
    try {
        this.httpServer.init();
        assertTrue(Boolean.getBoolean("com.sun.grizzly.util.buf.UDecoder.ALLOW_ENCODED_SLASH"));
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        this.httpServer.destroy();
    }

    // assert
}
 
Example 11
Project: moskito-central   File: RESTConnectorHttpsTest.java   Source Code and License 6 votes vote down vote up
public static void start() {
    WebappContext webappContext = new WebappContext("TestContext");
    ServletRegistration registration = webappContext.addServlet("ServletContainer", ServletContainer.class);
    registration.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, "org.moskito.central.connectors.rest;org.codehaus.jackson.jaxrs");
    registration.addMapping("/*");

    SSLContextConfigurator sslConfigurator = new SSLContextConfigurator();
    sslConfigurator.setKeyStoreFile("./target/test-classes/central_server_keystore.jks");
    sslConfigurator.setKeyStorePass("moskito");
    SSLContext sslContext = sslConfigurator.createSSLContext();

    try {
        server = GrizzlyServerFactory.createHttpServer(
                getBaseURI(),
                null,
                true,
                new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(false)
        );

        webappContext.deploy(server);
        server.start();
    } catch (Exception e) {
        System.out.println("Error while starting the test server: " + e);
    }
}
 
Example 12
Project: AisAbnormal   File: RestModule.java   Source Code and License 6 votes vote down vote up
@Override
protected void configureServlets() {
    ResourceConfig rc = new PackagesResourceConfig(
            "dk.dma.ais.abnormal.event.rest",
            "dk.dma.ais.abnormal.stat.rest",
            "dk.dma.commons.web.rest.defaults",
            "org.codehaus.jackson.jaxrs"
    );

    for ( Class<?> resource : rc.getClasses() ) {
        String packageName = resource.getPackage().getName();
        if (packageName.equals("dk.dma.commons.web.rest.defaults") || packageName.equals("org.codehaus.jackson.jaxrs")) {
            bind(resource).in(Scopes.SINGLETON);
        } else {
            bind(resource);
        }
    }

    serve("/rest/*").with( GuiceContainer.class );
}
 
Example 13
Project: hbase-indexer   File: Main.java   Source Code and License 6 votes vote down vote up
private void startHttpServer() throws Exception {
    server = new Server();
    SelectChannelConnector selectChannelConnector = new SelectChannelConnector();
    selectChannelConnector.setPort(11060);
    server.setConnectors(new Connector[]{selectChannelConnector});

    PackagesResourceConfig packagesResourceConfig = new PackagesResourceConfig("com/ngdata/hbaseindexer/rest");

    ServletHolder servletHolder = new ServletHolder(new ServletContainer(packagesResourceConfig));
    servletHolder.setName("HBase-Indexer");


    Context context = new Context(server, "/", Context.NO_SESSIONS);
    context.addServlet(servletHolder, "/*");
    context.setContextPath("/");
    context.setAttribute("indexerModel", indexerModel);
    context.setAttribute("indexerSupervisor", indexerSupervisor);

    server.setHandler(context);
    server.start();
}
 
Example 14
Project: jetty-guice   File: MainModule.java   Source Code and License 6 votes vote down vote up
@Override
    protected void configureServlets() {
        bind(MetricsServlet.class).asEagerSingleton();

        Map<String, String> parameters = new HashMap<>();
        parameters.put(JSONConfiguration.FEATURE_POJO_MAPPING, "true");
//        parameters.put("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
//        parameters.put("com.sun.jersey.config.property.packages", packageName);
        parameters.put("jersey.config.beanValidation.enableOutputValidationErrorEntity.server", "true");
        parameters.put("com.sun.jersey.api.json.POJOMappingFeature", "true");

        ResourceConfig rc = new PackagesResourceConfig(packageName);
        for (Class<?> resource : rc.getClasses()) {
            bind(resource).asEagerSingleton();
        }

        serve("/metrics").with(MetricsServlet.class);
        serve("/rest/*").with(GuiceContainer.class, parameters);
    }
 
Example 15
Project: load-test-target   File: AppServletContextListener.java   Source Code and License 6 votes vote down vote up
@Override
protected Injector getInjector() {
    final ResourceConfig rc = new PackagesResourceConfig( PredictableResponseService.class.getPackage().getName() );

    return Guice.createInjector( new ServletModule() {
        @Override
        protected void configureServlets() {
            bind( ResponsesProvider.class ).to( PreFabricatedResponses.class );
            bind( ResourceLoader.class ).to( FileResourceLoader.class );

            for ( Class<?> resource : rc.getClasses() ) {
                System.out.println( "Binding resource: " + resource.getName() );
                bind( resource );
            }

            serve( "/loadtest/*" ).with( GuiceContainer.class );
        }
    } );
}
 
Example 16
Project: joynr   File: TestContextListener.java   Source Code and License 6 votes vote down vote up
/**
 * Creates guice injector with servlet's jersey resource class and mocked acl store
 * @return
 */
@Override
protected Injector getInjector() {
    return Guice.createInjector(new JerseyServletModule() {
        @Override
        protected void configureServlets() {
            bind(GuiceContainer.class);
            // bind Jersey resources
            PackagesResourceConfig resourceConfig = new PackagesResourceConfig("io.joynr.accesscontrol.global");
            for (Class<?> resource : resourceConfig.getClasses()) {
                bind(resource);
            }

            bindConstant().annotatedWith(Names.named("joynr.messaging.domainaccesscontrollerchannelid"))
                          .to("gdac_channelid");
            bindConstant().annotatedWith(Names.named("joynr.messaging.discoverydirectoriesdomain")).to("io.joynr");

            bind(DomainAccessControlStore.class).toInstance(mockedStore);
            bind(GlobalDomainAccessStoreAdmin.class).toInstance(mockedStore);
            serve("/*").with(GuiceContainer.class);
            serve("/accesscontrol/*").with(AccessControlEditorServlet.class);

        }
    });
}
 
Example 17
Project: karyon   File: AdminResourcesFilter.java   Source Code and License 6 votes vote down vote up
@Override
protected ResourceConfig getDefaultResourceConfig(Map<String, Object> props,
                                                  WebConfig webConfig) throws ServletException {
    HashMap<String, Object> mergedProps = new HashMap<>(props);
    mergedProps.putAll(this.props);
    return new PackagesResourceConfig(mergedProps) {
        @Override
        public Set<Class<?>> getProviderClasses() {
            Set<Class<?>> providers = super.getProviderClasses();
            // remove conflicting provider if present
            providers.remove(FreemarkerTemplateProvider.class);
            providers.add(AdminFreemarkerTemplateProvider.class);
            providers.add(WebApplicationExceptionMapper.class);
            return providers;
        }
    };
}
 
Example 18
Project: karyon   File: PropertiesBasedResourceConfig.java   Source Code and License 6 votes vote down vote up
private synchronized void initIfRequired() {
    if (initialized) {
        return;
    }
    initialized = true;
    String pkgNamesStr = getConfigInstance().getString(PackagesResourceConfig.PROPERTY_PACKAGES, null);
    if (null == pkgNamesStr) {
        logger.warn("No property defined with name: " + PackagesResourceConfig.PROPERTY_PACKAGES +
                    ", this means that jersey can not find any of your resource/provider classes.");
    } else {
        String[] pkgNames = getElements(new String[]{pkgNamesStr}, ResourceConfig.COMMON_DELIMITERS);
        logger.info("Packages to scan by jersey {}", Arrays.toString(pkgNames));
        init(new PackageNamesScanner(pkgNames));
    }
    Map<String, Object> jerseyProperties = createPropertiesMap();
    setPropertiesAndFeatures(jerseyProperties);
}
 
Example 19
Project: jerseyoauth2   File: AppModule.java   Source Code and License 6 votes vote down vote up
@Override
	protected void configureServlets() {
    	bind(IUserService.class).to(DefaultPrincipalUserService.class);
    	bind(ITokenGenerator.class).to(MD5TokenGenerator.class);
    	bind(IClientIdGenerator.class).to(UUIDClientIdGenerator.class);
    	
    	bind(IConfiguration.class).to(Configuration.class);
    	bind(IRSConfiguration.class).to(Configuration.class);
    	bind(IAuthorizationFlow.class).to(TestAuthorizationFlow.class);
    	
    	bind(IClientService.class).to(DatabaseClientService.class);
    	bind(IAccessTokenStorageService.class).to(DatabaseAccessTokenStorage.class);
    	
    	serve("/oauth2/auth").with(AuthorizationServlet.class);
    	serve("/oauth2/allow").with(AllowServlet.class);
    	serve("/oauth2/accessToken").with(IssueAccessTokenServlet.class);
    	
       Map<String, String> params = new HashMap<String, String>();
       params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "com.burgmeier.jerseyoauth2.sample.resources");
//see http://java.net/jira/browse/JERSEY-630	            
       params.put(PackagesResourceConfig.FEATURE_DISABLE_WADL, "true");
       params.put(ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES, OAuth20FilterFactory.class.getName());
       // Route all requests for rest resources through GuiceContainer
       serve("/rest/*").with(GuiceContainer.class, params);		
	}
 
Example 20
Project: recipes-rss   File: BaseNettyServer.java   Source Code and License 6 votes vote down vote up
public void start() {
    this.host = ConfigurationManager.getConfigInstance().getString("netty.http.host", "not-found-in-configuration");
    this.port = ConfigurationManager.getConfigInstance().getInt("netty.http.port", Integer.MIN_VALUE);

    final PackagesResourceConfig rcf = new PackagesResourceConfig(ConfigurationManager.getConfigInstance().getString("jersey.resources.package","not-found-in-configuration"));

    nettyServer = NettyServer
            .builder()
            .host(host)
            .port(port)
            .addHandler(
                    "jerseyHandler",
                    ContainerFactory.createContainer(
                            NettyHandlerContainer.class, rcf))
                            .numBossThreads(NettyServer.cpus)
                            .numWorkerThreads(NettyServer.cpus * 4).build();
    try {
        karyonServer.start();
    } catch (Exception exc) {
        throw new RuntimeException("Cannot start karyon server.", exc);
    }
}
 
Example 21
Project: angulardemorestful   File: NgDemoApplicationSetup.java   Source Code and License 6 votes vote down vote up
@Override
protected Injector getInjector() {
    return Guice.createInjector(new ServletModule() {

        @Override
        protected void configureServlets() {

            super.configureServlets();

            // Configuring Jersey via Guice:
            ResourceConfig resourceConfig = new PackagesResourceConfig("ngdemo/web");
            for (Class<?> resource : resourceConfig.getClasses()) {
                bind(resource);
            }

            // hook Jackson into Jersey as the POJO <-> JSON mapper
            bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);

            serve("/web/*").with(GuiceContainer.class);

            filter("/web/*").through(ResponseCorsFilter.class);
        }
    }, new UserModule());
}
 
Example 22
Project: angulardemorestful   File: ServerProvider.java   Source Code and License 6 votes vote down vote up
public void createServer() throws IOException {
    System.out.println("Starting grizzly...");

    Injector injector = Guice.createInjector(new ServletModule() {
        @Override
        protected void configureServlets() {
            bind(UserService.class).to(UserServiceImpl.class);
            bind(UserRepository.class).to(UserMockRepositoryImpl.class);
            bind(DummyService.class).to(DummyServiceImpl.class);
            bind(DummyRepository.class).to(DummyMockRepositoryImpl.class);

            // hook Jackson into Jersey as the POJO <-> JSON mapper
            bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);
        }
    });

    ResourceConfig rc = new PackagesResourceConfig("ngdemo.web");
    IoCComponentProviderFactory ioc = new GuiceComponentProviderFactory(rc, injector);
    server = GrizzlyServerFactory.createHttpServer(BASE_URI + "web/", rc, ioc);

    System.out.println(String.format("Jersey app started with WADL available at "
            + "%srest/application.wadl\nTry out %sngdemo\nHit enter to stop it...",
            BASE_URI, BASE_URI));
}
 
Example 23
Project: elastic-job-cloud   File: RestfulServer.java   Source Code and License 5 votes vote down vote up
private ServletHolder getServletHolder(final String packages) {
    ServletHolder result = new ServletHolder(ServletContainer.class);
    result.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, Joiner.on(",").join(RestfulServer.class.getPackage().getName(), packages));
    result.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", PackagesResourceConfig.class.getName());
    result.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", Boolean.TRUE.toString());
    result.setInitParameter("resteasy.scan.providers", Boolean.TRUE.toString());
    result.setInitParameter("resteasy.use.builtin.providers", Boolean.FALSE.toString());
    return result;
}
 
Example 24
Project: conductor   File: JerseyModule.java   Source Code and License 5 votes vote down vote up
@Override
  protected void configureServlets() {
 

  	filter("/*").through(apiOriginFilter());
      
      Map<String, String> jerseyParams = new HashMap<>();	
jerseyParams.put("com.sun.jersey.config.feature.FilterForwardOn404", "true");
jerseyParams.put("com.sun.jersey.config.property.WebPageContentRegex", "/(((webjars|api-docs|swagger-ui/docs|manage)/.*)|(favicon\\.ico))");
jerseyParams.put(PackagesResourceConfig.PROPERTY_PACKAGES, "com.netflix.conductor.server.resources;io.swagger.jaxrs.json;io.swagger.jaxrs.listing");
jerseyParams.put(ResourceConfig.FEATURE_DISABLE_WADL, "false");
serve("/api/*").with(GuiceContainer.class, jerseyParams);
  }
 
Example 25
Project: OpenChatAlytics   File: ComputeRealtimeServerFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new {@link ComputeRealtimeServer}
 *
 * @param config
 *            The chatalytics config
 * @return A newly created {@link ComputeRealtimeServer}
 */
public ComputeRealtimeServer createComputeRealtimeServer() {
    Server server = new Server(config.computeConfig.rtComputePort);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
    jerseyServlet.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES,
                                   StatusResource.class.getPackage().toString());
    server.setHandler(context);
    ServerContainer wscontainer;
    try {
        wscontainer = WebSocketServerContainerInitializer.configureContext(context);
        wscontainer.addEndpoint(RealtimeResource.class);
    } catch (ServletException | DeploymentException e) {
        throw new RuntimeException("Can't instantiate websocket. Reason: " + e.getMessage());
    }

    return new ComputeRealtimeServer(server);
}
 
Example 26
Project: emodb   File: ResourceTestAuthUtil.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void addResourceFilterFactories(ResourceTestRule.Builder test, JerseyAuthConfiguration config) {
    // The ability to add properties is normally protected so we need to break in to update the resource filter
    // factories.
    Map<String, Object> properties;
    try {
        Field field = ResourceTestRule.Builder.class.getDeclaredField("properties");
        field.setAccessible(true);
        properties = (Map<String, Object>) field.get(test);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

    List resourceFilterFactories;

    // Add the new resource filter factories to any existing values
    Object existing = properties.get(PackagesResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES);
    if (existing == null) {
        resourceFilterFactories = config.getResourceFilterFactories();
    } else {
        resourceFilterFactories = Lists.newArrayList();
        if (existing.getClass().isArray()) {
            resourceFilterFactories.addAll(Arrays.asList((Object[]) existing));
        } else if (Iterable.class.isAssignableFrom(existing.getClass())) {
            Iterables.addAll(resourceFilterFactories, (Iterable) existing);
        } else {
            resourceFilterFactories.add(existing);
        }
        resourceFilterFactories.addAll(config.getResourceFilterFactories());
    }

    properties.put(PackagesResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES, resourceFilterFactories);
}
 
Example 27
Project: emrooz   File: EmroozServer.java   Source Code and License 5 votes vote down vote up
private static HttpServer getServer() throws IllegalArgumentException,
		NullPointerException, IOException {

	ResourceConfig rc = new PackagesResourceConfig(
			"fi.uef.envi.emrooz.rest");
	HttpServer server = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);

	return server;
}
 
Example 28
Project: lemo2   File: DMSResourceConfig.java   Source Code and License 5 votes vote down vote up
/**
 * Scan a package for {@link Path} annotations and map the types to their
 * paths, prefixed by the given base URL.
 * 
 * @param packagePath
 *            the package to scan
 * @param baseUrl
 *            URL prefix to be added to the annotations' values
 * @return every {@link Path}-annotated class in the package, mapped to the
 *         annotations value prefixed by the base URL
 */
private Map<String, Class<?>> getResourceClasses(final String packagePath,
		final String baseUrl) {
	final HashMap<String, Class<?>> resourceClasses = Maps.newHashMap();
	final Set<Class<?>> packageClasses =
			new PackagesResourceConfig(packagePath).getClasses();
	for (final Class<?> resource : packageClasses) {
		final Path annotation = resource.getAnnotation(Path.class);
		resourceClasses.put(
				baseUrl + CharMatcher.is('/').trimFrom(annotation.value()),
				resource);
	}
	return resourceClasses;
}
 
Example 29
Project: geocode   File: GuiceConfig.java   Source Code and License 5 votes vote down vote up
@Override
protected void configureServlets() {
  Map<String, String> params = new HashMap<String, String>(2);

  // Configure automatic JSON output for Jersey
  params.put(JSONConfiguration.FEATURE_POJO_MAPPING, "true");

  // Let Jersey look for root resources and Providers automatically
  params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "org.gbif.geocode");

  serve("/*").with(GuiceContainer.class, params);
}
 
Example 30
Project: Artemis   File: RestModule.java   Source Code and License 5 votes vote down vote up
@Override
protected void configureServlets() {
    bind(GuiceContainer.class);
    serve("/*").with(GuiceContainer.class);
    PackagesResourceConfig packagesResourceConfig = new PackagesResourceConfig(getClass().getPackage().getName());
    for (Class<?> resource : packagesResourceConfig.getClasses()) {
        bind(resource);
    }
}
 
Example 31
Project: gae-jersey-guice-jsf   File: GuiceRestModule.java   Source Code and License 5 votes vote down vote up
/**
 * bind JAX-RS annotated classes to be served through Guice. based on a recursive class scanning that starts from the package
 * returned by {@link #getRootPackage()}. override this if you wish to avoid the scanning and bind your classes explicitly
 */
protected void bindJaxrsResources()
{
	String rootPackage = getRootPackage();
	if (rootPackage == null)
		throw new NullPointerException(
				"to scan for JAX-RS annotated classes, either override getRootPackage() or bindJaxrsResources()");

	ResourceConfig rc = new PackagesResourceConfig(rootPackage);
	for (Class<?> resource : rc.getClasses())
		bind(resource);
}
 
Example 32
Project: Raigad   File: InjectedWebListener.java   Source Code and License 5 votes vote down vote up
@Override
protected void configureServlets() {
    Map<String, String> params = new HashMap<String, String>();
    params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "unbound");
    params.put("com.sun.jersey.config.property.packages", "com.netflix.raigad.resources");
    params.put(ServletContainer.PROPERTY_FILTER_CONTEXT_PATH, "/REST");
    serve("/REST/*").with(GuiceContainer.class, params);
}
 
Example 33
Project: stickypunch   File: JettyService.java   Source Code and License 5 votes vote down vote up
private static ServletHolder buildJerseyServlet() {
    Set<String> jerseyPackages = Sets.newHashSet();
    jerseyPackages.add(STICKYPUNCH_RESOURCE);
    jerseyPackages.add(INJECT_JERSEY_PACKAGE);
    ImmutableMap.Builder<String, Object> propsBuilder = ImmutableMap.builder();
    propsBuilder.put(PackagesResourceConfig.PROPERTY_PACKAGES, jerseyPackages.toArray(new String[jerseyPackages.size()]));
    PackagesResourceConfig jerseyResourceConfig = new PackagesResourceConfig(propsBuilder.build());
    return new ServletHolder(new ServletContainer(jerseyResourceConfig));
}
 
Example 34
Project: vertigo-labs   File: ConverterManagerDistributedTest.java   Source Code and License 5 votes vote down vote up
protected static HttpServer startServer() throws IOException {
	System.out.println("Starting grizzly...");
	final ResourceConfig rc = new PackagesResourceConfig("io.vertigo.dynamo.plugins.work.rest.master");
	rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, com.sun.jersey.api.container.filter.GZIPContentEncodingFilter.class.getName());
	rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, com.sun.jersey.api.container.filter.GZIPContentEncodingFilter.class.getName());
	return GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
}
 
Example 35
Project: MissingBot   File: Main.java   Source Code and License 5 votes vote down vote up
protected static HttpServer startServer(int port) throws IOException {
    System.out.println("Starting grizzly...");
    ResourceConfig rc = new PackagesResourceConfig("org/dbpedia/mappings/missingbot/rest/resources");
    rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, CorsResponseFilter.class.getName());
    rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, CharsetResponseFilter.class.getName());

    URI baseUri = getBaseURI(port);

    return GrizzlyServerFactory.createHttpServer(baseUri, rc);
}
 
Example 36
Project: preferanser   File: PreferanserServletContextListener.java   Source Code and License 5 votes vote down vote up
@Override protected void configureServlets() {
    bind(GuiceContainer.class);
    bind(JacksonJsonProvider.class).toProvider(JacksonJsonProviderProvider.class).in(Scopes.SINGLETON);
    List<String> responseFilters = Arrays.asList(
        EncodingJerseyResponseFilter.class.getName(),
        GZIPContentEncodingFilter.class.getName()
    );
    Map<String, String> params = ImmutableMap.of(
        WebComponent.RESOURCE_CONFIG_CLASS, JerseyResourceConfig.class.getName(),
        PackagesResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, Joiner.on(",").join(responseFilters)
    );
    serve("/Preferanser/*").with(GuiceContainer.class, params);
}
 
Example 37
Project: ruist   File: JerseyModule.java   Source Code and License 5 votes vote down vote up
@Override
protected void configure() {
    install(new ServletModule() {
        @Override
        protected void configureServlets() {
            serve("/*").with(GuiceContainer.class);
        }
    });
    final ResourceConfig rc = new PackagesResourceConfig(packageName);
    for (final Class<?> resource : rc.getClasses()) {
        bind(resource);
    }
}
 
Example 38
Project: agathon   File: ServletModule.java   Source Code and License 5 votes vote down vote up
@Override
protected void configureServlets() {
  serve("/*").with(GuiceContainer.class,
      ImmutableMap.of(
          JSONConfiguration.FEATURE_POJO_MAPPING, "true",
          PackagesResourceConfig.PROPERTY_PACKAGES,
              "com.brighttag.agathon.resources,com.fasterxml.jackson.jaxrs.json"));
}
 
Example 39
Project: ribbon   File: GetPostTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass 
public static void init() throws Exception {
    PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.niws.http", "com.netflix.niws.client");
    int port = (new Random()).nextInt(1000) + 4000;
    SERVICE_URI = "http://localhost:" + port + "/";
    try{
        server = HttpServerFactory.create(SERVICE_URI, resourceConfig);           
        server.start();
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    client = (RestClient) ClientFactory.getNamedClient("GetPostTest");
}
 
Example 40
Project: ribbon   File: PrimeConnectionsTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void setup(){
       PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.niws.client.http");
       SERVICE_URI = "http://localhost:" + port + "/";
       try{
           server = HttpServerFactory.create(SERVICE_URI, resourceConfig);           
           server.start();
       } catch (Exception e) {
           e.printStackTrace();
           fail(e.getMessage());
       }
   }