com.sun.jersey.api.core.ResourceConfig Java Examples

The following examples show how to use com.sun.jersey.api.core.ResourceConfig. 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: ConsoleEndPointServer.java    From db with GNU Affero General Public License v3.0 6 votes vote down vote up
@PostConstruct
private void init() {
    final Map<String, List<String>> portConfigData = ConfigUtil.getConfigData(Constants.APP_CONFIG_FILE, "/config/ports/port");
    final int port = Integer.parseInt(portConfigData.get(this.getClass().getName()).get(0));
    final Map<String, List<String>> packageConfigData = ConfigUtil.getConfigData(Constants.APP_CONFIG_FILE, "/config/resources/package");
    final List<String> packageList = packageConfigData.get(this.getClass().getName());

    try {
        final ResourceConfig resourceConfig = new PackagesResourceConfig(packageList.toArray(new String[packageList.size()]));
        final String serverAddress = "localhost";

        logger.debug("Attempting to start CLI listener at address {} with port {}", serverAddress, port);
        new Thread(new ConsoleEndPointServerSocket(port)).start();
        logger.info("CLI listener has started. CLI end point for database is ready."); // this is obviously non complete code
    } catch (ContainerException ex) {
        logger.error("CLI specified by {} couldn't be started because no root resource classes could be found in the listed packages ({}). Confirm if the packages have been refactored.", this.getClass(), packageList);
    }
}
 
Example #2
Source File: ServerProvider.java    From angulardemorestful with MIT 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 #3
Source File: NgDemoApplicationSetup.java    From angulardemorestful with MIT 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 #4
Source File: AppModule.java    From jerseyoauth2 with MIT 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 #5
Source File: PropertiesBasedResourceConfig.java    From karyon with Apache License 2.0 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 #6
Source File: AdminResourcesFilter.java    From karyon with Apache License 2.0 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 #7
Source File: RestModule.java    From AisAbnormal with GNU Lesser General Public License v3.0 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 #8
Source File: AppServletModule.java    From appstart with Apache License 2.0 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 #9
Source File: RestApplication.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 * @param manager
 */
public RestApplication( Manager manager ) {
	super();

	this.applicationResource = new ApplicationResource( manager );
	this.managementResource = new ManagementResource( manager );
	this.debugResource = new DebugResource( manager );
	this.targetResource = new TargetResource( manager );
	this.preferencesResource = new PreferencesResource( manager );
	this.schedulerResource = new SchedulerResource( manager );
	this.authenticationResource = new AuthenticationResource( manager );
	this.historyResource = new HistoryResource( manager );

	getFeatures().put( "com.sun.jersey.api.json.POJOMappingFeature", Boolean.TRUE );
	getFeatures().put( ResourceConfig.FEATURE_DISABLE_WADL, Boolean.TRUE );
}
 
Example #10
Source File: DaggerComponentProviderFactoryTest.java    From dagger-servlet with Apache License 2.0 6 votes vote down vote up
@Test
public void testClassesFromProvidesMethodsWithModuleInjectsAndNoInjectsConstructorAreRegistered() {
    ResourceConfig config = new DefaultResourceConfig();
    ObjectGraph objectGraph = ObjectGraph.create(SomeInjectableProvidesModule.class,
            new SomeOtherInjectableProvidesModule());
    IoCComponentProviderFactory factory = new DaggerComponentProviderFactory(config, objectGraph,
            new Object[]{SomeInjectableProvidesModule.class, new SomeOtherInjectableProvidesModule()});

    assertTrue(config.getClasses().contains(SomeProvidesInjectableResource.class));
    assertTrue(config.getClasses().contains(SomeOtherProvidesInjectableResource.class));
    assertTrue(config.getClasses().contains(SomeProvidesInjectableProvider.class));

    SomeProvidesInjectableResource someResource = (SomeProvidesInjectableResource) factory.
            getComponentProvider(SomeProvidesInjectableResource.class).getInstance();
    SomeOtherProvidesInjectableResource someOtherResource = (SomeOtherProvidesInjectableResource) factory
            .getComponentProvider(SomeOtherProvidesInjectableResource.class).getInstance();
    SomeProvidesInjectableProvider someProvider = (SomeProvidesInjectableProvider) factory
            .getComponentProvider(SomeProvidesInjectableProvider.class).getInstance();

    assertNotNull(someResource);
    assertNotNull(someOtherResource);
    assertNotNull(someProvider);
}
 
