@Override public void beforeEach(final ExtensionContext context) throws Exception { final GuicyTest testInstance = (GuicyTest)context.getTestInstance().get(); final Module module = testInstance.module(); final RequestScope requestScope = new RequestScope(); final AbstractModule basicTestModule = new AbstractModule() { @Override protected void configure() { this.bindScope(RequestScoped.class, requestScope); this.bind(RequestScope.class).toInstance(requestScope); this.bind(HttpServletRequest.class).to(FakeHttpServletRequest.class); this.bind(HttpServletResponse.class).to(FakeHttpServletResponse.class); } }; final Injector injector = Guice.createInjector(Modules.override(basicTestModule).with(module)); context.getStore(NAMESPACE).put(Injector.class, injector); final ScopeRequestFilter scopeFilter = injector.getInstance(ScopeRequestFilter.class); injector.getInstance(Requestor.class).addFilter(scopeFilter); }
@Provides @CookieMap @RequestScoped Multimap<String,Cookie> getCookieMap( Provider<HttpServletRequest> httpServletRequestProvider) { Cookie[] cookies = httpServletRequestProvider.get().getCookies(); ImmutableMultimap.Builder<String, Cookie> temp = new ImmutableMultimap.Builder<String, Cookie>(); if (cookies != null) { for (Cookie cookie : cookies) { temp.put(cookie.getName(), cookie); } } return temp.build(); }
static Module module() { return new AbstractModule() { @Override public void configure() { install(new GerritRequestModule()); bind(RequestScopePropagator.class).to(Propagator.class); bindScope(RequestScoped.class, InProcessProtocol.REQUEST); } @Provides @RemotePeer SocketAddress getSocketAddress() { // TODO(dborowitz): Could potentially fake this with thread ID or // something. throw new OutOfScopeException("No remote peer in acceptance tests"); } }; }
public static Module module() { return new CacheModule() { @Override protected void configure() { persist(WebSessionManager.CACHE_NAME, String.class, Val.class) .maximumWeight(1024) // reasonable default for many sites .expireAfterWrite( CacheBasedWebSession.MAX_AGE_MINUTES, MINUTES) // expire sessions if they are inactive ; install(new FactoryModuleBuilder().build(WebSessionManagerFactory.class)); DynamicItem.itemOf(binder(), WebSession.class); DynamicItem.bind(binder(), WebSession.class) .to(H2CacheBasedWebSession.class) .in(RequestScoped.class); } }; }
@Provides @RequestScoped User provideAppengineUser(UserService userService) { User user = userService.getCurrentUser(); if (user == null) { throw new ProvisionException("Not logged in"); } return user; }
@Provides @RequestScoped @Named("wave url base") String provideWaveUrlBase(HttpServletRequest req) throws MalformedURLException { URL requestUrl = new URL(req.getRequestURL().toString()); String portString = requestUrl.getPort() == -1 ? "" : ":" + requestUrl.getPort(); String waveUrlBase = requestUrl.getProtocol() + "://" + requestUrl.getHost() + portString + "/"; log.info("requestUrl=" + requestUrl + ", waveUrlBase=" + waveUrlBase); return waveUrlBase; }
@Provides @RequestScoped TestId get(@CookieMap Multimap<String,Cookie> cookieMap) { Collection<Cookie> temp = cookieMap.get(TestId.COOKIE_NAME); if (temp.size() > 1) { throw new IllegalStateException(String.format( "There's more than one Cookie named '%s'.", TestId.COOKIE_NAME)); } else if (temp.size() == 0) { return null; } return new TestId(temp.iterator().next()); }
@Override protected void configure() { bind(RequestScopePropagator.class).to(GuiceRequestScopePropagator.class); bind(HttpRequestContext.class); installAuthModule(); if (options.enableMasterFeatures()) { install(new UrlModule(options, authConfig)); install(new UiRpcModule()); } install(new GerritRequestModule()); install(new GitOverHttpServlet.Module(options.enableMasterFeatures())); if (gitwebCgiConfig.getGitwebCgi() != null) { install(new GitwebModule()); } install(new AsyncReceiveCommits.Module()); bind(SocketAddress.class) .annotatedWith(RemotePeer.class) .toProvider(HttpRemotePeerProvider.class) .in(RequestScoped.class); bind(ProxyProperties.class).toProvider(ProxyPropertiesProvider.class); listener().toInstance(registerInParentInjectors()); install(UniversalWebLoginFilter.module()); }
@Override protected void configure() { bind(RequestCleanup.class).in(RequestScoped.class); bind(RequestScopedReviewDbProvider.class); bind(IdentifiedUser.RequestFactory.class).in(SINGLETON); bind(PerRequestProjectControlCache.class).in(RequestScoped.class); }
@Override protected void configure() { bind(Gson.class).toInstance(new GsonBuilder().setPrettyPrinting().create()); bind(LabelJsonProvider.class).to(LabelJsonFromFileProvider.class).in(Scopes.SINGLETON); bind(GlobalConfigurationJsonStore.class).in(Scopes.SINGLETON); bind(IdentityConfJsonStore.class).in(Scopes.SINGLETON); bind(UserPermissionsJsonStore.class).in(Scopes.SINGLETON); bind(ExperimentalConfJsonStore.class).in(Scopes.SINGLETON); bind(RequestBodyReader.class).in(RequestScoped.class); }
@Override protected void configure() { Provider<Injector> injector = getProvider(Injector.class); bind(ServiceLocator.class).toProvider(new ServiceLocatorProvider(injector, locator)) .in(Singleton.class); Provider<ServiceLocator> provider = getProvider(ServiceLocator.class); bind(Application.class) .toProvider(new JerseyProvider<>(provider, Application.class)); bind(Providers.class) .toProvider(new JerseyProvider<>(provider, Providers.class)); bind(UriInfo.class) .toProvider(new JerseyProvider<>(provider, UriInfo.class)) .in(RequestScoped.class); bind(HttpHeaders.class) .toProvider(new JerseyProvider<>(provider, HttpHeaders.class)) .in(RequestScoped.class); bind(SecurityContext.class) .toProvider(new JerseyProvider<>(provider, SecurityContext.class)) .in(RequestScoped.class); bind(Request.class) .toProvider(new JerseyProvider<>(provider, Request.class)) .in(RequestScoped.class); }
@Override protected void configure() { bindScope(RequestScoped.class, ServletScopes.REQUEST); for (Binding binding : bindings) { binding.bind(); } }
@Override protected void configure() { configureHandlers(); bindScope(RequestScoped.class, requestScope); bind(RequestScope.class).toInstance(requestScope); bind(new Key<List<RequestMatcher>>() {}).toInstance(matchers.build()); bind(Servlet.class).to(RequestHandlerServlet.class).in(Singleton.class); bind(GatewayRequestHandler.Factory.class).toProvider( FactoryProvider.newFactory( GatewayRequestHandler.Factory.class, GatewayRequestHandler.class)); bind(GatewayConfiguration.class).in(Singleton.class); }
protected void serve(HttpMethod method, String pattern, Class<? extends RequestHandler> withHttpHandler) { logger.debug("Registering {} on {} to {}", new Object[]{method, pattern, withHttpHandler}); RequestMatcher matcher = new RequestMatcher(method, pattern); matchers.add(matcher); MapBinder.newMapBinder(binder(), RequestMatcher.class, RequestHandler.class) .addBinding(matcher).to(withHttpHandler).in(RequestScoped.class); }
@Override protected void configure() { ThrowingProviderBinder.create(binder()) .bind(PaginationProvider.class, Pagination.class) .to(PaginationProviderImpl.class) .in(RequestScoped.class); }
/** * Create a mock injector for tests * @param <T> type of class/interface * @param api the interface class of the object to inject * @param impl the implementation object to inject * @param modules additional guice modules * @return an injector */ public static <T> Injector createMockInjector(final Class<T> api, final T impl, final Module... modules) { return Guice.createInjector(new AbstractModule() { final PrintWriter writer = spy(new PrintWriter(System.out)); final HttpServletRequest request = createRequest(); final HttpServletResponse response = createResponse(); @Override protected void configure() { if (api != null) { bind(api).toInstance(impl); } bindScope(RequestScoped.class, Scopes.SINGLETON); if (modules != null) { for (Module module : modules) { install(module); } } } @Provides HttpServletRequest request() { return request; } @Provides HttpServletResponse response() { return response; } @Provides PrintWriter writer() { return writer; } HttpServletRequest createRequest() { // the default suffices for now return mock(HttpServletRequest.class); } HttpServletResponse createResponse() { try { HttpServletResponse res = mock(HttpServletResponse.class); when(res.getWriter()).thenReturn(writer); return res; } catch (Exception e) { throw new WebAppException(e); } } }); }
public static void main(String[] args) throws Exception { System.setProperty(Sdk.DISABLE_REQUEST_SIGNATURE_CHECK_SYSTEM_PROPERTY, "true"); String envPort = System.getenv("PORT"); int port = envPort == null || envPort.isEmpty() ? 8000 : Integer.valueOf(envPort); // Configure server and its associated servlets Server server = new Server(port); ServletContextHandler context = new ServletContextHandler(); context.addEventListener(new GuiceServletContextListener() { @Override protected Injector getInjector() { Module services = new AbstractModule() { @Override protected void configure() { bind(SpeechRouter.class).toProvider(new Provider<SpeechRouter>() { @Inject Injector injector; @Override public SpeechRouter get() { try { return SpeechRouter.create(injector, "rottentomatoes"); } catch (Exception e) { e.printStackTrace(); return null; } } }).in(Singleton.class); bind(AlexaSessionProvider.class).in(RequestScoped.class); bind(RequestContextProvider.class).in(RequestScoped.class); bind(SpeechletServlet.class).toProvider(new Provider<SpeechletServlet>() { @Inject SpeechRouter router; @Inject Injector injector; @Override public SpeechletServlet get() { SpeechletServlet servlet = new SpeechletServlet(); servlet.setSpeechlet(new RoutingSpeechlet(router, injector)); return servlet; } }).in(Singleton.class); } }; return Guice.createInjector(services, new ServletModule() { @Override protected void configureServlets() { serve("/sample-utterances").with(SampleUtterancesServlet.class); serve("/intent-schema").with(IntentSchemaServlet.class); serve("/rotten-tomatoes").with(SpeechletServlet.class); } }); } }); context.addFilter(GuiceFilter.class, "/*", null); context.addServlet(DefaultServlet.class, "/"); server.setHandler(context); server.start(); server.join(); }
protected Destination( Injector injector, DestinationConfiguration cfg, RemoteSiteUser.Factory replicationUserFactory, PluginUser pluginUser, GitRepositoryManager gitRepositoryManager, PermissionBackend permissionBackend, Provider<CurrentUser> userProvider, ProjectCache projectCache, GroupBackend groupBackend, ReplicationStateListener stateLog, GroupIncludeCache groupIncludeCache, DynamicItem<EventDispatcher> eventDispatcher) { config = cfg; this.eventDispatcher = eventDispatcher; gitManager = gitRepositoryManager; this.permissionBackend = permissionBackend; this.userProvider = userProvider; this.projectCache = projectCache; this.stateLog = stateLog; CurrentUser remoteUser; if (!cfg.getAuthGroupNames().isEmpty()) { ImmutableSet.Builder<AccountGroup.UUID> builder = ImmutableSet.builder(); for (String name : cfg.getAuthGroupNames()) { GroupReference g = GroupBackends.findExactSuggestion(groupBackend, name); if (g != null) { builder.add(g.getUUID()); addRecursiveParents(g.getUUID(), builder, groupIncludeCache); } else { repLog.warn(String.format("Group \"%s\" not recognized, removing from authGroup", name)); } } remoteUser = replicationUserFactory.create(new ListGroupMembership(builder.build())); } else { remoteUser = pluginUser; } Injector child = injector.createChildInjector( new FactoryModule() { @Override protected void configure() { bindScope(RequestScoped.class, PerThreadRequestScope.REQUEST); bind(PerThreadRequestScope.Propagator.class); bind(Destination.class).toInstance(Destination.this); bind(RemoteConfig.class).toInstance(config.getRemoteConfig()); install(new FactoryModuleBuilder().build(PushOne.Factory.class)); } @Provides public PerThreadRequestScope.Scoper provideScoper( final PerThreadRequestScope.Propagator propagator, final Provider<RequestScopedReviewDbProvider> dbProvider) { final RequestContext requestContext = new RequestContext() { @Override public CurrentUser getUser() { return remoteUser; } @Override public Provider<ReviewDb> getReviewDbProvider() { return dbProvider.get(); } }; return new PerThreadRequestScope.Scoper() { @Override public <T> Callable<T> scope(Callable<T> callable) { return propagator.scope(requestContext, callable); } }; } }); opFactory = child.getInstance(PushOne.Factory.class); threadScoper = child.getInstance(PerThreadRequestScope.Scoper.class); }
@Override protected void configure() { bindScope(RequestScoped.class, SshScope.REQUEST); bind(RequestScopePropagator.class).to(SshScope.Propagator.class); bind(SshScope.class).in(SINGLETON); configureRequestScope(); install(new AsyncReceiveCommits.Module()); configureAliases(); bind(SshLog.class); bind(SshInfo.class).to(SshDaemon.class).in(SINGLETON); factory(DispatchCommand.Factory.class); factory(QueryShell.Factory.class); factory(PeerDaemonUser.Factory.class); bind(DispatchCommandProvider.class) .annotatedWith(Commands.CMD_ROOT) .toInstance(new DispatchCommandProvider(Commands.CMD_ROOT)); bind(CommandFactoryProvider.class); bind(CommandFactory.class).toProvider(CommandFactoryProvider.class); bind(ScheduledThreadPoolExecutor.class) .annotatedWith(StreamCommandExecutor.class) .toProvider(StreamCommandExecutorProvider.class) .in(SINGLETON); bind(QueueProvider.class).to(CommandExecutorQueueProvider.class).in(SINGLETON); bind(GSSAuthenticator.class).to(GerritGSSAuthenticator.class); bind(PublickeyAuthenticator.class).to(CachingPublicKeyAuthenticator.class); bind(ModuleGenerator.class).to(SshAutoRegisterModuleGenerator.class); bind(SshPluginStarterCallback.class); bind(StartPluginListener.class) .annotatedWith(UniqueAnnotations.create()) .to(SshPluginStarterCallback.class); bind(ReloadPluginListener.class) .annotatedWith(UniqueAnnotations.create()) .to(SshPluginStarterCallback.class); DynamicMap.mapOf(binder(), DynamicOptions.DynamicBean.class); listener().toInstance(registerInParentInjectors()); listener().to(SshLog.class); listener().to(SshDaemon.class); listener().to(CommandFactoryProvider.class); }
@Provides @Named("current.user") @RequestScoped public User provideCurrentUser() { throw new NotAuthorizedException("user id must be manually seeded"); }
@Provides @RequestScoped @Inject PersistenceManager getPersistenceManager(PersistenceManagerFactory pmf) { return pmf.getPersistenceManager(); }
@RequestScoped @Provides public HttpContext httpContext(WebApplication webApplication) { return webApplication.getThreadLocalHttpContext(); }
@Provides @RequestScoped public UriInfo uriInfo(WebApplication wa) { return wa.getThreadLocalHttpContext().getUriInfo(); }
@Provides @RequestScoped public ExtendedUriInfo extendedUriInfo(WebApplication wa) { return wa.getThreadLocalHttpContext().getUriInfo(); }
@RequestScoped @Provides public HttpRequestContext requestContext(WebApplication wa) { return wa.getThreadLocalHttpContext().getRequest(); }
@RequestScoped @Provides public HttpHeaders httpHeaders(WebApplication wa) { return wa.getThreadLocalHttpContext().getRequest(); }
@RequestScoped @Provides public Request request(WebApplication wa) { return wa.getThreadLocalHttpContext().getRequest(); }
@RequestScoped @Provides public SecurityContext securityContext(WebApplication wa) { return wa.getThreadLocalHttpContext().getRequest(); }
@RequestScoped @Provides public HttpResponseContext responseContext(WebApplication wa) { return wa.getThreadLocalHttpContext().getResponse(); }
@Override protected void configure() { bind(Validator.class).toProvider(HibernateValidatorProvider.class).in(Singleton.class); for (Class<?> resource : new JerseyResourceConfig().getClasses()) bind(resource).in(Singleton.class); bind(User.class).toProvider(AuthenticationService.class).in(RequestScoped.class); }