Java Code Examples for com.google.inject.Stage

The following are top voted examples for showing how to use com.google.inject.Stage. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ProjectAres   File: UtilCoreManifest.java   Source Code and License 7 votes vote down vote up
@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());
    }
}
 
Example 2
Project: datarouter   File: GuiceStageFinder.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 3
Project: StopCozi-api   File: Server.java   Source Code and License 6 votes vote down vote up
@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)
        )
    );
}
 
Example 4
Project: Mastering-Mesos   File: SingularityExecutorCleanupRunner.java   Source Code and License 6 votes vote down vote up
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);
  }
}
 
Example 5
Project: Mastering-Mesos   File: SingularityExecutorRunner.java   Source Code and License 6 votes vote down vote up
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);
  }
}
 
Example 6
Project: dropwizard-microservices-example   File: ProductCatalogApplication.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 7
Project: dropwizard-microservices-example   File: ProductReviewApplication.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 8
Project: J-Kinopoisk2IMDB   File: Client.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 9
Project: guacamole-client   File: GuacamoleServletContextListener.java   Source Code and License 6 votes vote down vote up
@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;

}
 
Example 10
Project: europa   File: Europa.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 11
Project: salta   File: GuiceModule.java   Source Code and License 6 votes vote down vote up
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();
        }

    });
}
 
Example 12
Project: guice-bootstrap   File: TestLifeCycleManager.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 13
Project: guice-bootstrap   File: TestLifeCycleManager.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 14
Project: guice-bootstrap   File: TestLifeCycleManager.java   Source Code and License 6 votes vote down vote up
@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
    }
}
 
Example 15
Project: guice-bootstrap   File: TestLifeCycleManager.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 16
Project: guice-bootstrap   File: TestLifeCycleManager.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 17
Project: guice-bootstrap   File: TestLifeCycleManager.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 18
Project: eureka   File: ContextTestListener.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 19
Project: HotswapAgentExamples   File: BackendStartupListener.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 20
Project: guice-old   File: OverrideModuleTest.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 21
Project: guice-old   File: InjectorOptionsProcessor.java   Source Code and License 6 votes vote down vote up
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);
  }
}
 
Example 22
Project: guice   File: ServletSpiVisitor.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 23
Project: guice   File: InjectorGrapherDemo.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 24
Project: guice   File: FactoryProvider2Test.java   Source Code and License 6 votes vote down vote up
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");
  }
}
 
Example 25
Project: guice   File: Elements.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 26
Project: guice   File: InternalInjectorCreator.java   Source Code and License 6 votes vote down vote up
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();
  }
}
 
Example 27
Project: guice   File: InternalInjectorCreator.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 28
Project: guice   File: InjectorOptionsProcessor.java   Source Code and License 6 votes vote down vote up
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);
  }
}
 
Example 29
Project: guice   File: InjectionRequestProcessor.java   Source Code and License 6 votes vote down vote up
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();
  }
}
 
Example 30
Project: guice   File: ToolStageInjectorTest.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 31
Project: guice   File: ToolStageInjectorTest.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 32
Project: guice   File: ToolStageInjectorTest.java   Source Code and License 6 votes vote down vote up
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.");
  }
}
 
Example 33
Project: guice   File: ToolStageInjectorTest.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 34
Project: guice   File: OverrideModuleTest.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 35
Project: guice-old   File: InjectionRequestProcessor.java   Source Code and License 6 votes vote down vote up
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();
  }
}
 
Example 36
Project: cultivar   File: NamespaceModuleBuilderIntegTest.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 37
Project: guice-old   File: ToolStageInjectorTest.java   Source Code and License 6 votes vote down vote up
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.");
  }
}
 
