@Override protected void configure() { // @InjectorScoped annotation install(new InjectorScopeModule()); // Provide a global, catch-all exception handler bind(LoggingExceptionHandler.class).in(Singleton.class); bind(ExceptionHandler.class).to(LoggingExceptionHandler.class); bind(new TypeLiteral<ExceptionHandler<Throwable>>(){}).to(LoggingExceptionHandler.class); bind(Thread.UncaughtExceptionHandler.class).to(LoggingExceptionHandler.class); // Evil decorator thing // Create it manually so we can use it before the injector is ready bind(DecoratorFactory.class).toInstance(DecoratorFactory.get()); install(new NumberFactory.Manifest()); install(new ParsersManifest()); requestStaticInjection(SystemFutureCallback.class); if(currentStage() == Stage.DEVELOPMENT) { // This is useful, but it makes the LeakDetector unhappy //install(new RepeatInjectionDetector()); } }
public Stage getGuiceStage(){ String stageString = System.getProperty(PROPERTY_NAME); final Stage stage; boolean development = Stage.DEVELOPMENT.name().equals(stageString); boolean production = Stage.PRODUCTION.name().equals(stageString); if(development || production){ stage = development ? Stage.DEVELOPMENT : Stage.PRODUCTION; logger.warn("using Guice Stage {} from JVM arg -D{}={}", stage, PROPERTY_NAME, stageString); }else if(stageString != null){ stage = Stage.PRODUCTION; logger.warn("unrecognized JVM arg value -D{}={}, using Guice Stage {}", PROPERTY_NAME, stageString, Stage.PRODUCTION); }else{ stage = Stage.PRODUCTION; logger.warn("using default Guice Stage={}", Stage.PRODUCTION); } return stage; }
@Override public void initialize(Bootstrap<ServerConfiguration> bootstrap) { bootstrap.addBundle(hibernateBundle); bootstrap.addBundle(new AssetsBundle("/swagger-spec", "/api-spec", null)); bootstrap.addBundle(GuiceBundle.<ServerConfiguration>newBuilder() .addModule(new AbstractModule(){ @Override protected void configure() {} @Provides SessionFactory sessionFactoryProvider() { return hibernateBundle.getSessionFactory();} }) .setConfigClass(ServerConfiguration.class) .enableAutoConfig(getClass().getPackage().getName()) .build(Stage.DEVELOPMENT) ); bootstrap.addBundle(new Java8Bundle()); // Enable variable substitution with environment variables bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(false) ) ); }
public static void main(String... args) { final long start = System.currentTimeMillis(); try { final Injector injector = Guice.createInjector(Stage.PRODUCTION, new SingularityRunnerBaseModule(SingularityExecutorCleanupConfiguration.class, ImmutableSet.of(SingularityS3Configuration.class, SingularityExecutorConfiguration.class)), new SingularityExecutorModule(), new SingularityExecutorCleanupModule(), new SingularityClientModule(), new SingularityMesosClientModule()); final SingularityExecutorCleanupRunner runner = injector.getInstance(SingularityExecutorCleanupRunner.class); LOG.info("Starting cleanup"); final SingularityExecutorCleanupStatistics statistics = runner.cleanup(); LOG.info("Finished with {} after {}", statistics, JavaUtils.duration(start)); System.exit(0); } catch (Throwable t) { LOG.error("Finished after {} with error", JavaUtils.duration(start), t); System.exit(1); } }
public static void main(String... args) { final long start = System.currentTimeMillis(); try { final Injector injector = Guice.createInjector(Stage.PRODUCTION, new SingularityRunnerBaseModule(SingularityExecutorConfiguration.class, ImmutableSet.<Class<? extends BaseRunnerConfiguration>>of(SingularityS3Configuration.class)), new SingularityExecutorModule()); final SingularityExecutorRunner executorRunner = injector.getInstance(SingularityExecutorRunner.class); final Protos.Status driverStatus = executorRunner.run(); LOG.info("Executor finished after {} with status: {}", JavaUtils.duration(start), driverStatus); System.exit(driverStatus == Protos.Status.DRIVER_STOPPED ? 0 : 1); } catch (Throwable t) { LOG.error("Finished after {} with error", JavaUtils.duration(start), t); System.exit(1); } }
@Override public void initialize(final Bootstrap<ProductCatalogConfiguration> bootstrap) { bootstrap.addBundle(discoveryBundle); bootstrap.addBundle(new MigrationsBundle<ProductCatalogConfiguration>() { @Override public PooledDataSourceFactory getDataSourceFactory(ProductCatalogConfiguration configuration) { return configuration.getDataSourceFactory(); } }); guiceBundle = GuiceBundle.<ProductCatalogConfiguration> newBuilder().addModule(new ProductCatalogModule()) .enableAutoConfig(getClass().getPackage().getName()).setConfigClass(ProductCatalogConfiguration.class) .build(Stage.PRODUCTION); bootstrap.addBundle(guiceBundle); // Uncomment below to read the yaml file from Jar // bootstrap.setConfigurationSourceProvider(new // ResourceConfigurationSourceProvider()); }
@Override public void initialize(final Bootstrap<ProductReviewConfiguration> bootstrap) { bootstrap.addBundle(discoveryBundle); bootstrap.addBundle(new MigrationsBundle<ProductReviewConfiguration>() { @Override public PooledDataSourceFactory getDataSourceFactory(ProductReviewConfiguration configuration) { return configuration.getDataSourceFactory(); } }); guiceBundle = GuiceBundle.<ProductReviewConfiguration> newBuilder().addModule(new ProductReviewModule()) .enableAutoConfig(getClass().getPackage().getName()).setConfigClass(ProductReviewConfiguration.class) .build(Stage.PRODUCTION); bootstrap.addBundle(guiceBundle); // Uncomment below to read the yaml file from Jar // bootstrap.setConfigurationSourceProvider(new // ResourceConfigurationSourceProvider()); }
public Client(@NonNull Path filePath, @NonNull Config config, boolean cleanRun, @NonNull List<?> listeners) { this.filePath = checkFile(filePath); this.cleanRun = cleanRun; Injector injector = Guice.createInjector( Stage.PRODUCTION, new ConfigurationModule(ConfigValidator.checkValid(config.withFallback(ConfigFactory.load()))), new JpaRepositoryModule(), new ServiceModule() ); persistService = injector.getInstance(PersistService.class); persistService.start(); handlerType = injector.getInstance(MovieHandler.Type.class); handlerChain = injector.getInstance(MovieHandler.class); importProgressService = injector.getInstance(ImportProgressService.class); eventBus = new EventBus(); listeners.forEach(eventBus::register); }
@Override protected Injector getInjector() { // Create injector Injector injector = Guice.createInjector(Stage.PRODUCTION, new EnvironmentModule(environment), new LogModule(environment), new ExtensionModule(environment), new RESTServiceModule(sessionMap), new TunnelModule() ); // Inject any annotated members of this class injector.injectMembers(this); return injector; }
protected void initialize() { EuropaConfiguration europaConfiguration = null; if(_configFilePath != null) europaConfiguration = EuropaConfiguration.fromFile(new File(_configFilePath)); else europaConfiguration = EuropaConfiguration.fromEnvironment(); europaConfiguration.setStage(_stage); Injector injector = Guice.createInjector(Stage.PRODUCTION, new PersistenceModule(), new AjaxHelperModule(), new ObjectStoreModule(), new EuropaInjectorModule(europaConfiguration)); injector.injectMembers(this); initializeWebServer(injector); }
private void addStageCreationRule() { // stage rule config.creationPipeline.creationRules.add(new CreationRule() { @Override public Optional<Function<RecipeCreationContext, SupplierRecipe>> apply( CoreDependencyKey<?> key, CoreInjector injector) { if (Stage.class.equals(key.getType().getType())) return Optional.of(ctx -> new SupplierRecipeImpl( () -> guiceConfig.stage)); else return Optional.empty(); } }); }
@Test public void testImmediateStarts() throws Exception { Injector injector = Guice.createInjector( Stage.PRODUCTION, new LifeCycleModule(), new Module() { @Override public void configure(Binder binder) { binder.bind(InstanceThatRequiresStart.class).in(Scopes.SINGLETON); binder.bind(InstanceThatUsesInstanceThatRequiresStart.class).in(Scopes.SINGLETON); } }); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); Assert.assertEquals(stateLog, ImmutableList.of("InstanceThatUsesInstanceThatRequiresStart:OK")); }
@Test public void testSubClassAnnotated() throws Exception { Injector injector = Guice.createInjector( Stage.PRODUCTION, new LifeCycleModule(), new Module() { @Override public void configure(Binder binder) { binder.bind(SimpleBase.class).to(SimpleBaseImpl.class).in(Scopes.SINGLETON); } }); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); Assert.assertEquals(stateLog, ImmutableList.of("postSimpleBaseImpl")); lifeCycleManager.destroy(); Assert.assertEquals(stateLog, ImmutableList.of("postSimpleBaseImpl", "preSimpleBaseImpl")); }
@Test public void testIllegalMethods() throws Exception { try { Guice.createInjector( Stage.PRODUCTION, new Module() { @Override public void configure(Binder binder) { binder.bind(IllegalInstance.class).in(Scopes.SINGLETON); } }, new LifeCycleModule()); Assert.fail(); } catch (CreationException dummy) { // correct behavior } }
@Test public void testDuplicateMethodNames() throws Exception { Injector injector = Guice.createInjector( Stage.PRODUCTION, new Module() { @Override public void configure(Binder binder) { binder.bind(FooTestInstance.class).in(Scopes.SINGLETON); } }, new LifeCycleModule() ); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); lifeCycleManager.destroy(); Assert.assertEquals(stateLog, ImmutableList.of("foo")); }
@Test public void testJITInjection() throws Exception { Injector injector = Guice.createInjector( Stage.PRODUCTION, new LifeCycleModule(), new Module() { @Override public void configure(Binder binder) { binder.bind(AnInstance.class).in(Scopes.SINGLETON); binder.bind(DependentInstance.class).in(Scopes.SINGLETON); } }); injector.getInstance(AnInstance.class); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); lifeCycleManager.destroy(); Assert.assertEquals(stateLog, ImmutableList.of("postDependentInstance", "preDependentInstance")); }
@Test public void testNoPreDestroy() throws Exception { Injector injector = Guice.createInjector( Stage.PRODUCTION, new LifeCycleModule(), new Module() { @Override public void configure(Binder binder) { binder.bind(PostConstructOnly.class).in(Scopes.SINGLETON); binder.bind(PreDestroyOnly.class).in(Scopes.SINGLETON); } }); injector.getInstance(PostConstructOnly.class); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); Assert.assertEquals(stateLog, ImmutableList.of("makeMe")); lifeCycleManager.destroy(); Assert.assertEquals(stateLog, ImmutableList.of("makeMe", "unmakeMe")); }
@Override protected Injector getInjector() { /** * This is called by super's contextInitialized. * * Must be created here in order for the modules to be initialized * correctly. */ if (this.injectorSupport == null) { this.injectorSupport = new InjectorSupport( new Module[]{ new AppTestModule(), new ServletTestModule() }, Stage.DEVELOPMENT); } return this.injectorSupport.getInjector(); }
@Override public void contextInitialized(ServletContextEvent sce) { /* * TODO switch to production */ injector = Guice.createInjector(Stage.DEVELOPMENT, new DevelopersSharedModule(), new DevelopersSharedServletModule(), new BackendServletModule()); logger.info("created injector"); super.contextInitialized(sce); return; }
public void testCorrectStage() { final Stage stage = Stage.PRODUCTION; Module module = Modules.override(new AbstractModule() { @Override protected void configure() { if (currentStage() != Stage.PRODUCTION) { addError("Wronge stage in overridden module:" + currentStage()); } } }).with(new AbstractModule() { @Override protected void configure() { if (currentStage() != Stage.PRODUCTION) { addError("Wronge stage in overriding module:" + currentStage()); } } }); Guice.createInjector(stage, module); }
InjectorOptions getOptions(Stage stage, InjectorOptions parentOptions) { checkNotNull(stage, "stage must be set"); if(parentOptions == null) { return new InjectorOptions( stage, jitDisabled, disableCircularProxies, atInjectRequired, exactBindingAnnotationsRequired); } else { checkState(stage == parentOptions.stage, "child & parent stage don't match"); return new InjectorOptions( stage, jitDisabled || parentOptions.jitDisabled, disableCircularProxies || parentOptions.disableCircularProxies, atInjectRequired || parentOptions.atInjectRequired, exactBindingAnnotationsRequired || parentOptions.exactBindingAnnotationsRequired); } }
ServletSpiVisitor(boolean forInjector) { ImmutableSet.Builder<Class> builder = ImmutableSet.builder(); // always ignore these things... builder.add( ServletRequest.class, ServletResponse.class, ManagedFilterPipeline.class, ManagedServletPipeline.class, FilterPipeline.class, ServletContext.class, HttpServletRequest.class, Filter.class, HttpServletResponse.class, HttpSession.class, Map.class, HttpServlet.class, InternalServletModule.BackwardsCompatibleServletContextProvider.class, GuiceFilter.class); if (forInjector) { // only ignore these if this is for the live injector, any other time it'd be an error! builder.add(Injector.class, Stage.class, Logger.class); } this.allowedClasses = builder.build(); }
public static void main(String[] args) throws Exception { // TODO(phopkins): Switch to Stage.TOOL when issue 297 is fixed. Injector demoInjector = Guice.createInjector( Stage.DEVELOPMENT, new BackToTheFutureModule(), new MultibinderModule(), new PrivateTestModule()); PrintWriter out = new PrintWriter(new File(args[0]), "UTF-8"); Injector injector = Guice.createInjector(new GraphvizModule()); GraphvizGrapher grapher = injector.getInstance(GraphvizGrapher.class); grapher.setOut(out); grapher.setRankdir("TB"); grapher.graph(demoInjector); }
public void testFactoryFailsWithMissingBindingInToolStage() { try { Guice.createInjector( Stage.TOOL, new AbstractModule() { @Override protected void configure() { bind(ColoredCarFactory.class) .toProvider(FactoryProvider.newFactory(ColoredCarFactory.class, Mustang.class)); } }); fail(); } catch (CreationException expected) { assertContains( expected.getMessage(), "Could not find a suitable constructor in java.lang.Double.", "at " + ColoredCarFactory.class.getName() + ".create(FactoryProvider2Test.java"); } }
private RecordingBinder(Stage stage) { this.stage = stage; this.modules = Maps.newLinkedHashMap(); this.scanners = Sets.newLinkedHashSet(); this.elements = Lists.newArrayList(); this.source = null; this.sourceProvider = SourceProvider.DEFAULT_INSTANCE.plusSkippedClasses( Elements.class, RecordingBinder.class, AbstractModule.class, ConstantBindingBuilderImpl.class, AbstractBindingBuilder.class, BindingBuilder.class); this.parent = null; this.privateElements = null; this.privateBinders = Lists.newArrayList(); }
public Injector build() { if (shellBuilder == null) { throw new AssertionError("Already built, builders are not reusable."); } // Synchronize while we're building up the bindings and other injector state. This ensures that // the JIT bindings in the parent injector don't change while we're being built synchronized (shellBuilder.lock()) { shells = shellBuilder.build(initializer, bindingData, stopwatch, errors); stopwatch.resetAndLog("Injector construction"); initializeStatically(); } injectDynamically(); if (shellBuilder.getStage() == Stage.TOOL) { // wrap the primaryInjector in a ToolStageInjector // to prevent non-tool-friendy methods from being called. return new ToolStageInjector(primaryInjector()); } else { return primaryInjector(); } }
/** * Inject everything that can be injected. This method is intentionally not synchronized. If we * locked while injecting members (ie. running user code), things would deadlock should the user * code build a just-in-time binding from another thread. */ private void injectDynamically() { injectionRequestProcessor.injectMembers(); stopwatch.resetAndLog("Static member injection"); initializer.injectAll(errors); stopwatch.resetAndLog("Instance injection"); errors.throwCreationExceptionIfErrorsExist(); if (shellBuilder.getStage() != Stage.TOOL) { for (InjectorShell shell : shells) { loadEagerSingletons(shell.getInjector(), shellBuilder.getStage(), errors); } stopwatch.resetAndLog("Preloading singletons"); } errors.throwCreationExceptionIfErrorsExist(); }
InjectorOptions getOptions(Stage stage, InjectorOptions parentOptions) { checkNotNull(stage, "stage must be set"); if (parentOptions == null) { return new InjectorOptions( stage, jitDisabled, disableCircularProxies, atInjectRequired, exactBindingAnnotationsRequired); } else { checkState(stage == parentOptions.stage, "child & parent stage don't match"); return new InjectorOptions( stage, jitDisabled || parentOptions.jitDisabled, disableCircularProxies || parentOptions.disableCircularProxies, atInjectRequired || parentOptions.atInjectRequired, exactBindingAnnotationsRequired || parentOptions.exactBindingAnnotationsRequired); } }
void injectMembers() { InternalContext context = injector.enterContext(); try { boolean isStageTool = injector.options.stage == Stage.TOOL; for (SingleMemberInjector memberInjector : memberInjectors) { // Run injections if we're not in tool stage (ie, PRODUCTION or DEV), // or if we are in tool stage and the injection point is toolable. if (!isStageTool || memberInjector.getInjectionPoint().isToolable()) { try { memberInjector.inject(context, null); } catch (InternalProvisionException e) { errors.merge(e); } } } } finally { context.close(); } }
public void testToolStageDoesntInjectInstances() { final Foo foo = new Foo(); Guice.createInjector( Stage.TOOL, new AbstractModule() { @Override protected void configure() { requestStaticInjection(Foo.class); requestInjection(foo); } }); assertNull(Foo.s); assertNull(Foo.sm); assertNull(foo.f); assertNull(foo.m); }
public void testToolStageDoesntInjectProviders() { final Foo foo = new Foo(); Guice.createInjector( Stage.TOOL, new AbstractModule() { @Override protected void configure() { requestStaticInjection(Foo.class); bind(Object.class).toProvider(foo); } }); assertNull(Foo.s); assertNull(Foo.sm); assertNull(foo.f); assertNull(foo.m); }
public void testToolStageWarnsOfMissingObjectGraph() { final Bar bar = new Bar(); try { Guice.createInjector( Stage.TOOL, new AbstractModule() { @Override protected void configure() { requestStaticInjection(Bar.class); requestInjection(bar); } }); fail("expected exception"); } catch (CreationException expected) { Asserts.assertContains( expected.toString(), "No implementation for java.util.Collection was bound.", "No implementation for java.util.Map was bound.", "No implementation for java.util.List was bound.", "No implementation for java.util.Set was bound."); } }
public void testToolStageInjectsTooledMethods() { final Tooled tooled = new Tooled(); Guice.createInjector( Stage.TOOL, new AbstractModule() { @Override protected void configure() { requestStaticInjection(Tooled.class); bind(Object.class).toProvider(tooled); } }); assertNull(Tooled.s); assertNotNull(Tooled.sm); assertNull(tooled.f); assertNotNull(tooled.m); }
public void testCorrectStage() { final Stage stage = Stage.PRODUCTION; Module module = Modules.override( new AbstractModule() { @Override protected void configure() { if (currentStage() != Stage.PRODUCTION) { addError("Wronge stage in overridden module:" + currentStage()); } } }) .with( new AbstractModule() { @Override protected void configure() { if (currentStage() != Stage.PRODUCTION) { addError("Wronge stage in overriding module:" + currentStage()); } } }); Guice.createInjector(stage, module); }
void injectMembers() { try { injector.callInContext(new ContextualCallable<Void>() { public Void call(InternalContext context) { for (SingleMemberInjector memberInjector : memberInjectors) { // Run injections if we're not in tool stage (ie, PRODUCTION or DEV), // or if we are in tool stage and the injection point is toolable. if(injector.options.stage != Stage.TOOL || memberInjector.getInjectionPoint().isToolable()) { memberInjector.inject(errors, context, null); } } return null; } }); } catch (ErrorsException e) { throw new AssertionError(); } }
@Before public void setUp() throws Exception { Injector inj = Guice.createInjector( Stage.PRODUCTION, new CuratorModule(new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith(Names.named("Cultivar.Curator.baseNamespace")).to("dev/test"); bind(EnsembleProvider.class).annotatedWith(Curator.class).toInstance( new FixedEnsembleProvider(testingCluster.getConnectString())); bind(RetryPolicy.class).annotatedWith(Curator.class).toInstance( new ExponentialBackoffRetry(10, 10)); } }), NamespaceModuleBuilder.create().newNamespace(null).targetAnnotation(Cultivar.class).build(), NamespaceModuleBuilder.create().newNamespace("foo").targetAnnotation(Names.named("foo")).build()); manager = inj.getInstance(CultivarStartStopManager.class); namespacedNullFramework = inj.getInstance(Key.get(CuratorFramework.class, Cultivar.class)); namespacedFooFramework = inj.getInstance(Key.get(CuratorFramework.class, Names.named("foo"))); manager.startAsync().awaitRunning(); }
public void testToolStageWarnsOfMissingObjectGraph() { final Bar bar = new Bar(); try { Guice.createInjector(Stage.TOOL, new AbstractModule() { @Override protected void configure() { requestStaticInjection(Bar.class); requestInjection(bar); } }); fail("expected exception"); } catch(CreationException expected) { Asserts.assertContains(expected.toString(), "No implementation for java.util.Collection was bound.", "No implementation for java.util.Map was bound.", "No implementation for java.util.List was bound.", "No implementation for java.util.Set was bound."); } }
@Test public void getInstance_NodeContainerWithAnnotation_PropertyOverrideSetAfter_ReturnsDefaultNodeContainer() { Module module = NodeContainerModuleBuilder.create(String.class).annotation(Curator.class) .mapper(StringUTF8ByteArrayMapper.class).overrideProperty("foo").path("/dev/test").build(); injector = Guice.createInjector(Stage.PRODUCTION, new AbstractModule() { @Override protected void configure() { bind(CuratorFramework.class).annotatedWith(Curator.class).toInstance(framework); } }, module); PropertyReader.setProperties(ImmutableMap.of("foo", "foo")); assertTrue(injector.getInstance(Key.get(Types.newParameterizedType(NodeContainer.class, String.class), Curator.class)) instanceof DefaultNodeContainer); }
@Test public void getInstance_NodeContainerWithAnnotation_PropertyOverrideSetBefore_ReturnsPropertyOverrideNodeContainer() { PropertyReader.setProperties(ImmutableMap.of("foo", "foo")); Module module = NodeContainerModuleBuilder.create(String.class).annotation(Curator.class) .mapper(StringUTF8ByteArrayMapper.class).overrideProperty("foo").path("/dev/test").build(); injector = Guice.createInjector(Stage.PRODUCTION, new AbstractModule() { @Override protected void configure() { bind(CuratorFramework.class).annotatedWith(Curator.class).toInstance(framework); } }, module); assertTrue(injector.getInstance(Key.get(Types.newParameterizedType(NodeContainer.class, String.class), Curator.class)) instanceof PropertyOverrideNodeContainer); }
/** We just want to make sure that mapbinder's binding depends on the underlying multibinder. */ public void testMultibinderDependenciesInToolStage() { Injector injector = Guice.createInjector(Stage.TOOL, new AbstractModule() { protected void configure() { MapBinder<Integer, String> mapBinder = MapBinder.newMapBinder(binder(), Integer.class, String.class); mapBinder.addBinding(1).toInstance("A"); mapBinder.addBinding(2).to(Key.get(String.class, Names.named("b"))); bindConstant().annotatedWith(Names.named("b")).to("B"); }}); Binding<Map<Integer, String>> binding = injector.getBinding(new Key<Map<Integer, String>>() {}); HasDependencies withDependencies = (HasDependencies) binding; Key<?> setKey = new Key<Set<Map.Entry<Integer, Provider<String>>>>() {}; assertEquals(ImmutableSet.<Dependency<?>>of(Dependency.get(setKey)), withDependencies.getDependencies()); }