Java Code Examples for com.google.inject.Module

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project airlift, under directory /bootstrap/src/test/java/io/airlift/bootstrap/.

Source file: TestLifeCycleManager.java

  22 
vote

@Test public void testImmediateStarts() throws Exception {
  Module module=new Module(){
    @Override public void configure(    Binder binder){
      binder.bind(InstanceThatRequiresStart.class).in(Scopes.SINGLETON);
      binder.bind(InstanceThatUsesInstanceThatRequiresStart.class).in(Scopes.SINGLETON);
    }
  }
;
  Injector injector=Guice.createInjector(Stage.PRODUCTION,new LifeCycleModule(),module);
  LifeCycleManager lifeCycleManager=injector.getInstance(LifeCycleManager.class);
  lifeCycleManager.start();
  Assert.assertEquals(stateLog,Arrays.asList("InstanceThatUsesInstanceThatRequiresStart:OK"));
}
 

Example 2

From project eclipse-task-editor, under directory /plugins/de.sebastianbenz.task.ui/src-gen/de/sebastianbenz/task/ui/internal/.

Source file: TaskActivator.java

  22 
vote

protected Injector createInjector(String language){
  try {
    Module runtimeModule=getRuntimeModule(language);
    Module sharedStateModule=getSharedStateModule();
    Module uiModule=getUiModule(language);
    Module mergedModule=Modules2.mixin(runtimeModule,sharedStateModule,uiModule);
    return Guice.createInjector(mergedModule);
  }
 catch (  Exception e) {
    logger.error("Failed to create injector for " + language);
    logger.error(e.getMessage(),e);
    throw new RuntimeException("Failed to create injector for " + language,e);
  }
}
 

Example 3

From project ElasticSearchExample, under directory /src/main/java/de/jetwick/ese/search/.

Source file: Feeding.java

  22 
vote

public void start(boolean fake){
  Module module=new DefaultModule();
  Injector injector=Guice.createInjector(module);
  MySearch tws=injector.getInstance(MySearch.class);
  Collection<MyTweet> tweets;
  if (fake)   tweets=createFake();
 else   tweets=createReal();
  logger.info("Now feeding");
  StopWatch sw=new StopWatch().start();
  tws.bulkUpdate(tweets,tws.getIndexName());
  long time=sw.stop().totalTime().seconds();
  if (time == 0)   time=1;
  logger.info("Feeded " + tweets.size() + " users => "+ tweets.size() / time + " users/sec");
}
 

Example 4

From project guice-jit-providers, under directory /core/test/com/google/inject/spi/.

Source file: ProviderMethodsTest.java

  22 
vote

/** 
 * If the user installs provider methods for the module manually, that shouldn't cause a double binding of the provider methods' types.
 */
public void testAutomaticProviderMethodsDoNotCauseDoubleBinding(){
  Module installsSelf=new AbstractModule(){
    protected void configure(){
      install(this);
      bind(Integer.class).toInstance(5);
    }
    @Provides public String provideString(    Integer count){
      return "A" + count;
    }
  }
;
  Injector injector=Guice.createInjector(installsSelf);
  assertEquals("A5",injector.getInstance(String.class));
}
 

Example 5

From project components-ness-httpserver_1, under directory /src/main/java/com/nesscomputing/httpserver/standalone/.

Source file: StandaloneServer.java

  21 
vote

/** 
 * Can be overridden in tests.
 */
public Module getPlumbingModules(final Config config){
  return new Module(){
    @Override public void configure(    final Binder binder){
      binder.install(new ConfigModule(config));
      binder.install(new JmxModule());
      binder.install(new JmxLoggingModule("server"));
      binder.install(getLifecycleModule());
      binder.bind(GuiceFilter.class).in(Scopes.SINGLETON);
      binder.install(new ServletModule());
    }
  }
;
}
 

Example 6

From project components-ness-integration-testing, under directory /src/main/java/com/nesscomputing/testing/.

Source file: IntegrationTestRuleBuilder.java

  21 
vote

/** 
 * Builds the rule so that JUnit may run it. If the testcase module requires the configuration object use  {@link IntegrationTestRuleBuilder#build(Object)} andinstall the module with <pre> addTweakedModule(TweakedModule.forTestModule(&lt;name or class or instance of test module&gt;)); </pre>
 * @param testCaseItself pass in the test case object so that Guice may perform field injection
 * @param testCaseModule any extra modules you would like injected into your test case
 * @return
 */