Example 38
Project: cultivar   File: NodeContainerModuleBuilderTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 39
Project: cultivar   File: NodeContainerModuleBuilderTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 40
Project: guice-old   File: MapBinderTest.java   Source Code and License 6 votes vote down vote up
/** 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());
}
 
Example 41
Project: guice-old   File: InternalInjectorCreator.java   Source Code and License 6 votes vote down vote up
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();
  }
}
 
Example 42
Project: guice-old   File: InternalInjectorCreator.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 43
Project: Re-Collector   File: CollectorInjector.java   Source Code and License 5 votes vote down vote up
public static Injector createInjector(Module... modules) {
    final Injector injector = Guice.createInjector(Stage.PRODUCTION, new CollectorModule() {
        @Override
        protected void configure() {
            binder().requireExplicitBindings();
        }
    });

    return injector.createChildInjector(modules);
}
 
Example 44
Project: NoraUi   File: NoraUiInjectorSource.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Injector getInjector() {
    Injector injector = Guice.createInjector(Stage.PRODUCTION, CucumberModules.SCENARIO, new SpeedRegulatorModule(), new TimeModule(), new NoraUiModule());
    try {
        NoraUiInjector.createInjector(injector);
    } catch (TechnicalException e) {
        logger.error("error NoraUiInjectorSource.getInjector()", e);
    }
    return injector;
}
 
Example 45
Project: java8-jersey2-guice4-webapp   File: AppServletContextListener.java   Source Code and License 5 votes vote down vote up
@Override
protected Injector getInjector() {
  Injector injector = Guice.createInjector(
    Stage.PRODUCTION,
    new JerseyGuiceModule("__HK2_Generated_0"),
    new ServletModule(),
    new AppModule()
  );

  JerseyGuiceUtils.install(injector);

  return injector;
}
 
Example 46
Project: java8-jersey2-guice4-webapp-archetype   File: AppServletContextListener.java   Source Code and License 5 votes vote down vote up
@Override
protected Injector getInjector() {
  Injector injector = Guice.createInjector(
    Stage.PRODUCTION,
    new JerseyGuiceModule("__HK2_Generated_0"),
    new ServletModule(),
    new AppModule()
  );

  JerseyGuiceUtils.install(injector);

  return injector;
}
 
Example 47
Project: parabuild-ci   File: DwrGuiceServletContextListener.java   Source Code and License 5 votes vote down vote up
public void contextInitialized(ServletContextEvent servletContextEvent)
{
    ServletContext servletContext = servletContextEvent.getServletContext();
    pushServletContext(servletContext);
    try
    {
        Stage stage = getStage();
        Injector injector = Guice.createInjector(stage, this);
        publishInjector(servletContext, injector);
    }
    finally
    {
        popServletContext();
    }
}
 
Example 48
Project: parabuild-ci   File: DwrGuiceServletContextListener.java   Source Code and License 5 votes vote down vote up
/**
 * Override this method to specify which stage to run Guice in.
 * Default behavior is to look first in user preferences and then
 * in system preferences for node "org/directwebremoting/guice"
 * with a value for key "stage". If not found, the default is
 * Stage.PRODUCTION.
 */
protected Stage getStage()
{
    Stage stage = Stage.PRODUCTION;

    try
    {
        Preferences userNode = Preferences.userNodeForPackage(PACKAGE);
        String userStage = userNode.get(STAGE_KEY, null);
        if (userStage != null)
        {
            stage = Stage.valueOf(userStage);
        }
        else
        {
            Preferences systemNode = Preferences.systemNodeForPackage(PACKAGE);
            String systemStage = systemNode.get(STAGE_KEY, null);
            if (systemStage != null)
            {
                stage = Stage.valueOf(systemStage);
            }
        }
    }
    catch (Exception e)
    {
        // ignore errors reading Preferences
    }

    return stage;
}
 
Example 49
Project: dwr   File: DwrGuiceServletContextListener.java   Source Code and License 5 votes vote down vote up
/**
 * Override this method to specify which stage to run Guice in.
 * Default behavior is to look first in user preferences and then
 * in system preferences for node "org/directwebremoting/guice"
 * with a value for key "stage". If not found, the default is
 * Stage.PRODUCTION.
 */
protected Stage getStage()
{
    Stage stage = Stage.PRODUCTION;

    try
    {
        Preferences userNode = Preferences.userNodeForPackage(PACKAGE);
        String userStage = userNode.get(STAGE_KEY, null);
        if (userStage != null)
        {
            stage = Stage.valueOf(userStage);
        }
        else
        {
            Preferences systemNode = Preferences.systemNodeForPackage(PACKAGE);
            String systemStage = systemNode.get(STAGE_KEY, null);
            if (systemStage != null)
            {
                stage = Stage.valueOf(systemStage);
            }
        }
    }
    catch (Exception e)
    {
        // ignore errors reading Preferences
    }

    return stage;
}
 
Example 50
Project: Mastering-Mesos   File: SingularityClientModuleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testModuleWithHosts() {
  final Injector injector = Guice.createInjector(Stage.PRODUCTION,
      new GuiceDisableModule(),
      new SingularityClientModule(Collections.singletonList("http://example.com")));

  injector.injectMembers(this);
}
 
Example 51
Project: Mastering-Mesos   File: SingularityRunner.java   Source Code and License 5 votes vote down vote up
@SuppressFBWarnings("DM_EXIT")
public void run(Iterable<? extends Module> modules) {
  final Injector injector = Guice.createInjector(Stage.PRODUCTION, modules);

  final SingularityRunnerExceptionNotifier exceptionNotifier = injector.getInstance(SingularityRunnerExceptionNotifier.class);

  final SingularityDriver driver = injector.getInstance(SingularityDriver.class);

  Runtime.getRuntime().addShutdownHook(new Thread("SingularityRunnerGracefulShutdown") {

    @Override
    public void run() {
      driver.shutdown();
    }

  });

  try {
    driver.startAndWait();

    LOG.info("Exiting normally");

    System.exit(0);
  } catch (MissingConfigException mce) {
    LOG.error("Missing required configuration, exiting", mce);
    System.exit(1);
  } catch (Throwable t) {
    LOG.error("Caught unexpected exception, exiting", t);
    exceptionNotifier.notify(t, Collections.<String, String>emptyMap());
    System.exit(1);
  }

}
 