Example #11
Source File: AggregatorApplication.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
protected HttpServer createHttpServer() throws Exception {
  ResourceConfig resourceConfig = new PackagesResourceConfig("org.apache.hadoop.metrics2.host.aggregator");
  HashMap<String, Object> params = new HashMap();
  params.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
  resourceConfig.setPropertiesAndFeatures(params);
  HttpServer server = HttpServerFactory.create(getURI(), resourceConfig);

  if (webServerProtocol.equalsIgnoreCase("https")) {
    HttpsServer httpsServer = (HttpsServer) server;
    SslContextFactory sslContextFactory = new SslContextFactory();
    String keyStorePath = configuration.get("ssl.server.keystore.location");
    String keyStorePassword = configuration.get("ssl.server.keystore.password");
    String keyManagerPassword = configuration.get("ssl.server.keystore.keypassword");
    String trustStorePath = configuration.get("ssl.server.truststore.location");
    String trustStorePassword = configuration.get("ssl.server.truststore.password");

    sslContextFactory.setKeyStorePath(keyStorePath);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    sslContextFactory.setTrustStorePath(trustStorePath);
    sslContextFactory.setTrustStorePassword(trustStorePassword);

    sslContextFactory.start();
    SSLContext sslContext = sslContextFactory.getSslContext();
    sslContextFactory.stop();
    HttpsConfigurator httpsConfigurator = new HttpsConfigurator(sslContext);
    httpsServer.setHttpsConfigurator(httpsConfigurator);
    server = httpsServer;
  }
  return server;
}
 
Example #12
Source File: WebApp.java    From hadoop with Apache License 2.0 6 votes vote down vote up
protected void configureWebAppServlets() {
  // Add in the web services filters/serves if app has them.
  // Using Jersey/guice integration module. If user has web services
  // they must have also bound a default one in their webapp code.
  if (this.wsName != null) {
    // There seems to be an issue with the guice/jersey integration
    // where we have to list the stuff we don't want it to serve
    // through the guicecontainer. In this case its everything except
    // the the web services api prefix. We can't just change the filter
    // from /* below - that doesn't work.
    String regex = "(?!/" + this.wsName + ")";
    serveRegex(regex).with(DefaultWrapperServlet.class);

    Map<String, String> params = new HashMap<String, String>();
    params.put(ResourceConfig.FEATURE_IMPLICIT_VIEWABLES, "true");
    params.put(ServletContainer.FEATURE_FILTER_FORWARD_ON_404, "true");
    params.put(FeaturesAndProperties.FEATURE_XMLROOTELEMENT_PROCESSING, "true");
    params.put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, GZIPContentEncodingFilter.class.getName());
    params.put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, GZIPContentEncodingFilter.class.getName());
    filter("/*").through(getWebAppFilterClass(), params);
  }
}
 
Example #13
Source File: WebApp.java    From big-c with Apache License 2.0 6 votes vote down vote up
protected void configureWebAppServlets() {
  // Add in the web services filters/serves if app has them.
  // Using Jersey/guice integration module. If user has web services
  // they must have also bound a default one in their webapp code.
  if (this.wsName != null) {
    // There seems to be an issue with the guice/jersey integration
    // where we have to list the stuff we don't want it to serve
    // through the guicecontainer. In this case its everything except
    // the the web services api prefix. We can't just change the filter
    // from /* below - that doesn't work.
    String regex = "(?!/" + this.wsName + ")";
    serveRegex(regex).with(DefaultWrapperServlet.class);

    Map<String, String> params = new HashMap<String, String>();
    params.put(ResourceConfig.FEATURE_IMPLICIT_VIEWABLES, "true");
    params.put(ServletContainer.FEATURE_FILTER_FORWARD_ON_404, "true");
    params.put(FeaturesAndProperties.FEATURE_XMLROOTELEMENT_PROCESSING, "true");
    params.put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, GZIPContentEncodingFilter.class.getName());
    params.put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, GZIPContentEncodingFilter.class.getName());
    filter("/*").through(getWebAppFilterClass(), params);
  }
}
 