public IntegrationTestRule build(final Object testCaseItself,@Nonnull final Module testCaseModule){
  final Map<String,String> testCaseConfigTweaks=Maps.newHashMap();
  final Map<String,String> serviceConfigTweaks=Maps.newHashMap();
  for (  final TweakedModule tweakedModule : tweakedModules) {
    testCaseConfigTweaks.putAll(tweakedModule.getTestCaseConfigTweaks());
    serviceConfigTweaks.putAll(tweakedModule.getServiceConfigTweaks());
  }
  final Config testCaseConfig=Config.getOverriddenConfig(baseConfig,new MapConfiguration(testCaseConfigTweaks),new MapConfiguration(configKeys));
  final Module module=new Module(){
    @Override public void configure(    final Binder binder){
      for (      TweakedModule tweakedModule : tweakedModules) {
        binder.install(tweakedModule.getTestCaseModule(testCaseConfig));
      }
      binder.install(new ConfigModule(testCaseConfig));
      binder.install(testCaseModule);
    }
  }
;
  final Map<String,Module> serviceModules=Maps.newHashMap();
  addServiceDefinitions(serviceDefinitions,serviceConfigTweaks,serviceModules);
  addServiceModules(serviceTweakedModules,serviceConfigTweaks,serviceModules);
  return new IntegrationTestRule(serviceModules,startStage,stopStage,module,testCaseItself);
}
 

Example 7

From project components-ness-jdbi, under directory /src/test/java/com/nesscomputing/jdbi/metrics/.

Source file: TestDatabaseMetricsModule.java

  21 
vote

@Test public void testSimple(){
  final Injector inj=Guice.createInjector(Stage.PRODUCTION,new Module(){
    @Override public void configure(    final Binder binder){
      binder.requireExplicitBindings();
      binder.disableCircularProxies();
    }
  }
,new DatabaseMetricsModule(),new InstrumentationModule());
  inj.injectMembers(this);
  Assert.assertNotNull(tc);
  Assert.assertNull(durationUnit);
  Assert.assertNull(rateUnit);
}
 

Example 8

From project components-ness-jersey, under directory /jersey/src/test/java/com/nesscomputing/jersey/exceptions/.

Source file: TestGuiceProvisionExceptionMapper.java

  21 
vote

@Test public void testNullCauseMessage(){
  final Injector injector=Guice.createInjector(Stage.PRODUCTION,new Module(){
    @Override public void configure(    final Binder binder){
      binder.bind(GuiceProvisionExceptionMapper.class).asEagerSingleton();
    }
  }
);
  final GuiceProvisionExceptionMapper mapper=injector.getInstance(GuiceProvisionExceptionMapper.class);
  final Throwable cause=new NullPointerException();
  final ProvisionException pe=new ProvisionException("hello, world",cause);
  final Response response=mapper.toResponse(pe);
  Assert.assertNotNull(response);
}
 

Example 9

From project components-ness-jmx, under directory /src/test/java/com/nesscomputing/jmx/starter/guice/.

Source file: TestJmxExporterConfigProvider.java

  21 
vote

private void prepareGuice(final Config config,final Module... modules){
  final Injector inj=Guice.createInjector(Stage.PRODUCTION,new ConfigModule(config),new JmxStarterModule(config),new Module(){
    @Override public void configure(    final Binder binder){
      binder.disableCircularProxies();
      binder.requireExplicitBindings();
      binder.bind(MBeanServer.class).to(TestingMBeanServer.class).in(Scopes.SINGLETON);
      for (      final Module module : modules) {
        binder.install(module);
      }
    }
  }
);
  inj.injectMembers(this);
}
 

Example 10

From project components-ness-pg, under directory /pg/src/main/java/com/nesscomputing/db/postgres/.

Source file: PostgresController.java

  21 
vote

@Override public Module getGuiceModule(@Nonnull final String visibleDbName){
  return Modules.combine(getInternalModule(visibleDbName),new Module(){
    @Override public void configure(    final Binder binder){
      final Annotation annotation=Names.named(visibleDbName);
      binder.bind(IDBI.class).annotatedWith(annotation).toInstance(userDbi);
    }
  }
);
}
 

Example 11

From project components-ness-tracking, under directory /src/test/java/com/nesscomputing/tracking/.

Source file: AbstractTrackingTestCase.java

  21 
vote

protected Module getTestModule(){
  return new Module(){
    @Override public void configure(    Binder binder){
    }
  }
;
}
 

Example 12

From project components-ness-lifecycle, under directory /src/test/java/com/nesscomputing/lifecycle/guice/.

Source file: TestDelegatingLifecycleProvider.java

  20 
