Java 类com.google.inject.Stage 实例源码

项目:ProjectAres    文件:UtilCoreManifest.java   
@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());
    }
}
项目:datarouter    文件:GuiceStageFinder.java   
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;
}
项目:StopCozi-api    文件:Server.java   
@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)
        )
    );
}
项目:Mastering-Mesos    文件:SingularityExecutorCleanupRunner.java   
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);
  }
}
项目:Mastering-Mesos    文件:SingularityExecutorRunner.java   
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);
  }
}
项目:dropwizard-microservices-example    文件:ProductCatalogApplication.java   
@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());
}
项目:dropwizard-microservices-example    文件:ProductReviewApplication.java   
@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());
}
项目:J-Kinopoisk2IMDB    文件:Client.java   
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);
}
项目:guacamole-client    文件:GuacamoleServletContextListener.java   
@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;

}
项目:europa    文件:Europa.java   
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);
}
项目:salta    文件:GuiceModule.java   
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();
        }

    });
}
项目:guice-bootstrap    文件:TestLifeCycleManager.java   
@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"));
}
项目:guice-bootstrap    文件:TestLifeCycleManager.java   
@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"));
}
项目:guice-bootstrap    文件:TestLifeCycleManager.java   
@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
    }
}
项目:guice-bootstrap    文件:TestLifeCycleManager.java   
@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"));
}
项目:guice-bootstrap    文件:TestLifeCycleManager.java   
@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"));
}
项目:guice-bootstrap    文件:TestLifeCycleManager.java   
@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"));
}
项目:eureka    文件:ContextTestListener.java   
@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();
}
项目:HotswapAgentExamples    文件:BackendStartupListener.java   
@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;
}
项目:guice-old    文件:OverrideModuleTest.java   
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);
}
项目:guice-old    文件:InjectorOptionsProcessor.java   
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);
  }
}
项目:guice    文件:ServletSpiVisitor.java   
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();
}
项目:guice    文件:InjectorGrapherDemo.java   
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);
}
项目:guice    文件:FactoryProvider2Test.java   
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");
  }
}
项目:guice    文件:Elements.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();
}
项目:guice    文件:InternalInjectorCreator.java   
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();
  }
}
项目:guice    文件:InternalInjectorCreator.java   
/**
 * 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();
}
项目:guice    文件:InjectorOptionsProcessor.java   
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);
  }
}
项目:guice    文件:InjectionRequestProcessor.java   
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();
  }
}
项目:guice    文件:ToolStageInjectorTest.java   
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);
}
项目:guice    文件:ToolStageInjectorTest.java   
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);
}
项目:guice    文件:ToolStageInjectorTest.java   
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.");
  }
}
项目:guice    文件:ToolStageInjectorTest.java   
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);
}
项目:guice    文件:OverrideModuleTest.java   
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);
}
项目:guice-old    文件:InjectionRequestProcessor.java   
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();
  }
}
项目:cultivar    文件:NamespaceModuleBuilderIntegTest.java   
@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();
}
项目:guice-old    文件:ToolStageInjectorTest.java   
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.");
  }
}
项目:cultivar    文件:NodeContainerModuleBuilderTest.java   
@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);
}
项目:cultivar    文件:NodeContainerModuleBuilderTest.java   
@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);
}
项目:guice-old    文件:MapBinderTest.java   
/** 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());
}