Example #14
Source File: Main.java    From wingtips with Apache License 2.0 6 votes vote down vote up
private static ServletContextHandler generateServletContextHandler() throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setContextPath("/");

    ResourceConfig rc = new WebAppResourceConfig(Collections.<String, Object>emptyMap(), contextHandler.getServletContext());
    rc.getSingletons().add(new SampleResource());
    ServletContainer jerseyServletContainer = new ServletContainer(rc);
    contextHandler.addServlet(SampleResource.SampleAsyncServlet.class, SampleResource.ASYNC_PATH);
    contextHandler.addServlet(SampleResource.SampleBlockingForwardServlet.class, SampleResource.BLOCKING_FORWARD_PATH);
    contextHandler.addServlet(SampleResource.SampleAsyncForwardServlet.class, SampleResource.ASYNC_FORWARD_PATH);
    contextHandler.addServlet(SampleResource.SampleAsyncTimeoutServlet.class, SampleResource.ASYNC_TIMEOUT_PATH);
    contextHandler.addServlet(SampleResource.SampleAsyncErrorServlet.class, SampleResource.ASYNC_ERROR_PATH);
    contextHandler.addServlet(new ServletHolder(jerseyServletContainer), "/*");
    contextHandler.addFilter(RequestTracingFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    return contextHandler;
}
 
Example #15
Source File: DaggerComponentProviderFactory.java    From dagger-servlet with Apache License 2.0 5 votes vote down vote up
public DaggerComponentProviderFactory(ResourceConfig config, ObjectGraph objectGraph, Object[] modules) {
    this.objectGraph = objectGraph;

    for (Object module : modules) {
        Class<?> moduleClass = getModuleClass(module);
        Module annotation = moduleClass.getAnnotation(Module.class);
        register(config, moduleClass, annotation);
    }
}
 
Example #16
Source File: JerseyContainerProvider.java    From recipes-rss with Apache License 2.0 5 votes vote down vote up
public NettyHandlerContainer createContainer(Class<NettyHandlerContainer> clazz, ResourceConfig config,WebApplication webApp)
           throws ContainerException {
	if (clazz != NettyHandlerContainer.class) {
		return null;
	}
	return new NettyHandlerContainer(webApp, config);
}
 
Example #17
Source File: AppModule.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
@Override
    protected void configureServlets() {
    	bind(IAccessTokenStorageService.class).to(CachingAccessTokenStorage.class);
    	bind(IClientService.class).to(DatabaseClientService.class);
    	bind(IConfiguration.class).to(Configuration.class);
    	bind(IRSConfiguration.class).to(Configuration.class);
    	bind(IAuthorizationFlow.class).to(TestAuthorizationFlow.class);
    	
    	bind(IUserService.class).to(DefaultPrincipalUserService.class);
    	bind(ITokenGenerator.class).to(MD5TokenGenerator.class);
    	bind(IClientIdGenerator.class).to(UUIDClientIdGenerator.class);
    	
    	bind(EntityManagerFactory.class).toProvider(new PersistenceProvider());
    	bind(CacheManager.class).toProvider(new DefaultCacheManagerProvider());
    	
    	serve("/oauth2/auth").with(AuthorizationServlet.class);
    	serve("/oauth2/accessToken").with(IssueAccessTokenServlet.class);
    	
    	filter("/oauth2/*").through(StrictSecurityFilter.class);
    	
       Map<String, String> params = new HashMap<String, String>();
       params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "com.github.hburgmeier.jerseyoauth2.testsuite.resource;" +
       		"com.github.hburgmeier.jerseyoauth2.testsuite.base.resource");
//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 #18
Source File: JerseyModule.java    From conductor with Apache License 2.0 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 #19
Source File: NettyContainerProvider.java    From karyon with Apache License 2.0 5 votes vote down vote up
@Override
public NettyContainer createContainer(Class<NettyContainer> type, ResourceConfig resourceConfig,
                                      WebApplication application) throws ContainerException {
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(application);
    if (!type.equals(NettyContainer.class)) {
        logger.error(
                "Netty container provider can only create container of type {}. Invoked to create container of type {}",
                NettyContainer.class.getName(), type.getName());
    }
    return new NettyContainer(application);
}
 
Example #20
Source File: Main.java    From backstopper 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 WebAppResourceConfig(Collections.<String, Object>emptyMap(), contextHandler.getServletContext());
    rc.getSingletons().add(Jersey1SampleConfigHelper.generateJerseyApiExceptionHandler());
    rc.getSingletons().add(Jersey1SampleConfigHelper.generateSampleResource());
    ServletContainer jerseyServletContainer = new ServletContainer(rc);
    contextHandler.addServlet(new ServletHolder(jerseyServletContainer), "/*");
    return contextHandler;
}
 