vote

@Test public void testLifecycleProviderClass(){
  final Map<LifecycleStage,CustomAction> actions=Maps.newHashMap();
  final LifecycleProvider<Foo> lcProvider=DelegatingLifecycleProvider.of(FooProvider.class);
  for (  LifecycleStage stage : stages) {
    final CustomAction action=new CustomAction();
    lcProvider.addAction(stage,action);
    actions.put(stage,action);
  }
  final Injector injector=Guice.createInjector(new Module(){
    @Override public void configure(    final Binder binder){
      binder.bind(Lifecycle.class).to(DefaultLifecycle.class).in(Scopes.SINGLETON);
      binder.bind(Foo.class).toProvider(lcProvider).in(Scopes.SINGLETON);
    }
  }
);
  final Lifecycle lifecycle=injector.getInstance(Lifecycle.class);
  final Foo foo=injector.getInstance(Foo.class);
  Assert.assertEquals(FOO,foo);
  lifecycle.executeTo(LifecycleStage.STOP_STAGE);
  Assert.assertEquals(stages.length,actions.size());
  for (  final Map.Entry<LifecycleStage,CustomAction> entry : actions.entrySet()) {
    Assert.assertEquals(1,entry.getValue().getCount());
  }
}
 

Example 13

From project gengweibo, under directory /src/com/gengweibo/web/.

Source file: GuiceInit.java

  20 
vote

public void init(ServletConfig config) throws ServletException {
  Injector injector=Guice.createInjector(new Module(){
    public void configure(    Binder binder){
      binder.bind(AccountAcction.class).in(Singleton.class);
      binder.bind(WeiboDao.class).to(WeiboDaoJdbcImpl.class).in(Singleton.class);
      binder.bind(DataSource.class).toProvider(C3P0Provider.class).in(Singleton.class);
      Properties properties=new Properties();
      try {
        properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("database.properties"));
      }
 catch (      IOException e) {
        throw new ExceptionInInitializerError(e);
      }
      Names.bindProperties(binder,properties);
    }
  }
);
  config.getServletContext().setAttribute(Injector.class.getName(),injector);
}
 

Example 14

From project agit, under directory /agit/src/main/java/com/madgag/agit/guice/.

Source file: OperationScope.java

  19 
vote

public static Module module(){
  return new AbstractModule(){
    public void configure(){
      OperationScope scope=new OperationScope();
      bindScope(OperationScoped.class,scope);
      bind(OperationScope.class).toInstance(scope);
      bind(GIT_OPERATION_KEY).toProvider(ScopeBase.<GitOperation>seededKeyProvider()).in(OperationScoped.class);
      bind(PROGRESS_LISTENER_KEY).toProvider(ScopeBase.<ProgressListener<Progress>>seededKeyProvider()).in(OperationScoped.class);
      bind(CancellationSignaller.class).to(GitOperation.class);
    }
  }
;
}
 

Example 15

From project Android, under directory /app/src/main/java/com/github/mobile/accounts/.

Source file: AccountScope.java

  19 
vote

/** 
 * Create new module
 * @return module
 */
public static Module module(){
  return new AbstractModule(){
    public void configure(){
      AccountScope scope=new AccountScope();
      bind(AccountScope.class).toInstance(scope);
      bind(GITHUB_ACCOUNT_KEY).toProvider(AccountScope.<GitHubAccount>seededKeyProvider()).in(scope);
    }
  }
;
}
 

Example 16

From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/.

Source file: Factory.java

  19 
vote

public Injector createInjector(SocketAddress address,Module... modules){
  List<Module> m=new ArrayList<>();
  m.add(new ArdverkModule(keySize,address));
  m.addAll(Arrays.asList(modules));
  return Guice.createInjector(m);
}
 

Example 17

From project Arecibo, under directory /alertmanager/src/main/java/com/ning/arecibo/alertmanager/guice/.

Source file: AlertManagerModule.java

  19 
vote

protected void installExtraModules(final AreciboAlertManagerConfig alertManagerConfigonfig){
  for (  final String guiceModule : alertManagerConfigonfig.getExtraGuiceModules().split(",")) {
    if (guiceModule.isEmpty()) {
      continue;
    }
    try {
      log.info("Installing extra module: " + guiceModule);
      install((Module)Class.forName(guiceModule).newInstance());
    }
 catch (    InstantiationException e) {
      log.warn("Ignoring module: " + guiceModule,e);
    }
catch (    IllegalAccessException e) {
      log.warn("Ignoring module: " + guiceModule,e);
    }
catch (    ClassNotFoundException e) {
      log.warn("Ignoring module: " + guiceModule,e);
    }
  }
}
 

