private Injector configureGuice(T configuration, Environment environment) throws Exception { // setup our core modules... appModules.add(new MetricRegistryModule(environment.metrics())); appModules.add(new ServletModule()); // ...and add the app's modules appModules.addAll(addModules(configuration, environment)); final Injector injector = Guice.createInjector(ImmutableList.copyOf(this.appModules)); // Taken from https://github.com/Squarespace/jersey2-guice/wiki#complex-example. HK2 is no fun. JerseyGuiceUtils.install((name, parent) -> { if (!name.startsWith("__HK2_Generated_")) { return null; } return injector.createChildInjector(Lists.newArrayList(new JerseyGuiceModule(name))) .getInstance(ServiceLocator.class); }); injector.injectMembers(this); registerWithInjector(environment, injector); return injector; }
@Override public Module getChildServletModule() { return new ServletModule() { @Override protected void configureServlets() { filter(PATH).through(filter); serve(PATH).with(new HttpServlet() { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { mockServlet.service(req, resp); resp.setStatus(HttpServletResponse.SC_OK); } }); } }; }
@Override public Module getChildServletModule() { return new ServletModule() { @Override protected void configureServlets() { filter(PATH).through(filter); serve(PATH).with(new HttpServlet() { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { getMockServlet().service(req, resp); resp.setStatus(HttpServletResponse.SC_OK); } }); } }; }
private ServletModule getSwagger() { String resourceBasePath = ServletContextListner.class.getResource("/swagger-ui").toExternalForm(); DefaultServlet ds = new DefaultServlet(); ServletModule sm = new ServletModule() { @Override protected void configureServlets() { Map<String, String> params = new HashMap<>(); params.put("resourceBase", resourceBasePath); params.put("redirectWelcome", "true"); serve("/*").with(ds, params); } }; return sm; }
public ServletModule getServletModule(final Injector injector) { return new ServletModule() { @Override protected void configureServlets() { // We add servlets here to override the DefaultServlet automatic registered by WebAppContext // in path "/" with our WaveClientServlet. Any other way to do this? // Related question (unanswered 08-Apr-2011) // http://web.archiveorange.com/archive/v/d0LdlXf1kN0OXyPNyQZp for (Pair<String, ServletHolder> servlet : servletRegistry) { String url = servlet.getFirst(); @SuppressWarnings("unchecked") Class<HttpServlet> clazz = (Class<HttpServlet>) servlet.getSecond().getHeldClass(); Map<String,String> params = servlet.getSecond().getInitParameters(); serve(url).with(clazz,params); bind(clazz).in(Singleton.class); } for (Pair<String, Class<? extends Filter>> filter : filterRegistry) { filter(filter.first).through(filter.second); } } }; }
private void doConfigure() { install(new ResteasyModule()); install(new ServletModule() { @Override protected void configureServlets() { log.debug("Mount point: {}", MOUNT_POINT); bind(SiestaServlet.class); serve(MOUNT_POINT + "/*").with(SiestaServlet.class, ImmutableMap.of( "resteasy.servlet.mapping.prefix", MOUNT_POINT )); filter(MOUNT_POINT + "/*").through(SecurityFilter.class); } }); install(new FilterChainModule() { @Override protected void configure() { addFilterChain(MOUNT_POINT + "/**", NexusAuthenticationFilter.NAME, AnonymousFilter.NAME); } }); }
@Override protected void configure() { install(new ResteasyModule()); install(new ValidationModule()); install(new ServletModule() { @Override protected void configureServlets() { serve(MOUNT_POINT + "/*").with(SiestaServlet.class, ImmutableMap.of( "resteasy.servlet.mapping.prefix", MOUNT_POINT )); } }); // register exception mappers required by tests register(ValidationErrorsExceptionMapper.class); register(WebappExceptionMapper.class); // register test resources register(EchoResource.class); register(ErrorsResource.class); register(UserResource.class); register(ValidationErrorsResource.class); }
@Override protected void configure() { final Binder lowPriorityBinder = binder().withSource(Sources.prioritize(Integer.MIN_VALUE)); lowPriorityBinder.install(new ServletModule() { @Override protected void configureServlets() { serve("/*").with(WebResourceServlet.class); filter("/*").through(SecurityFilter.class); } }); lowPriorityBinder.install(new FilterChainModule() { @Override protected void configure() { addFilterChain("/**", AnonymousFilter.NAME); } }); }
@Override protected void configure() { bind(filterKey(SessionAuthenticationFilter.NAME)).to(SessionAuthenticationFilter.class); install(new ServletModule() { @Override protected void configureServlets() { serve(SESSION_MP).with(SessionServlet.class); filter(SESSION_MP).through(SecurityFilter.class); filter(SESSION_MP).through(CookieFilter.class); } }); install(new FilterChainModule() { @Override protected void configure() { addFilterChain(SESSION_MP, SessionAuthenticationFilter.NAME); } }); }
protected static void setupWithModule(Module baseModule) { Log.debug("Setting up Jersey"); application = new TestApplication(); Log.trace("+- application=[{}]", application); Log.debug("Bootstrapping Jersey2-Guice bridge"); ServiceLocator locator = BootstrapUtils.newServiceLocator(); Log.trace("+- locator=[{}]", locator); final List<Module> modules = Arrays.asList(new ServletModule(), baseModule); final Injector injector = BootstrapUtils.newInjector(locator, modules); Log.trace("+- injector=[{}]", injector); BootstrapUtils.install(locator); Log.trace("+- done: locator installed"); }
private void scanGuiceModules(Set<Class<?>> classes) throws IOException { try { Class<?> sysModuleBaseClass = Module.class; Class<?> httpModuleBaseClass = ServletModule.class; Class<?> sshModuleBaseClass = Class.forName("com.google.gerrit.sshd.CommandModule"); sshModuleClass = null; httpModuleClass = null; sysModuleClass = null; for (Class<?> clazz : classes) { if (clazz.isLocalClass()) { continue; } if (sshModuleBaseClass.isAssignableFrom(clazz)) { sshModuleClass = getUniqueGuiceModule(sshModuleBaseClass, sshModuleClass, clazz); } else if (httpModuleBaseClass.isAssignableFrom(clazz)) { httpModuleClass = getUniqueGuiceModule(httpModuleBaseClass, httpModuleClass, clazz); } else if (sysModuleBaseClass.isAssignableFrom(clazz)) { sysModuleClass = getUniqueGuiceModule(sysModuleBaseClass, sysModuleClass, clazz); } } } catch (ClassNotFoundException e) { throw new IOException("Cannot find base Gerrit classes for Guice Plugin Modules", e); } }
@Override protected Injector getInjector() { ServletModule servletModule=new ServletModule(){ @Override protected void configureServlets() { filter("/*").through(FunrouteFilter.class); } }; Module[] all=new Module[otherModules.length+2]; all[0]=cfg; all[1]=servletModule; for(int i=0;i<otherModules.length;i++){ all[i+2]=otherModules[i]; } return Guice.createInjector(all); }
@Override protected Injector getInjector() { injector = Guice.createInjector(new ServletModule() { @Override protected void configureServlets() { String persistenceUnitName = PersistenceInitializeListener.getPersistenceUnitName(); install(new JpaPersistModule(persistenceUnitName)); filter("/*").through(PersistFilter.class); requestStaticInjection(EntityOperatorProvider.class); bind(GitOperation.class).in(Singleton.class); bind(GitApi.class).in(Singleton.class); ClassFinder.findClasses("gw.service").forEach(clazz -> bind(clazz).in(Singleton.class)); } }); return injector; }
private Injector createInjector() { Injector injector; try { final DataSource dataSource = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/postgresql"); injector = Guice.createInjector( new DatabaseModule(dataSource), new ServletModule() { @Override protected void configureServlets() { // Hibernate thread-scoped sessions filter("/*").through(DatabaseSessionFilter.class); // RequestFactory servlet mapping install(new InjectableRequestFactoryModule()); serve("/gwtRequest").with(InjectableRequestFactoryServlet.class); // RPC servlet mappings go here // example: //serve("/sheets/myurl").with(MyServiceImpl.class); } }); } catch (NamingException e) { throw new RuntimeException(e); } return injector; }
@Override protected Injector getInjector() { return Guice.createInjector(new ServletModule() { protected void configureServlets() { install(new JpaPersistModule("IneFormShowCaseWithEjbs")); filter("/*").through(PersistFilter.class); }; } , new IneFrameBaseServletModule("ineformshowcasewithejbs", ShowcaseDispatchServlet.class) // , new IneCoreBaseServletModule("ineformshowcasewithejbs", ShowcaseDispatchServlet.class) , new UploadServletModule() , new TestServletModule() , new IneFrameBaseActionHanlderModule() , new IneFrameBaseModule() , new IneFormActionHanlderModule() , new IneFormDispatcherGuiceModule() // , new IneFrameModuleGuiceModule() , new IneModuleGuiceModule(false) ); }
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; }
@Test public void checkJersey() throws IOException { JerseyGuiceUtils.install(new ServiceLocatorGenerator() { @Override public ServiceLocator create(String name, ServiceLocator parent) { if (!name.startsWith("__HK2_")) { return null; } List<Module> modules = new ArrayList<>(); modules.add(new JerseyGuiceModule(name)); modules.add(new ServletModule()); modules.add(jerseyModule); modules.add(customModule); return Guice.createInjector(modules) .getInstance(ServiceLocator.class); } }); try (HttpServer server = HttpServerUtils.newHttpServer(RESOURCES)) { check(); } }
@Override protected void configure() { install(new ServletModule() { @Override protected void configureServlets() { serve("/private/healthcheck/live").with(Key.get(AbstractDaemonCheckReportServlet.class, Live.class)); serve("/private/healthcheck").with(Key.get(AbstractDaemonCheckReportServlet.class, Background.class)); } }); bind(RuistDependencyManager.class).annotatedWith(Live.class).to(RuistDependencyManager.class).asEagerSingleton(); bind(RuistDependencyManager.class).annotatedWith(Background.class).to(RuistDependencyManager.class).asEagerSingleton(); final LinkedBindingBuilder<Dependency> builder = Multibinder.newSetBinder(binder(), Dependency.class).addBinding(); for (final Class<? extends Dependency> dep : deps) { builder.to(dep); } }
@Override protected void configure() { bind(RefAppResource.class); // Install servlet module setting a the Jersey/Guice integration. install(new ServletModule() { @Override protected void configureServlets() { filter("/*").through(GuiceContainer.class, ImmutableMap.of(JSONConfiguration.FEATURE_POJO_MAPPING, "true", ResourceConfig.FEATURE_TRACE, "true", ResourceConfig.FEATURE_TRACE_PER_REQUEST, "true", ServletContainer.FEATURE_FILTER_FORWARD_ON_404, "true")); } }); }
public ServletModule getServletModule() { return new ServletModule() { @Override protected void configureServlets() { // We add servlets here to override the DefaultServlet automatic registered by WebAppContext // in path "/" with our WaveClientServlet. Any other way to do this? // Related question (unanswered 08-Apr-2011) // http://web.archiveorange.com/archive/v/d0LdlXf1kN0OXyPNyQZp for (Pair<String, ServletHolder> servlet : servletRegistry) { String url = servlet.getFirst(); @SuppressWarnings("unchecked") Class<HttpServlet> clazz = (Class<HttpServlet>) servlet.getSecond().getHeldClass(); Map<String,String> params = servlet.getSecond().getInitParameters(); serve(url).with(clazz,params); bind(clazz).in(Singleton.class); } for (Pair<String, Class<? extends Filter>> filter : filterRegistry) { filter(filter.first).through(filter.second); } } }; }
@Override protected Injector getInjector() { return Guice.createInjector(new ServletModule() { public void configureServlets() { serve("/cacerts").with(CaDistributionServlet.class); serve("/simpleenroll").with(EnrollmentServlet.class); serve("/simplereenroll").with(EnrollmentServlet.class); serve("/serverkeygen").with(KeyGenerationServlet.class); serve("/csrattrs").with(CsrAttributesServlet.class); bind(CaDistributionServlet.class).asEagerSingleton(); bind(EnrollmentServlet.class).asEagerSingleton(); bind(KeyGenerationServlet.class).asEagerSingleton(); bind(CsrAttributesServlet.class).asEagerSingleton(); bind(EstMediator.class).to(SampleEstMediator.class); bind(new TypeLiteral<EntityEncoder<X509Certificate>>(){}).to(BouncyCastleSignedDataEncoder.class); bind(new TypeLiteral<EntityEncoder<String>>(){}).to(BouncyCastleCsrAttributeEncoder.class); bind(new TypeLiteral<EntityDecoder<CertificationRequest>>(){}).to(BouncyCastleCertificateRequestDecoder.class); } }); }
private static Injector getInjector(final Module module) { return Guice.createInjector(new AbstractModule() { @Override protected void configure() { binder().requireExplicitBindings(); install(new ResourceMethodWrappedDispatchModule()); install(new ServletModule() { @Override protected void configureServlets() { serve("/*").with(GuiceContainer.class); } }); install(new JerseyServletModule()); bind(GuiceFilter.class); bind(GuiceContainer.class); bind(FooResource.class); install(module); } }); }
@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 ); } } ); }
@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()); }
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)); }
@Override protected Injector getInjector() { Injector injector = Guice.createInjector( Stage.PRODUCTION, new JerseyGuiceModule("__HK2_Generated_0"), new ServletModule(), new AppModule() ); JerseyGuiceUtils.install(injector); return injector; }
@Test public void testJobCountersForKilledJob() throws Exception { WebResource r = resource(); appContext = new MockHistoryContext(0, 1, 1, 1, true); injector = Guice.createInjector(new ServletModule() { @Override protected void configureServlets() { webApp = mock(HsWebApp.class); when(webApp.name()).thenReturn("hsmockwebapp"); bind(JAXBContextResolver.class); bind(HsWebServices.class); bind(GenericExceptionHandler.class); bind(WebApp.class).toInstance(webApp); bind(AppContext.class).toInstance(appContext); bind(HistoryContext.class).toInstance(appContext); bind(Configuration.class).toInstance(conf); serve("/*").with(GuiceContainer.class); } }); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); ClientResponse response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("counters/") .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); JSONObject json = response.getEntity(JSONObject.class); assertEquals("incorrect number of elements", 1, json.length()); JSONObject info = json.getJSONObject("jobCounters"); WebServicesTestUtils.checkStringMatch("id", MRApps.toString(id), info.getString("id")); assertTrue("Job shouldn't contain any counters", info.length() == 1); } }
protected void configure() { install(MultibindingsScanner.asModule()); install(new ServletModule()); requireBinding(Key.get(new TypeLiteral<Set<ConnectorFactory>>() {})); bind(ServletHolder.class) .toProvider(ServletHolderProvider.class) .asEagerSingleton(); bind(Handler.class) .toProvider(ServletContextHandlerProvider.class) .asEagerSingleton(); bind(Server.class) .toProvider(JettyServerProvider.class) .asEagerSingleton(); bind(ResourceConfig.class) .toProvider(resourceConfigProvider()) .asEagerSingleton(); bind(HttpConfiguration.class) .annotatedWith(BaseConfiguration.class) .toProvider(HttpConfigurationProvider.class) .asEagerSingleton(); }
@Override protected Injector getInjector() { try { injector = Guice.createInjector(new GeeMvcModule(), new GeeTicketModule(), new ServletModule() { @Override protected void configureServlets() { install(new JpaPersistModule("geeticketPU")); filter("/*").through(PersistFilter.class); Map<String, String> params = new HashMap<String, String>(); params.put(Configuration.VIEW_PREFIX_KEY, "/jsp/pages"); params.put(Configuration.VIEW_SUFFIX_KEY, ".jsp"); params.put(Configuration.SUPPORTED_LOCALES_KEY, "en, de_DE, fr_FR, es_ES, ru_RU:UTF-8, ja_JP:Shift_JIS, zh:UTF-8"); params.put(Configuration.DEFAULT_CHARACTER_ENCODING_KEY, "UTF-8"); params.put(Configuration.DEFAULT_CONTENT_TYPE_KEY, "text/html"); serve("/geeticket/*").with(DispatcherServlet.class, params); } }); } catch (Throwable t) { System.out.println("!! An error occured during initialization of the GeeticketGuiceServletContextListener."); if (t instanceof com.google.inject.CreationException) { System.out.println("It seems that Guice was not able to create the injector due to problems with unregistered or incorrectly registered classes. Please check the Guice errors below!"); } t.printStackTrace(); } return injector; }
@Override protected Injector getInjector() { return Guice.createInjector(new AppModule(), new ServletModule() { @Override protected void configureServlets() { bind(TodoServlet.class) .in(Singleton.class); serve("/todos").with(TodoServlet.class); } }); }
@Override protected Injector getInjector() { return Guice.createInjector(new ServletModule() { @Override protected void configureServlets() { serve("/upload").with(UploadServlet.class); } }); }
@Override protected void configure() { install(new ServletModule() { @Override protected void configureServlets() { Map<String, String> config = Maps.newHashMap(); config.put(GlobalParameters.PROVIDERS_URL, MOUNT_POINT.substring(1)); config.put("minify", Boolean.FALSE.toString()); config.put(GlobalParameters.DEBUG, Boolean.toString(log.isDebugEnabled())); config.put(GlobalParameters.JSON_REQUEST_PROCESSOR_THREAD_CLASS, ExtDirectJsonRequestProcessorThread.class.getName()); config.put(GlobalParameters.GSON_BUILDER_CONFIGURATOR_CLASS, ExtDirectGsonBuilderConfigurator.class.getName()); serve(MOUNT_POINT + "*").with(ExtDirectServlet.class, config); filter(MOUNT_POINT + "*").through(SecurityFilter.class); } }); install(new FilterChainModule() { @Override protected void configure() { addFilterChain(MOUNT_POINT + "/**", NexusAuthenticationFilter.NAME, AnonymousFilter.NAME); } }); }
@Override protected void configure() { bind(GuiceFilter.class).to(DynamicGuiceFilter.class); // our configuration needs to be first-most when calculating order (some fudge room for edge-cases) final Binder highPriorityBinder = binder().withSource(Sources.prioritize(0x70000000)); highPriorityBinder.install(new ServletModule() { @Override protected void configureServlets() { bind(HeaderPatternFilter.class); bind(EnvironmentFilter.class); bind(ErrorPageFilter.class); filter("/*").through(HeaderPatternFilter.class); filter("/*").through(EnvironmentFilter.class); filter("/*").through(ErrorPageFilter.class); bind(ErrorPageServlet.class); serve("/error.html").with(ErrorPageServlet.class); serve("/throw.html").with(ThrowServlet.class); } }); highPriorityBinder.install(new MetricsModule()); install(new OrientModule()); }
@Override protected Injector getInjector() { return Guice.createInjector( new ServletModule() { @Override protected void configureServlets() { filter("/*").through(PrepareRequestAttributesFilter.class); } }, new AppEngineGuiceModule()); }