Example #21
Source File: StartServer.java    From EVCache with Apache License 2.0 5 votes vote down vote up
@Override
    protected ServletModule getServletModule() {
        return new JerseyServletModule() {
            @Override
            protected void configureServlets() {
                logger.info("########## CONFIGURING SERVLETS ##########");

                // initialize NFFilter
                Map<String, String> initParams = new HashMap<String,String>();
//                initParams.put(ServletContainer.JSP_TEMPLATES_BASE_PATH, "/WEB-INF/jsp");
//                initParams.put(ServletContainer.FEATURE_FILTER_FORWARD_ON_404, "true");
//                initParams.put("requestId.accept", "true");
//                initParams.put("requestId.require", "true");
                initParams.put(ResourceConfig.FEATURE_DISABLE_WADL, "true");
                initParams.put(PackagesResourceConfig.PROPERTY_PACKAGES, "com.netflix.evcache.service.resources");
                filter("/*").through(NFFilter.class, initParams);
                filter("/healthcheck", "/status").through(NFFilter.class, initParams);
                serve("/Status", "/status").with(BaseStatusPage.class);
                serve("/healthcheck", "/Healthcheck").with(BaseHealthCheckServlet.class);
                serve("/*").with(GuiceContainer.class, initParams);
                bind(EVCacheRESTService.class).asEagerSingleton();
                binder().bind(GuiceContainer.class).asEagerSingleton();
                
                install(new EVCacheServiceModule());
            }
        };
    }
 
Example #22
Source File: HmacAuthProviderTest.java    From jersey-hmac-auth with Apache License 2.0 5 votes vote down vote up
@Override
protected AppDescriptor configure() {
    this.requestConfiguration = RequestConfiguration.builder().withApiKeyQueryParamName("passkey")
            .withSignatureHttpHeader("duck-duck-signature-header")
            .withTimestampHttpHeader("duck-duck-timestamp-header")
            .withVersionHttpHeader("duck-duck-version-header")
            .build();
    final Authenticator<String> authenticator = new Authenticator<String>() {
        @Override
        public String getApiKeyName() {
            return DEFAULT_API_KEY_PARAM;
        }

        @Override
        public String authenticate(Credentials credentials) {
            if (GOOD_API_KEY.equals(credentials.getApiKey())) {
                return GOOD_API_KEY;
            }
            if (INTERNAL_ERROR.equals(credentials.getApiKey())) {
                throw new IllegalStateException("An internal error occurred");
            }
            return null;
        }
    };

    ResourceConfig config = new ScanningResourceConfig();
    config.getSingletons().add(new HmacAuthProvider<String>(new DefaultRequestHandler<String>(authenticator, requestConfiguration)));
    config.getSingletons().add(new AuthResource());
    return new LowLevelAppDescriptor.Builder(config).build();
}
 
Example #23
Source File: DaggerComponentProviderFactoryTest.java    From dagger-servlet with Apache License 2.0 5 votes vote down vote up
@Test
public void testProviderClassesAreRegistered() {
    ResourceConfig config = new DefaultResourceConfig();
    ObjectGraph objectGraph = ObjectGraph.create(SomeModule.class, new SomeOtherModule());
    new DaggerComponentProviderFactory(config, objectGraph, new Object[]{SomeModule.class, new SomeOtherModule()});

    assertTrue(config.getClasses().contains(SomeProvider.class));
}
 
Example #24
Source File: DaggerComponentProviderFactoryTest.java    From dagger-servlet with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassesFromProvidesMethodsWithoutModuleInjectsAreNotRegistered() {
    ResourceConfig config = new DefaultResourceConfig();
    ObjectGraph objectGraph = ObjectGraph.create(SomeProvidesModule.class, new SomeOtherProvidesModule());
    new DaggerComponentProviderFactory(config, objectGraph,
            new Object[]{SomeProvidesModule.class, new SomeOtherProvidesModule()});

    assertFalse(config.getClasses().contains(SomeResource.class));
    assertFalse(config.getClasses().contains(SomeOtherResource.class));
    assertFalse(config.getClasses().contains(SomeProvider.class));
}
 
Example #25
Source File: DaggerComponentProviderFactoryTest.java    From dagger-servlet with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassesFromModuleInstancesAndModuleClassesAreRegistered() {
    ResourceConfig config = new DefaultResourceConfig();
    ObjectGraph objectGraph = ObjectGraph.create(SomeModule.class, new SomeOtherModule());
    new DaggerComponentProviderFactory(config, objectGraph, new Object[]{SomeModule.class, new SomeOtherModule()});

    assertTrue(config.getClasses().contains(SomeResource.class));
    assertTrue(config.getClasses().contains(SomeOtherResource.class));
}
 