Example 18

From project atunit, under directory /atunit-guice/src/main/java/atunit/guice/.

Source file: GuiceContainer.java

  19 
vote

public Object createTest(Class<?> testClass,Map<Field,Object> fieldValues) throws Exception {
  FieldModule fields=new FieldModule(fieldValues);
  Injector injector;
  if (Module.class.isAssignableFrom(testClass)) {
    injector=Guice.createInjector(fields,(Module)testClass.newInstance());
  }
 else {
    injector=Guice.createInjector(fields);
  }
  return injector.getInstance(testClass);
}
 

Example 19

From project atunit_1, under directory /src/atunit/guice/.

Source file: GuiceContainer.java

  19 
vote

public Object createTest(Class<?> testClass,Map<Field,Object> fieldValues) throws Exception {
  FieldModule fields=new FieldModule(fieldValues);
  Injector injector;
  if (Module.class.isAssignableFrom(testClass)) {
    injector=Guice.createInjector(fields,(Module)testClass.newInstance());
  }
 else {
    injector=Guice.createInjector(fields);
  }
  return injector.getInstance(testClass);
}
 

Example 20

From project candlepin, under directory /src/main/java/org/candlepin/guice/.

Source file: CandlepinContextListener.java

  19 
vote

/** 
 * Returns a list of Guice modules to initialize.
 * @return a list of Guice modules to initialize.
 */
protected List<Module> getModules(){
  List<Module> modules=new LinkedList<Module>();
  modules.add(Modules.override(new DefaultConfig()).with(new CustomizableModules().load()));
  modules.add(new CandlepinModule());
  modules.add(new CandlepinFilterModule());
  return modules;
}
 

Example 21

From project cdk, under directory /commons/src/test/java/org/richfaces/cdk/.

Source file: CdkTestRunner.java

  19 
vote

private Object createTest(Class<?> testClass,Map<Field,Binding> fieldValues) throws Exception {
  FieldModule fields=new FieldModule(fieldValues);
  Injector injector;
  Object test=super.createTest();
  if (Module.class.isAssignableFrom(testClass)) {
    injector=Guice.createInjector(fields,(Module)testClass.newInstance());
  }
 else {
    injector=Guice.createInjector(fields);
  }
  injector.injectMembers(test);
  return test;
}
 

Example 22

From project closure-templates, under directory /java/src/com/google/template/soy/.

Source file: MainClassUtils.java

  19 
vote

/** 
 * Creates a Guice injector that includes the SoyModule, a message plugin module, and maybe additional plugin modules.
 * @param msgPluginModuleName The full class name of the message plugin module. Required.
 * @param pluginModuleNames Comma-delimited list of full class names of additional plugin modulesto include. Optional.
 * @return A Guice injector that includes the SoyModule, the given message plugin module, and thegiven additional plugin modules (if any).
 */
public static Injector createInjector(String msgPluginModuleName,@Nullable String pluginModuleNames){
  List<Module> guiceModules=Lists.newArrayListWithCapacity(2);
  guiceModules.add(new SoyModule());
  checkArgument(msgPluginModuleName != null && msgPluginModuleName.length() > 0);
  guiceModules.add(instantiatePluginModule(msgPluginModuleName));
  if (pluginModuleNames != null && pluginModuleNames.length() > 0) {
    for (    String pluginModuleName : Splitter.on(',').split(pluginModuleNames)) {
      guiceModules.add(instantiatePluginModule(pluginModuleName));
    }
  }
  return Guice.createInjector(guiceModules);
}
 

Example 23

From project cloud-management, under directory /src/main/java/com/proofpoint/cloudmanagement/service/.

Source file: ConditionalModule.java

  19 
vote

private ConditionalModule(Module module,String property,String expectedValue){
  Preconditions.checkNotNull(module,"module is null");
  Preconditions.checkNotNull(property,"property is null");
  this.module=module;
  this.property=property;
  this.expectedValue=expectedValue;
}
 

Example 24

From project cloudify, under directory /cloudify/tools/maven-plugins/s3client-maven-plugin/src/main/java/com/gigaspaces/cloudify/s3client/.

Source file: S3PutMojo.java

  19 
vote

