public static void main(String[] args) { LifeManager manager = new LifeManager(); manager.add(Guice.createInjector(new PrivateModule() { @Override protected void configure() { bind(Service.class).annotatedWith(Names.named("1")) .to(ServiceImpl.class) .in(Scopes.SINGLETON); expose(Service.class).annotatedWith(Names.named("1")); bind(ImplWorker.class).toInstance(new ImplWorker() { @Override public void work() { System.out.println("work 1 done"); } }); } }, new PrivateModule() { @Override protected void configure() { bind(Service.class).annotatedWith(Names.named("2")) .to(ServiceImpl.class) .in(Scopes.SINGLETON); expose(Service.class).annotatedWith(Names.named("2")); bind(ImplWorker.class).toInstance(new ImplWorker() { @Override public void work() { System.out.println("work 2 done"); } }); } }, new AbstractModule() { @Override protected void configure() { final Annotation id = UniqueAnnotations.create(); bind(Listener.class).annotatedWith(id).to(Client.class).asEagerSingleton(); } })); manager.start(); }
@Override protected void configure() { bind(DestinationFactory.class).in(Scopes.SINGLETON); bind(ReplicationQueue.class).in(Scopes.SINGLETON); DynamicSet.bind(binder(), GitReferenceUpdatedListener.class).to(ReplicationQueue.class); DynamicSet.bind(binder(), NewProjectCreatedListener.class).to(ReplicationQueue.class); DynamicSet.bind(binder(), ProjectDeletedListener.class).to(ReplicationQueue.class); DynamicSet.bind(binder(), HeadUpdatedListener.class).to(ReplicationQueue.class); bind(OnStartStop.class).in(Scopes.SINGLETON); bind(LifecycleListener.class).annotatedWith(UniqueAnnotations.create()).to(OnStartStop.class); bind(LifecycleListener.class) .annotatedWith(UniqueAnnotations.create()) .to(ReplicationLogFile.class); bind(CredentialsFactory.class) .to(AutoReloadSecureCredentialsFactoryDecorator.class) .in(Scopes.SINGLETON); bind(CapabilityDefinition.class) .annotatedWith(Exports.named(START_REPLICATION)) .to(StartReplicationCapability.class); install(new FactoryModuleBuilder().build(PushAll.Factory.class)); install(new FactoryModuleBuilder().build(RemoteSiteUser.Factory.class)); bind(ReplicationConfig.class).to(AutoReloadConfigDecorator.class); bind(ReplicationStateListener.class).to(ReplicationStateLogger.class); EventTypes.register(RefReplicatedEvent.TYPE, RefReplicatedEvent.class); EventTypes.register(RefReplicationDoneEvent.TYPE, RefReplicationDoneEvent.class); EventTypes.register(ReplicationScheduledEvent.TYPE, ReplicationScheduledEvent.class); bind(SshSessionFactory.class).toProvider(ReplicationSshSessionFactoryProvider.class); }
@Override protected final void configure() { internalConfigure(); configureServlets(); for ( FilterDefinition filterDefinition : filterDefinitions ) { bind(FilterDefinition.class).annotatedWith(UniqueAnnotations.create()).toInstance(filterDefinition); } for ( ServletDefinition servletDefinition : servletDefinitions ) { bind(ServletDefinition.class).annotatedWith(UniqueAnnotations.create()).toInstance(servletDefinition); } }
@Override public <T> Void visit(Binding<T> binding) { final Key<T> key = binding.getKey(); if (!keysToIntercept.contains(key)) { return super.visit(binding); } binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, Void>() { @Override public Void visit(UntargettedBinding<? extends T> untargettedBinding) { binder.addError("Cannot intercept bare binding of %s. " + "You may only intercept bindings that bind a class to something.", key); return null; } }); Key<T> anonymousKey = Key.get(key.getTypeLiteral(), UniqueAnnotations.create()); binder.bind(key).toProvider(new InterceptingProvider<T>(key, binder.getProvider(anonymousKey))); ScopedBindingBuilder scopedBindingBuilder = bindKeyToTarget(binding, binder, anonymousKey); // we scope the user's provider, not the interceptor. This is dangerous, // but convenient. It means that although the user's provider will live // in its proper scope, the intereptor gets invoked without a scope applyScoping(binding, scopedBindingBuilder); keysIntercepted.add(key); return null; }
@Override public <T> Void visit(Binding<T> binding) { final Key<T> key = binding.getKey(); if (!keysToIntercept.contains(key)) { return super.visit(binding); } binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, Void>() { @Override public Void visit(UntargettedBinding<? extends T> untargettedBinding) { binder.addError("Cannot intercept bare binding of %s. " + "You may only intercept bindings that bind a class to something.", key); return null; } }); Key<T> anonymousKey = Key.get(key.getTypeLiteral(), UniqueAnnotations.create()); binder.bind(key).toProvider(new InterceptingProvider<T>(key, binder.getProvider(anonymousKey))); ScopedBindingBuilder scopedBindingBuilder = bindKeyToTarget(binding, binder, anonymousKey); // we scope the user's provider, not the interceptor. This is dangerous, // but convenient. It means that although the user's provider will live // in its proper scope, the interceptor gets invoked without a scope applyScoping(binding, scopedBindingBuilder); keysIntercepted.add(key); return null; }
protected <T extends HttpServlet> ServletBindingBuilder bindServlet(Class<T> servlet) { Annotation annotation = UniqueAnnotations.create(); Key<T> servletKey = Key.get(servlet, UniqueAnnotations.create()); binder().bind(servletKey).to(servlet).in(Scopes.SINGLETON); return new ServletBindingBuilder(binder(), servletKey); }
@SuppressWarnings("unchecked") public ApplicationBindingBuilder addResources(Class<?>... annotatedClass) { for (Class<?> clazz : annotatedClass) { Key<Object> key = Key.get((Class<Object>) clazz, UniqueAnnotations.create()); binder.bind(key).to(clazz); initializer.addResource(key, clazz); } return this; }
@SuppressWarnings("unchecked") public <T> ApplicationBindingBuilder addResources(Class<T> annotatedClass, Provider<? extends T> resourceProvider) { Key<T> key = Key.get(annotatedClass, UniqueAnnotations.create()); binder.bind(key).toProvider(resourceProvider); initializer.addResource((Key<Object>) key, annotatedClass); return this; }
@SuppressWarnings("unchecked") public ApplicationBindingBuilder addProvider(Class<?> annotatedClass) { Key<Object> key = Key.get((Class<Object>) annotatedClass, UniqueAnnotations.create()); binder.bind(key).to(annotatedClass); initializer.addProvider(key); return this; }
@SuppressWarnings("unchecked") public ApplicationBindingBuilder addProviderInstance(Object object) { Key<Object> key = Key.get((Class<Object>) object.getClass(), UniqueAnnotations.create()); binder.bind(key).toInstance(object); initializer.addProvider(key); return this; }
@SuppressWarnings("unchecked") public <T> ApplicationBindingBuilder addProvider(Class<T> annotatedClass, Provider<? extends T> providerProvider) { Key<T> key = Key.get(annotatedClass, UniqueAnnotations.create()); binder.bind(key).toProvider(providerProvider); initializer.addProvider((Key<Object>) key); return this; }
@SuppressWarnings("unchecked") public <T> ApplicationBindingBuilder addProvider(Class<T> annotatedClass, Class<? extends Provider<? extends T>> providerProvider) { Key<T> key = Key.get(annotatedClass, UniqueAnnotations.create()); binder.bind(key).toProvider(providerProvider); initializer.addProvider((Key<Object>) key); return this; }
protected void rpc(String name, Class<? extends RemoteJsonService> clazz) { final Key<GerritJsonServlet> srv = Key.get(GerritJsonServlet.class, UniqueAnnotations.create()); final GerritJsonServletProvider provider = new GerritJsonServletProvider(clazz); bind(clazz); serve(prefix + name).with(srv); bind(srv).toProvider(provider).in(Scopes.SINGLETON); }
private Key<HttpServlet> key(HttpServlet servlet) { final Key<HttpServlet> srv = Key.get(HttpServlet.class, UniqueAnnotations.create()); bind(srv) .toProvider( new Provider<HttpServlet>() { @Override public HttpServlet get() { return servlet; } }) .in(SINGLETON); return srv; }
public static ServletModule module() { return new ServletModule() { @Override protected void configureServlets() { DynamicSet.setOf(binder(), AllRequestFilter.class); filter("/*").through(FilterProxy.class); bind(StopPluginListener.class) .annotatedWith(UniqueAnnotations.create()) .to(FilterProxy.class); } }; }
@Override protected void configureServlets() { bind(HttpPluginServlet.class); serveRegex("^/(?:a/)?plugins/(.*)?$").with(HttpPluginServlet.class); bind(LfsPluginServlet.class); serveRegex(LfsDefinitions.LFS_URL_REGEX).with(LfsPluginServlet.class); bind(StartPluginListener.class) .annotatedWith(UniqueAnnotations.create()) .to(HttpPluginServlet.class); bind(ReloadPluginListener.class) .annotatedWith(UniqueAnnotations.create()) .to(HttpPluginServlet.class); bind(StartPluginListener.class) .annotatedWith(UniqueAnnotations.create()) .to(LfsPluginServlet.class); bind(ReloadPluginListener.class) .annotatedWith(UniqueAnnotations.create()) .to(LfsPluginServlet.class); bind(ModuleGenerator.class).to(HttpAutoRegisterModuleGenerator.class); install( new CacheModule() { @Override protected void configure() { cache(PLUGIN_RESOURCES, ResourceKey.class, Resource.class) .maximumWeight(2 << 20) .weigher(ResourceWeigher.class); } }); DynamicMap.mapOf(binder(), DynamicOptions.DynamicBean.class); }
public static Annotation calculateBindAnnotation(Class<Object> impl) { Annotation n = impl.getAnnotation(Export.class); if (n == null) { n = impl.getAnnotation(javax.inject.Named.class); } if (n == null) { n = impl.getAnnotation(com.google.inject.name.Named.class); } if (n == null) { n = UniqueAnnotations.create(); } return n; }
private void with( Key<? extends HttpServlet> servletKey, Map<String, String> initParams, HttpServlet servletInstance) { for (UriPatternMatcher pattern : uriPatterns) { binder .bind(Key.get(ServletDefinition.class, UniqueAnnotations.create())) .toProvider(new ServletDefinition(servletKey, pattern, initParams, servletInstance)); } }
private void through( Key<? extends Filter> filterKey, Map<String, String> initParams, Filter filterInstance) { for (UriPatternMatcher pattern : uriPatterns) { binder .bind(FilterDefinition.class) .annotatedWith(UniqueAnnotations.create()) .toProvider(new FilterDefinition(filterKey, pattern, initParams, filterInstance)); } }
private static <T> Key<T> processSetBinding(Binder binder, Key<T> key) { Annotation annotation = key.getAnnotation(); Multibinder<T> setBinder = (annotation != null) ? Multibinder.newSetBinder(binder, key.getTypeLiteral(), annotation) : Multibinder.newSetBinder(binder, key.getTypeLiteral()); Key<T> newKey = Key.get(key.getTypeLiteral(), UniqueAnnotations.create()); setBinder.addBinding().to(newKey); return newKey; }
ScopedBindingBuilder toProviderMethod(CheckedProviderMethod<?> target) { Key<CheckedProviderMethod<?>> targetKey = Key.get(CHECKED_PROVIDER_METHOD_TYPE, UniqueAnnotations.create()); binder.bind(targetKey).toInstance(target); return toInternal(targetKey); }
private void with(Key<? extends HttpServlet> servletKey, Map<String, String> initParams, HttpServlet servletInstance) { for (String pattern : uriPatterns) { // Ensure two servlets aren't bound to the same pattern. if (!servletUris.add(pattern)) { binder.addError("More than one servlet was mapped to the same URI pattern: " + pattern); } else { binder.bind(Key.get(ServletDefinition.class, UniqueAnnotations.create())).toProvider( new ServletDefinition(pattern, servletKey, UriPatternType .get(uriPatternType, pattern), initParams, servletInstance)); } } }
private void through(Key<? extends Filter> filterKey, Map<String, String> initParams, Filter filterInstance) { for (String pattern : uriPatterns) { binder.bind(FilterDefinition.class).annotatedWith(UniqueAnnotations.create()).toProvider( new FilterDefinition(pattern, filterKey, UriPatternType.get(uriPatternType, pattern), initParams, filterInstance)); } }
ScopedBindingBuilder toProviderMethod(CheckedProviderMethod<?> target) { Key<CheckedProviderMethod> targetKey = Key.get(CheckedProviderMethod.class, UniqueAnnotations.create()); binder.bind(targetKey).toInstance(target); return toInternal(targetKey); }
public void through(Filter filter, Map<String, String> initParams) { Key<Filter> filterKey = Key.get(Filter.class, UniqueAnnotations.create()); module.add(filterKey, filter); through(filterKey, initParams, filter); }
public void with(HttpServlet servlet, Map<String, String> initParams) { Key<HttpServlet> servletKey = Key.get(HttpServlet.class, UniqueAnnotations.create()); module.add(servletKey, servlet); with(servletKey, initParams, servlet); }
AbstractServletBindingBuilder(Binder binder, Initializer initializer) { this.initializer = initializer; binder.bind(GuiceRsServletInitializer.class).annotatedWith(UniqueAnnotations.create()).toInstance(initializer); }
protected LinkedBindingBuilder<InitStep> step() { final Annotation id = UniqueAnnotations.create(); return bind(InitStep.class).annotatedWith(id); }
@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); }
@Override public void with(HttpServlet servlet, Map<String, String> initParams) { Key<HttpServlet> servletKey = Key.get(HttpServlet.class, UniqueAnnotations.create()); binder.bind(servletKey).toInstance(servlet); with(servletKey, initParams, servlet); }
@Override public void through(Filter filter, Map<String, String> initParams) { Key<Filter> filterKey = Key.get(Filter.class, UniqueAnnotations.create()); binder.bind(filterKey).toInstance(filter); through(filterKey, initParams, filter); }
public ScopedBindingBuilder to(P target) { Key<P> targetKey = Key.get(interfaceType, UniqueAnnotations.create()); binder.bind(targetKey).toInstance(target); return to(targetKey); }
/** @since 4.0 */ @SuppressWarnings("unchecked") // safe because this is the cxtor of the literal public ScopedBindingBuilder providing(TypeLiteral<? extends T> cxtorLiteral) { // Find a constructor that has @ThrowingInject. Constructor<? extends T> cxtor = CheckedProvideUtils.findThrowingConstructor(cxtorLiteral, binder); final Provider<T> typeProvider; final Key<? extends T> typeKey; // If we found an injection point, then bind the cxtor to a unique key if (cxtor != null) { // Validate the exceptions are consistent with the CheckedProvider interface. CheckedProvideUtils.validateExceptions( binder, cxtorLiteral.getExceptionTypes(cxtor), exceptionTypes, interfaceType); typeKey = Key.get(cxtorLiteral, UniqueAnnotations.create()); binder.bind(typeKey).toConstructor((Constructor) cxtor).in(Scopes.NO_SCOPE); typeProvider = binder.getProvider((Key<T>) typeKey); } else { // never used, but need it assigned. typeProvider = null; typeKey = null; } // Create a CheckedProvider that calls our cxtor CheckedProvider<T> checkedProvider = new CheckedProviderWithDependencies<T>() { @Override public T get() throws Exception { try { return typeProvider.get(); } catch (ProvisionException pe) { // Rethrow the provision cause as the actual exception if (pe.getCause() instanceof Exception) { throw (Exception) pe.getCause(); } else if (pe.getCause() instanceof Error) { throw (Error) pe.getCause(); } else { // If this failed because of multiple reasons (ie, more than // one dependency failed due to scoping errors), then // the ProvisionException won't have a cause, so we need // to rethrow it as-is. throw pe; } } } @Override public Set<Dependency<?>> getDependencies() { return ImmutableSet.<Dependency<?>>of(Dependency.get(typeKey)); } }; Key<CheckedProvider<?>> targetKey = Key.get(CHECKED_PROVIDER_TYPE, UniqueAnnotations.create()); binder.bind(targetKey).toInstance(checkedProvider); return toInternal(targetKey); }
private ScopedBindingBuilder toInternal(final Key<? extends CheckedProvider<?>> targetKey) { final Key<Result> resultKey = Key.get(Result.class, UniqueAnnotations.create()); // Note that this provider will behave like the final provider Guice creates. // It will especially do scoping if the user adds that. final Provider<Result> resultProvider = binder.getProvider(resultKey); final Provider<? extends CheckedProvider<?>> targetProvider = binder.getProvider(targetKey); interfaceKey = createKey(); // don't bother binding the proxy type if this is in an invalid state. if (valid) { binder .bind(interfaceKey) .toProvider( new ProviderWithDependencies<P>() { private final P instance = interfaceType.cast( Proxy.newProxyInstance( interfaceType.getClassLoader(), new Class<?>[] {interfaceType}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Allow methods like .equals(..), .hashcode(..), .toString(..) to work. if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args); } if (scopeExceptions) { return resultProvider.get().getOrThrow(); } else { Result result; try { result = resultProvider.get(); } catch (ProvisionException pe) { Throwable cause = pe.getCause(); if (cause instanceof ResultException) { throw ((ResultException) cause).getCause(); } else { throw pe; } } return result.getOrThrow(); } } })); @Override public P get() { return instance; } @Override public Set<Dependency<?>> getDependencies() { return ImmutableSet.<Dependency<?>>of(Dependency.get(resultKey)); } }); } // The provider is unscoped, but the user may apply a scope to it through the // ScopedBindingBuilder this returns. return binder.bind(resultKey).toProvider(createResultProvider(targetKey, targetProvider)); }
@Override protected void configureServlets() { log.info("Configuring servlet and filters"); // Plugin life-cycle listener bind(PluginActivator.class); bind(LifecycleListener.class).annotatedWith(UniqueAnnotations.create()).to(PluginActivator.class); // Changed things bind(IStoredSettings.class).to(GitBlitSettings.class); bind(IRuntimeManager.class).to(GerritGitBlitRuntimeManager.class); bind(IUserManager.class).to(GerritGitBlitUserManager.class); bind(IAuthenticationManager.class).to(GerritGitBlitAuthenticationManager.class); bind(IRepositoryManager.class).to(GerritGitBlitRepositoryManager.class); bind(GitblitContext.class).to(GerritGitBlitContext.class); bind(GitBlitWebApp.class).to(GerritGitBlitWebApp.class); bind(IPluginManager.class).to(NullPluginManager.class); bind(ITicketService.class).to(ReallyNullTicketService.class); // Gitblit bindings bind(XssFilter.class).to(JSoupXssFilter.class); bind(AvatarGenerator.class).to(GravatarGenerator.class); bind(WorkQueue.class).toProvider(WorkQueueProvider.class); bind(IGitblit.class).to(GitblitManager.class); // core managers bind(IPluginManager.class).to(NullPluginManager.class); bind(INotificationManager.class).to(NotificationManager.class); bind(IProjectManager.class).to(ProjectManager.class); bind(IFederationManager.class).to(FederationManager.class); bind(IFilestoreManager.class).to(FilestoreManager.class); bind(IPublicKeyManager.class).toProvider(IPublicKeyManagerProvider.class); // manager for long-running daemons and services bind(IServicesManager.class).to(ServicesManager.class); // Servlets -- note: FilestoreServlet is not configured serve('/' + WrappedPagesFilter.SERVLET_RELATIVE_PATH + '*').with(PagesServlet.class); serve('/' + WrappedRawFilter.SERVLET_RELATIVE_PATH + '*').with(RawServlet.class); serve('/' + WrappedSyndicationFilter.SERVLET_RELATIVE_PATH + '*').with(WrappedSyndicationServlet.class); serve("/zip/*").with(DownloadZipServlet.class); serve("/logo.png").with(LogoServlet.class); serve("/static/logo.png").with(LogoServlet.class); serve("/graph/*").with(BranchGraphServlet.class); serve("/static/*").with(StaticResourcesServlet.class); serve("/clippy.swf").with(StaticResourcesServlet.class); serve("/pt").with(PtServlet.class); // Filters filter("/*").through(GerritWicketFilter.class); filter('/' + WrappedPagesFilter.SERVLET_RELATIVE_PATH + '*').through(WrappedPagesFilter.class); filter('/' + WrappedRawFilter.SERVLET_RELATIVE_PATH + '*').through(WrappedRawFilter.class); filter('/' + WrappedSyndicationFilter.SERVLET_RELATIVE_PATH + '*').through(WrappedSyndicationFilter.class); }
public void with(HttpServlet servlet, Map<String, String> initParams) { Key<HttpServlet> servletKey = Key.get(HttpServlet.class, UniqueAnnotations.create()); binder.bind(servletKey).toInstance(servlet); with(servletKey, initParams, servlet); }
public void through(Filter filter, Map<String, String> initParams) { Key<Filter> filterKey = Key.get(Filter.class, UniqueAnnotations.create()); binder.bind(filterKey).toInstance(filter); through(filterKey, initParams, filter); }