Example #26
Source File: DaggerComponentProviderFactory.java    From dagger-servlet with Apache License 2.0 5 votes vote down vote up
private void registerClass(ResourceConfig config, Class<?> clazz) {
    if (!daggerInjectableClasses.contains(clazz) && !daggerProvidedClasses.contains(clazz)) {
        if (ResourceConfig.isProviderClass(clazz)) {
            LOGGER.info("Registering {} as a provider class", clazz.getName());
            config.getClasses().add(clazz);
        } else if (ResourceConfig.isRootResourceClass(clazz)) {
            LOGGER.info("Registering {} as a root resource class", clazz.getName());
            config.getClasses().add(clazz);
        }
    }
}
 
Example #27
Source File: DaggerComponentProviderFactory.java    From dagger-servlet with Apache License 2.0 5 votes vote down vote up
/**
 * Does not actually register the provides return types with Jersey. They are only added to the
 * daggerProvidedClasses set. Only classes in the 'injects' field of a module can be created via the
 * ObjectGraph#get() method.
 */
private void registerProvides(ResourceConfig config, Class<?> moduleClass) {
    for (Method method : moduleClass.getDeclaredMethods()) {
        Provides annotation = method.getAnnotation(Provides.class);
        if (annotation != null) {
            Class<?> returnType = method.getReturnType();
            daggerProvidedClasses.add(returnType);
        }
    }
}
 
Example #28
Source File: JerseySupport.java    From exhibitor with Apache License 2.0 4 votes vote down vote up
public static void      addSingletons(ResourceConfig config, UIContext context)
{
    config.getSingletons().addAll(getSingletons(context));
}
 
Example #29
Source File: RestServer.java    From ecs-sync with Apache License 2.0 4 votes vote down vote up
protected ResourceConfig createResourceConfig() {
    return new PackagesResourceConfig(RestServer.class.getPackage().getName());
}
 
Example #30
Source File: ResourceTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
protected static ResourceTestRule setupResourceTestRule(List<Object> resourceList, List<Object> filters,
                                                        AuthIdentityManager<ApiKey> authIdentityManager,
                                                        PermissionManager permissionManager) {
    ResourceTestRule.Builder resourceTestRuleBuilder = ResourceTestRule.builder();

    for (Object resource : resourceList) {
        resourceTestRuleBuilder.addResource(resource);
    }

    List<ResourceFilterFactory> resourceFilterFactories = Lists.newArrayList();
    List<ContainerRequestFilter> containerRequestFilters = Lists.newArrayList();
    List<ContainerResponseFilter> containerResponseFilters = Lists.newArrayList();

    for (Object filter : filters) {
        if (filter instanceof ResourceFilterFactory) {
            resourceFilterFactories.add((ResourceFilterFactory) filter);
        }
        if (filter instanceof ContainerRequestFilter) {
            containerRequestFilters.add((ContainerRequestFilter) filter);
        }
        if (filter instanceof ContainerResponseFilter) {
            containerResponseFilters.add((ContainerResponseFilter) filter);
        }
    }

    resourceTestRuleBuilder.addProperty(ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES, resourceFilterFactories);
    resourceTestRuleBuilder.addProperty(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, containerRequestFilters);
    resourceTestRuleBuilder.addProperty(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, containerResponseFilters);

    // Jersey tests don't inject Context parameters, so create an injector to provide a mock instance.
    resourceTestRuleBuilder.addProvider(new DatabusJerseyTest.ContextInjectableProvider<>(HttpServletRequest.class, mock(HttpServletRequest.class)));

    ResourceTestAuthUtil.setUpResources(resourceTestRuleBuilder, SecurityManagerBuilder.create()
            .withAuthIdentityReader(authIdentityManager)
            .withPermissionReader(permissionManager)
            .build());

    for (Object mapper : ExceptionMappers.getMappers()) {
        resourceTestRuleBuilder.addProvider(mapper);
    }
    for (Class mapperType : ExceptionMappers.getMapperTypes()) {
        resourceTestRuleBuilder.addProvider(mapperType);
    }

    ResourceTestRule resourceTestRule = resourceTestRuleBuilder.build();

    // Write Date objects using ISO8601 strings instead of numeric milliseconds-since-1970.
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    resourceTestRule.getObjectMapper().setDateFormat(fmt);

    return resourceTestRule;
}