public void execute() throws MojoExecutionException, MojoFailureException {
  BlobStoreContext context=null;
  try {
    Set<Module> wiring=new HashSet<Module>();
    context=new BlobStoreContextFactory().createContext("aws-s3",user,key,wiring,new Properties());
    BlobStore store=context.getBlobStore();
    uploadFile(source,target,store);
  }
 catch (  Exception e) {
    throw new MojoFailureException("Failed put operation",e);
  }
 finally {
    if (context != null) {
      context.close();
    }
  }
}
 

Example 25

From project components-ness-jackson, under directory /src/test/java/com/nesscomputing/jackson/.

Source file: TestNessObjectMapperProvider.java

  19 
vote

private ObjectMapper getObjectMapper(final Module module){
  return getObjectMapper(module,new AbstractModule(){
    @Override protected void configure(){
    }
  }
);
}
 

Example 26

From project dimdwarf, under directory /dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/server/.

Source file: ApplicationLoader.java

  19 
vote

public Module newModuleInstance(){
  String clazz=applicationModule;
  try {
    return (Module)classLoader.loadClass(clazz).newInstance();
  }
 catch (  Exception e) {
    throw new RuntimeException("Unable to instantiate " + clazz,e);
  }
}
 

Example 27

From project edna-rcp, under directory /org.edna.datamodel.language.ui/src-gen/org/edna/datamodel/ui/internal/.

Source file: DatamodelActivator.java

  19 
vote

protected Module getRuntimeModule(String grammar){
  if ("org.edna.datamodel.Datamodel".equals(grammar)) {
    return new org.edna.datamodel.DatamodelRuntimeModule();
  }
  throw new IllegalArgumentException(grammar);
}
 

Example 28

From project EMF-IncQuery, under directory /plugins/org.eclipse.viatra2.patternlanguage.emf.ui/src/org/eclipse/viatra2/patternlanguage/ui/.

Source file: EMFPatternLanguageUIActivator.java

  19 
vote

@Override protected Module getRuntimeModule(String grammar){
  if (ORG_ECLIPSE_VIATRA2_PATTERNLANGUAGE_EMFPATTERNLANGUAGE.equals(grammar)) {
    return IncQueryGeneratorPlugin.INSTANCE.getRuntimeModule();
  }
  throw new IllegalArgumentException(grammar);
}
 

Example 29

From project Empire, under directory /core/src/com/clarkparsia/empire/.

Source file: Empire.java

  19 
vote

/** 
 * Initialize Empire with the given set of Guice Modules
 * @param theModules the modules to use with Empire
 */
public static void init(Collection<EmpireModule> theModules){
  mModules.clear();
  Collection<EmpireModule> aModules=new HashSet<EmpireModule>(theModules);
  if (aModules.isEmpty() || !find2(aModules,new FindDefaultEmpireModulePredicate())) {
    aModules.add(new DefaultEmpireModule());
  }
  for (  Module aModule : aModules) {
    mModules.put(aModule.getClass(),aModule);
  }
  injector=Guice.createInjector(mModules.values());
}
 

Example 30

From project grouperfish, under directory /service/src/main/java/com/mozilla/grouperfish/bootstrap/.

Source file: Grouperfish.java

  19 
vote

public Grouperfish(final Module... modules){
  SLF4JBridgeHandler.install();
  final Injector injector=Guice.createInjector(modules);
  final RestService rest=new JerseyGuiceRestService(injector,ResourceConfig.class);
  rest.start();
  log.info("Grouperfish started.");
  log.debug("Configured port: {}, default: {}",System.getProperty(JerseyGuiceRestService.PROPERTY_PORT),DEFAULT_PORT);
}
 

Example 31

From project guice-automatic-injection, under directory /core/src/main/java/de/devsurf/injection/guice/annotations/features/.

Source file: ModuleBindingFeature.java

  19 
vote

@Override public void process(final Class<Object> annotatedClass,Map<String,Annotation> annotations){
  BindingJob job=new ModuleBindingJob(annotatedClass.getName());
  if (!tracer.contains(job)) {
    if (_logger.isLoggable(Level.INFO)) {
      _logger.info("Installing Module: " + annotatedClass.getName());
    }
synchronized (_binder) {
      _binder.install((Module)injector.getInstance(annotatedClass));
    }
  }
 else {
    if (_logger.isLoggable(Level.FINE)) {
      _logger.log(Level.FINE,"Ignoring BindingJob \"" + job.toString() + "\", because it was already bound.",new Exception("Ignoring BindingJob \"" + job.toString() + "\", because it was already bound."));
    }
 else     if (_logger.isLoggable(Level.INFO)) {
      _logger.log(Level.INFO,"Ignoring BindingJob \"" + job.toString() + "\", because it was already bound.");
    }
  }
}