Example 52
Project: restlet-framework   File: RestletGuice.java   Source Code and License 5 votes vote down vote up
private static Injector injectorFor(Stage stage, Module rootModule) {
    if (stage == null) {
        return Guice.createInjector(rootModule);
    } else {
        return Guice.createInjector(stage, rootModule);
    }
}
 
Example 53
Project: walkaround   File: GuiceSetup.java   Source Code and License 5 votes vote down vote up
public static Injector getInjectorForTaskQueueTask() {
  return Guice.createInjector(
      // Stage.DEVELOPMENT here because this is meant to be called from
      // mappers, possibly for each invocation, and the mappers probably won't
      // need all singletons.
      Stage.DEVELOPMENT,
      getRootModule(),
      getTaskQueueTaskModule());
}
 
Example 54
Project: walkaround   File: ServletConfig.java   Source Code and License 5 votes vote down vote up
@Override
protected Injector getInjector() {
  return Guice.createInjector(
      // We use Stage.DEVELOPMENT to make start-up faster on App Engine.  We
      // have a test (GuiceSetupTest) that uses Stage.PRODUCTION to find
      // errors.  TODO(ohler): Find out if Stage.PRODUCTION combined with
      // warmup requests is better.
      Stage.DEVELOPMENT,
      GuiceSetup.getRootModule(),
      GuiceSetup.getServletModule());
}
 
Example 55
Project: walkaround   File: GuiceSetupTest.java   Source Code and License 5 votes vote down vote up
public void testBindingsForServlets() {
  SystemProperty.environment.set(SystemProperty.Environment.Value.Development);
  // The test is that none of this throws any exceptions.
  Guice.createInjector(Stage.PRODUCTION,
      Modules.combine(
          GuiceSetup.getRootModule(WEB_INF_DIR),
          GuiceSetup.getServletModule(),
          new DefaultModule()));
  // TODO(ohler): Figure out how to set up a fake request scope and reinstate this.
  //for (Class<?> handlerClass : WalkaroundServletModule.HANDLER_MAP.values()) {
  //  injector.getInstance(handlerClass);
  //}
}
 
Example 56
Project: walkaround   File: GuiceSetupTest.java   Source Code and License 5 votes vote down vote up
public void testBindingsForTaskQueueTask() {
  SystemProperty.environment.set(SystemProperty.Environment.Value.Development);
  // The test is that none of this throws any exceptions.
  Guice.createInjector(Stage.PRODUCTION,
      Modules.combine(
          GuiceSetup.getRootModule(WEB_INF_DIR),
          GuiceSetup.getTaskQueueTaskModule(),
          new DefaultModule()));
}
 
Example 57
Project: dropwizard-microservices-example   File: APIGatewayApplication.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize(final Bootstrap<APIGatewayConfiguration> bootstrap) {
	bootstrap.addBundle(discoveryBundle);
	guiceBundle = GuiceBundle.<APIGatewayConfiguration> newBuilder().addModule(new APIGatewayModule())
			.enableAutoConfig(getClass().getPackage().getName()).setConfigClass(APIGatewayConfiguration.class)
			.build(Stage.PRODUCTION);
	bootstrap.addBundle(guiceBundle);
	// Uncomment below to read the yaml file from Jar
	// bootstrap.setConfigurationSourceProvider(new
	// ResourceConfigurationSourceProvider());
}
 
Example 58
Project: biomedicus   File: Bootstrapper.java   Source Code and License 5 votes vote down vote up
private Application biomedicus() {
  Injector biomedicusInjector;
  if (injector != null) {
    biomedicusInjector = injector.createChildInjector(modules);
  } else {
    biomedicusInjector = Guice
        .createInjector(Stage.PRODUCTION, modules);
  }

  return biomedicusInjector.getInstance(Application.class);
}
 
Example 59
Project: europa   File: TestECRClient.java   Source Code and License 5 votes vote down vote up
@Before
public void beforeTest()
{
    String testName = name.getMethodName();
    String prefix = "Running Test: ";
    char[] line = new char[prefix.length()+testName.length()];
    Arrays.fill(line, '=');
    System.out.println();
    System.out.println(line);
    System.out.println(prefix+name.getMethodName());
    System.out.println(line);
    Guice.createInjector(Stage.PRODUCTION,
                         new EuropaTestModule())
    .injectMembers(this);
}
 
Example 60
Project: vertx-sisu   File: SimpleInjectorFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Injector injectorFor(final ClassLoader classLoader, final Iterable<Module> modules)
{
  return Guice.createInjector(
      Stage.DEVELOPMENT,
      new WireModule(
          new AbstractModule() // params
          {
            @Override
            protected void configure() {
              bind(Vertx.class).toInstance(vertx);
              bind(EventBus.class).toInstance(vertx.eventBus());
              if (parameters != null) {
                bind(ParameterKeys.PROPERTIES).toInstance(parameters);
              }
              if (bootstrapModules != null) {
                for (Module bootstrapModule : bootstrapModules) {
                  install(bootstrapModule);
                }
              }
              for (Module module : modules) {
                install(module);
              }
            }
          },
          new SpaceModule( // space module
              new URLClassSpace(classLoader), BeanScanning.INDEX
          )
      )
  );
}