Java 类com.google.inject.multibindings.MapBinder 实例源码

项目:Re-Collector    文件:CollectorModule.java   
public void registerInput(String type,
                          Class<? extends Input> inputClass,
                          Class<? extends Input.Factory<? extends Input, ? extends InputConfiguration>> inputFactoryClass,
                          Class<? extends InputConfiguration> inputConfigurationClass,
                          Class<? extends InputConfiguration.Factory<? extends InputConfiguration>> inputConfigurationFactoryClass) {
    if (inputsMapBinder == null) {
        this.inputsMapBinder = MapBinder.newMapBinder(binder(),
                TypeLiteral.get(String.class),
                new TypeLiteral<InputConfiguration.Factory<? extends InputConfiguration>>() {
                });
    }

    install(new FactoryModuleBuilder().implement(Input.class, inputClass).build(inputFactoryClass));
    install(new FactoryModuleBuilder().implement(Configuration.class, inputConfigurationClass).build(inputConfigurationFactoryClass));

    inputsMapBinder.addBinding(type).to(inputConfigurationFactoryClass);
}
项目:Re-Collector    文件:CollectorModule.java   
public void registerOutput(String type,
                           Class<? extends Output> outputClass,
                           Class<? extends Output.Factory<? extends Output, ? extends OutputConfiguration>> outputFactoryClass,
                           Class<? extends OutputConfiguration> outputConfigurationClass,
                           Class<? extends OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigurationFactoryClass) {

    if (outputsMapBinder == null) {
        this.outputsMapBinder = MapBinder.newMapBinder(binder(),
                TypeLiteral.get(String.class),
                new TypeLiteral<OutputConfiguration.Factory<? extends OutputConfiguration>>() {
                });
    }

    install(new FactoryModuleBuilder().implement(Output.class, outputClass).build(outputFactoryClass));
    install(new FactoryModuleBuilder().implement(Configuration.class, outputConfigurationClass).build(outputConfigurationFactoryClass));

    outputsMapBinder.addBinding(type).to(outputConfigurationFactoryClass);
}
项目:tac-kbp-eal    文件:ScoreKBPAgainstERE.java   
@Override
protected void configure() {
  bind(Parameters.class).toInstance(params);
  // declare that people can provide scoring observer plugins, even though none are
  // provided by default
  MapBinder.newMapBinder(binder(), TypeLiteral.get(String.class),
      new TypeLiteral<ScoringEventObserver<DocLevelEventArg, DocLevelEventArg>>() {
      });
  try {
    bind(EREToKBPEventOntologyMapper.class)
        .toInstance(EREToKBPEventOntologyMapper.create2016Mapping());
  } catch (IOException ioe) {
    throw new TACKBPEALException(ioe);
  }
  install(new ResponsesAndLinkingFromEREExtractor.Module());
  install(new FactoryModuleBuilder()
      .build(ResponsesAndLinkingFromKBPExtractorFactory.class));
}
项目:ProjectAres    文件:TypeMapBinder.java   
public TypeMapBinder(Binder binder, @Nullable TypeLiteral<K> keyType, @Nullable TypeLiteral<V> valueType) {
    this.keyType = keyType != null ? keyType : new ResolvableType<K>(){}.in(getClass());
    this.valueType = valueType != null ? valueType : new ResolvableType<V>(){}.in(getClass());

    final TypeArgument<K> keyTypeArg = new TypeArgument<K>(this.keyType){};
    final TypeArgument<V> valueTypeArg = new TypeArgument<V>(this.valueType){};

    this.collectionKey = Key.get(new ResolvableType<TypeMap<K, V>>(){}.with(keyTypeArg, valueTypeArg));
    this.backingCollectionKey = Key.get(new ResolvableType<Map<TypeToken<? extends K>, Set<V>>>(){}.with(keyTypeArg, valueTypeArg));

    this.backingCollectionBinder = MapBinder.newMapBinder(
        binder,
        new ResolvableType<TypeToken<? extends K>>(){}.with(keyTypeArg),
        this.valueType
    ).permitDuplicates();

    binder.install(new KeyedManifest.Impl(collectionKey) {
        @Override
        public void configure() {
            final Provider<Map<TypeToken<? extends K>, Set<V>>> backingCollectionProvider = getProvider(backingCollectionKey);
            bind(collectionType()).toProvider(() -> ImmutableTypeMap.copyOf(backingCollectionProvider.get()));
        }
    });
}
项目:graylog-plugin-file-output    文件:FileOutputModule.java   
@Override
protected void configure() {
    /*
     * Register your plugin types here.
     *
     * Examples:
     *
     * addMessageInput(Class<? extends MessageInput>);
     * addMessageFilter(Class<? extends MessageFilter>);
     * addMessageOutput(Class<? extends MessageOutput>);
     * addPeriodical(Class<? extends Periodical>);
     * addAlarmCallback(Class<? extends AlarmCallback>);
     * addInitializer(Class<? extends Service>);
     * addRestResource(Class<? extends PluginRestResource>);
     *
     *
     * Add all configuration beans returned by getConfigBeans():
     *
     * addConfigBeans();
     */

    MapBinder<String, Factory<? extends MessageOutput>> outputMapBinder = outputsMapBinder();
    installOutput(outputMapBinder, FileOutput.class, FileOutput.Factory.class);
}
项目:bot4j    文件:MiddlewareModule.java   
@Override
protected void configure() {
    bind(DuplicateMessageFilter.class).to(DuplicateMessageFilterImpl.class);
    bind(MessageReceiver.class).to(MessageReceiverImpl.class);
    bind(MessageSender.class).to(MessageSenderImpl.class);
    bind(PostbackPayloadService.class).to(PostbackPayloadServiceImpl.class);
    bind(SessionManager.class).to(InMemorySessionManagerImpl.class);
    bind(InMemorySessionManager.class).to(InMemorySessionManagerImpl.class);

    final MapBinder<Platform, PlatformMessageSender> platformMessageSenderBinder = MapBinder.newMapBinder(binder(),
            Platform.class, PlatformMessageSender.class);
    platformMessageSenderBinder.addBinding(FacebookPlatformEnum.FACEBOOK).to(FacebookMessageSenderImpl.class);
    platformMessageSenderBinder.addBinding(SlackPlatformEnum.SLACK).to(SlackMessageSenderImpl.class);
    platformMessageSenderBinder.addBinding(TelegramPlatformEnum.TELEGRAM).to(TelegramMessageSenderImpl.class);
    platformMessageSenderBinder.addBinding(AlexaPlatformEnum.ALEXA).to(AlexaMessageSenderImpl.class);
    platformMessageSenderBinder.addBinding(ApiAiPlatformEnum.APIAI).to(ApiAiMessageSenderImpl.class);
}
项目:ice    文件:FileDynamicConfigSource.java   
public static Module module(final int configSourcePriority)
{
    return new AbstractModule()
    {
        @Override
        protected void configure()
        {
            MapBinder<Integer, DynamicConfigSource> mapBinder = MapBinder.newMapBinder(binder(), Integer.class, DynamicConfigSource.class);
            mapBinder.addBinding(configSourcePriority).to(FileDynamicConfigSource.class);
            bind(FileDynamicConfigSource.class);

            // Bind inner class as a service to ensure resource cleanup
            Multibinder.newSetBinder(binder(), Service.class).addBinding().to(FileDynamicConfigSourceService.class);
        }
    };
}
项目:walkaround    文件:GuiceSetup.java   
public static Module getRootModule(final String webinfRoot) {
  return Modules.combine(
      Modules.combine(extraModules),
      new WalkaroundServerModule(),
      new ConvStoreModule(),
      new UdwStoreModule(),
      new AbstractModule() {
        @Override public void configure() {
          bind(String.class).annotatedWith(Names.named("webinf root")).toInstance(webinfRoot);

          // TODO(ohler): Find a way to create these bindings in StoreModuleHelper; but note that
          // http://code.google.com/p/google-guice/wiki/Multibindings says something about
          // private modules not interacting well with multibindings.  I don't know if that
          // refers to our situation here.
          MapBinder<String, SlobFacilities> mapBinder =
              MapBinder.newMapBinder(binder(), String.class, SlobFacilities.class);
          for (Entry<String, Class<? extends Annotation>> entry
              : ImmutableMap.of(ConvStoreModule.ROOT_ENTITY_KIND, ConvStore.class,
                  UdwStoreModule.ROOT_ENTITY_KIND, UdwStore.class).entrySet()) {
            mapBinder.addBinding(entry.getKey())
                .to(Key.get(SlobFacilities.class, entry.getValue()));
          }
        }
      });
}
项目:yql-plus    文件:SourceModule.java   
@Override
protected void configure() {
    install(new JavaEngineModule());
    bind(ViewRegistry.class).toInstance(new ViewRegistry() {
        @Override
        public OperatorNode<SequenceOperator> getView(List<String> name) {
            return null;
        }
    });
    bind(TaskMetricEmitter.class).toInstance(
            new DummyStandardRequestEmitter(new MetricDimension(), new RequestMetricSink() {
                @Override
                public void emitRequest(final RequestEvent arg0) {
                }            
              }).start("program", "program"));
    MapBinder<String, Source> sourceBindings = MapBinder.newMapBinder(binder(), String.class, Source.class);
    sourceBindings.addBinding("weather").toInstance(new WeatherSource());
    sourceBindings.addBinding("geo").toInstance(new GeoSource());
}
项目:yql-plus    文件:SourceModule.java   
@Override
protected void configure() {
    install(new JavaEngineModule());
    bind(ViewRegistry.class).toInstance(new ViewRegistry() {
        @Override
        public OperatorNode<SequenceOperator> getView(List<String> name) {
            return null;
        }
    });
    bind(TaskMetricEmitter.class).toInstance(
            new DummyStandardRequestEmitter(new MetricDimension(), new RequestMetricSink() {
                @Override
                public void emitRequest(final RequestEvent arg0) {
                }
            }).start("program", "program"));
    MapBinder<String, Source> sourceBindings = MapBinder.newMapBinder(binder(), String.class, Source.class);
    sourceBindings.addBinding("stocks").toInstance(new StockSource());
    sourceBindings.addBinding("putStock").toInstance(new StockPutSource());
    sourceBindings.addBinding("updateStocks").toInstance(new StockUpdateSource());
}
项目:yql-plus    文件:JavaProgramCompilerTest.java   
@Test
public void testSimplistWithBoxedParamSourceSource() throws Exception {
    String programStr = "PROGRAM (@category string); \n" +
                        "select id, category \n" +
                        "from sampleListWithBoxedParams(10, 5.0, \"program\") \n" +
                        "where category = @category order by id \n" + 
                        "output as sampleIds; \n";
    Injector injector = Guice.createInjector(new JavaTestModule(), new AbstractModule() {
        @Override
        protected void configure() {
            MapBinder<String, Source> sourceBindings = MapBinder.newMapBinder(binder(), String.class, Source.class);
            sourceBindings.addBinding("sampleListWithBoxedParams").toInstance(new SampleListSourceWithBoxedParams());
        }            
    });
    YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
    CompiledProgram program = compiler.compile(programStr);
    ProgramResult myResult = program.run(new ImmutableMap.Builder<String, Object>().put("category", "test").build(), true);
    YQLResultSet result = myResult.getResult("sampleIds").get();
    List resultSet = result.getResult();
    assertEquals(10, resultSet.size());
}
项目:yql-plus    文件:JavaProgramCompilerTest.java   
@Test
public void testSimplistWithUnBoxedParamSourceSource() throws Exception {
    String programStr = "PROGRAM (@category string); \n" +
                        "select id, category \n" +
                        "from sampleListWithUnBoxedParams(10, 5.0, \"program\") \n" +
                        "where category = @category order by id \n" + 
                        "output as sampleIds; \n";
    Injector injector = Guice.createInjector(new JavaTestModule(), new AbstractModule() {
        @Override
        protected void configure() {
            MapBinder<String, Source> sourceBindings = MapBinder.newMapBinder(binder(), String.class, Source.class);
            sourceBindings.addBinding("sampleListWithUnBoxedParams").toInstance(new SampleListSourceWithUnboxedParams());
        }            
    });
    YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
    CompiledProgram program = compiler.compile(programStr);
    ProgramResult myResult = program.run(new ImmutableMap.Builder<String, Object>().put("category", "test").build(), true);
    YQLResultSet result = myResult.getResult("sampleIds").get();
    List resultSet = result.getResult();
    assertEquals(10, resultSet.size());
}
项目:yql-plus    文件:JavaProgramCompilerTest.java   
@Test
public void testEmpytKeyList() throws Exception {
    String programStr = "PROGRAM (@category array<string>); \n" +
        "select id, category \n" +
        "from sampleListWithBoxedParams(10, 5.0, \"program\") \n" +
        "where category in (@category) order by id \n" +
        "output as sampleIds; \n";
    Injector injector = Guice.createInjector(new JavaTestModule(), new AbstractModule() {
        @Override
        protected void configure() {
            MapBinder<String, Source> sourceBindings = MapBinder.newMapBinder(binder(), String.class, Source.class);
            sourceBindings.addBinding("sampleListWithBoxedParams").toInstance(new SampleListSourceWithBoxedParams());
        }
    });
    YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
    CompiledProgram program = compiler.compile(programStr);
    ProgramResult myResult = program.run(new ImmutableMap.Builder<String, Object>().put("category", ImmutableList.of()).build(), true);
    YQLResultSet result = myResult.getResult("sampleIds").get();
    List<Record> resultSet = result.getResult();
    assertEquals(0, resultSet.size());
}
项目:EDDI    文件:BehaviorModule.java   
@Override
protected void configure() {
    bind(IBehaviorDeserialization.class).to(BehaviorDeserialization.class).in(Scopes.SINGLETON);
    MapBinder<String, ILifecycleTask> lifecycleTaskPlugins
            = MapBinder.newMapBinder(binder(), String.class, ILifecycleTask.class);
    lifecycleTaskPlugins.addBinding("ai.labs.behavior").to(BehaviorRulesEvaluationTask.class);

    MapBinder<String, IBehaviorExtension> behaviorExtensionPlugins
            = MapBinder.newMapBinder(binder(), String.class, IBehaviorExtension.class);
    behaviorExtensionPlugins.addBinding("ai.labs.behavior.extension.inputmatcher").
            to(InputMatcher.class);
    behaviorExtensionPlugins.addBinding("ai.labs.behavior.extension.actionmatcher").
            to(ActionMatcher.class);
    behaviorExtensionPlugins.addBinding("ai.labs.behavior.extension.contextmatcher").
            to(ContextMatcher.class);
    behaviorExtensionPlugins.addBinding("ai.labs.behavior.extension.connector").
            to(Connector.class);
    behaviorExtensionPlugins.addBinding("ai.labs.behavior.extension.dependency").
            to(Dependency.class);
    behaviorExtensionPlugins.addBinding("ai.labs.behavior.extension.negation").
            to(Negation.class);
    behaviorExtensionPlugins.addBinding("ai.labs.behavior.extension.occurrence").
            to(Occurrence.class);
    behaviorExtensionPlugins.addBinding("ai.labs.behavior.extension.resultsize").
            to(ResultSize.class);
}
项目:europa    文件:AjaxHelperModule.java   
protected void addBinding(String operationName, Class<? extends AjaxHelper> clazz, String... paths)
{
    MapBinder<String, AjaxHelper> mapbinder = MapBinder.newMapBinder(binder(), String.class, AjaxHelper.class);
    mapbinder.addBinding(operationName).to(clazz);

    MapBinder<String, Set<String>> pathRestrictionBinder = MapBinder.newMapBinder(binder(),
                                                                                  new TypeLiteral<String>(){},
                                                                                  new TypeLiteral<Set<String>>(){});
    if(paths != null)
    {
        Set<String> pathSet = new HashSet<String>();
        for(String path : paths)
            pathSet.add(path);
        pathRestrictionBinder.addBinding(operationName).toInstance(pathSet);
    }
}
项目:bootique-job    文件:JobModule.java   
@Override
public void configure(Binder binder) {

    BQCoreModule.extend(binder).addCommand(ExecCommand.class)
            .addCommand(ListCommand.class)
            .addCommand(ScheduleCommand.class);

    // trigger extension points creation and provide default contributions
    JobModuleExtender extender = JobModule.extend(binder).initAllExtensions();
    jobTypes.forEach(extender::addJob);

    // TODO: move this to extender API
    MapBinder<LockType, LockHandler> lockHandlers = MapBinder.newMapBinder(binder, LockType.class,
            LockHandler.class);
    lockHandlers.addBinding(LockType.local).to(LocalLockHandler.class);
    lockHandlers.addBinding(LockType.clustered).to(ZkClusterLockHandler.class);
}
项目:collector    文件:CollectorModule.java   
public void registerInput(String type,
                          Class<? extends Input> inputClass,
                          Class<? extends Input.Factory<? extends Input, ? extends InputConfiguration>> inputFactoryClass,
                          Class<? extends InputConfiguration> inputConfigurationClass,
                          Class<? extends InputConfiguration.Factory<? extends InputConfiguration>> inputConfigurationFactoryClass) {
    if (inputsMapBinder == null) {
        this.inputsMapBinder = MapBinder.newMapBinder(binder(),
                TypeLiteral.get(String.class),
                new TypeLiteral<InputConfiguration.Factory<? extends InputConfiguration>>() {
                });
    }

    install(new FactoryModuleBuilder().implement(Input.class, inputClass).build(inputFactoryClass));
    install(new FactoryModuleBuilder().implement(Configuration.class, inputConfigurationClass).build(inputConfigurationFactoryClass));

    inputsMapBinder.addBinding(type).to(inputConfigurationFactoryClass);
}
项目:collector    文件:CollectorModule.java   
public void registerOutput(String type,
                           Class<? extends Output> outputClass,
                           Class<? extends Output.Factory<? extends Output, ? extends OutputConfiguration>> outputFactoryClass,
                           Class<? extends OutputConfiguration> outputConfigurationClass,
                           Class<? extends OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigurationFactoryClass) {

    if (outputsMapBinder == null) {
        this.outputsMapBinder = MapBinder.newMapBinder(binder(),
                TypeLiteral.get(String.class),
                new TypeLiteral<OutputConfiguration.Factory<? extends OutputConfiguration>>() {
                });
    }

    install(new FactoryModuleBuilder().implement(Output.class, outputClass).build(outputFactoryClass));
    install(new FactoryModuleBuilder().implement(Configuration.class, outputConfigurationClass).build(outputConfigurationFactoryClass));

    outputsMapBinder.addBinding(type).to(outputConfigurationFactoryClass);
}
项目:protostuff-compiler    文件:CompilerModule.java   
@Override
protected void configure() {
    bind(CompilerRegistry.class);
    bind(CompilerUtils.class);
    bind(MarkdownProcessor.class).to(PegDownMarkdownProcessor.class).in(Scopes.SINGLETON);
    install(new FactoryModuleBuilder()
            .implement(ProtoCompiler.class, StCompiler.class)
            .build(StCompilerFactory.class));
    install(new FactoryModuleBuilder()
            .implement(ProtoCompiler.class, ExtensibleStCompiler.class)
            .build(ExtensibleStCompilerFactory.class));
    Multibinder<HtmlCompiler> htmlCompilerBinder = Multibinder.newSetBinder(binder(), HtmlCompiler.class);
    htmlCompilerBinder.addBinding().to(JsonIndexGenerator.class);
    htmlCompilerBinder.addBinding().to(JsonEnumGenerator.class);
    htmlCompilerBinder.addBinding().to(JsonMessageGenerator.class);
    htmlCompilerBinder.addBinding().to(JsonServiceGenerator.class);
    htmlCompilerBinder.addBinding().to(JsonProtoGenerator.class);
    htmlCompilerBinder.addBinding().to(JsonPagesIndexGenerator.class);
    htmlCompilerBinder.addBinding().to(JsonPageGenerator.class);
    MapBinder<String, ProtoCompiler> compilers = newMapBinder(binder(), String.class, ProtoCompiler.class);
    compilers.addBinding(HTML_COMPILER).to(HtmlGenerator.class);
    compilers.addBinding(JAVA_COMPILER).toProvider(JavaCompilerProvider.class);
    compilers.addBinding(ST4_COMPILER).toProvider(St4CompilerProvider.class);
    compilers.addBinding(DUMMY_COMPILER).to(DummyGenerator.class).in(Scopes.SINGLETON);
}
项目:che    文件:WorkspaceApiPermissionsModule.java   
@Override
protected void configure() {
  bind(WorkspacePermissionsFilter.class);
  bind(StackPermissionsFilter.class);

  bind(WorkspaceCreatorPermissionsProvider.class).asEagerSingleton();
  bind(StackCreatorPermissionsProvider.class).asEagerSingleton();
  bind(StackLoader.class).to(MultiuserStackLoader.class);

  Multibinder.newSetBinder(
          binder(),
          PermissionsDomain.class,
          Names.named(SuperPrivilegesChecker.SUPER_PRIVILEGED_DOMAINS))
      .addBinding()
      .to(WorkspaceDomain.class);

  MapBinder.newMapBinder(binder(), String.class, SetPermissionsChecker.class)
      .addBinding(StackDomain.DOMAIN_ID)
      .to(StackDomainSetPermissionsChecker.class);

  MapBinder.newMapBinder(binder(), String.class, RemovePermissionsChecker.class)
      .addBinding(StackDomain.DOMAIN_ID)
      .to(PublicPermissionsRemoveChecker.class);
}
项目:che    文件:PermissionsModule.java   
@Override
protected void configure() {
  bind(PermissionsService.class);
  bind(SetPermissionsFilter.class);
  bind(RemovePermissionsFilter.class);
  bind(GetPermissionsFilter.class);

  // Creates empty multibinder to avoid error during container starting
  Multibinder.newSetBinder(
      binder(), String.class, Names.named(SystemDomain.SYSTEM_DOMAIN_ACTIONS));

  // initialize empty set binder
  Multibinder.newSetBinder(binder(), AccountPermissionsChecker.class);
  MapBinder.newMapBinder(binder(), String.class, SetPermissionsChecker.class);
  MapBinder.newMapBinder(binder(), String.class, RemovePermissionsChecker.class);
}
项目:che    文件:OpenShiftInfraModule.java   
@Override
protected void configure() {
  MapBinder<String, InternalEnvironmentFactory> factories =
      MapBinder.newMapBinder(binder(), String.class, InternalEnvironmentFactory.class);

  factories.addBinding(OpenShiftEnvironment.TYPE).to(OpenShiftEnvironmentFactory.class);
  factories.addBinding(DockerImageEnvironment.TYPE).to(DockerImageEnvironmentFactory.class);

  bind(RuntimeInfrastructure.class).to(OpenShiftInfrastructure.class);

  install(new FactoryModuleBuilder().build(OpenShiftRuntimeContextFactory.class));
  install(new FactoryModuleBuilder().build(OpenShiftRuntimeFactory.class));
  install(new FactoryModuleBuilder().build(OpenShiftBootstrapperFactory.class));
  bind(WorkspacePVCCleaner.class).asEagerSingleton();
  bind(RemoveProjectOnWorkspaceRemove.class).asEagerSingleton();

  bind(CheApiEnvVarProvider.class).to(OpenShiftCheApiEnvVarProvider.class);

  MapBinder<String, WorkspaceVolumesStrategy> volumesStrategies =
      MapBinder.newMapBinder(binder(), String.class, WorkspaceVolumesStrategy.class);
  volumesStrategies.addBinding(COMMON_STRATEGY).to(CommonPVCStrategy.class);
  volumesStrategies.addBinding(UNIQUE_STRATEGY).to(UniqueWorkspacePVCStrategy.class);
  bind(WorkspaceVolumesStrategy.class).toProvider(WorkspaceVolumeStrategyProvider.class);
}
项目:societies    文件:SiegeCommandModule.java   
@Override
protected void configure() {
    MapBinder<Class<?>, ArgumentParser<?>> parsers = MapBinder
            .newMapBinder(binder(), new TypeLiteral<Class<?>>() {}, new TypeLiteral<ArgumentParser<?>>() {}, Names
                    .named("parsers"));


    bind(new TypeLiteral<ArgumentParser<City>>() {}).to(CityParser.class);
    parsers.addBinding(City.class).to(CityParser.class);


    Multibinder<Class> cmds = newSetBinder(
            binder(),
            new TypeLiteral<Class>() {},
            named("custom-commands")
    );

    for (Class command : commands) {
        cmds.addBinding().toInstance(command);
    }
}
项目:guice    文件:MapBinderTest.java   
public void testMapBinderMapIsUnmodifiable() {
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              MapBinder.newMapBinder(binder(), String.class, String.class)
                  .addBinding("a")
                  .toInstance("A");
            }
          });

  Map<String, String> map = injector.getInstance(Key.get(mapOfString));
  try {
    map.clear();
    fail();
  } catch (UnsupportedOperationException expected) {
  }
}
项目:guice    文件:MapBinderTest.java   
public void testMapBinderMapForbidsNullValues() {
  Module m =
      new AbstractModule() {
        @Override
        protected void configure() {
          MapBinder.newMapBinder(binder(), String.class, String.class)
              .addBinding("null")
              .toProvider(Providers.<String>of(null));
        }
      };
  Injector injector = Guice.createInjector(m);

  try {
    injector.getInstance(Key.get(mapOfString));
    fail();
  } catch (ProvisionException expected) {
    assertContains(
        expected.getMessage(),
        "1) Map injection failed due to null value for key \"null\", bound at: "
            + m.getClass().getName()
            + ".configure(");
  }
}
项目:guice    文件:MapBinderTest.java   
public void testMapBinderProviderIsScoped() {
  final Provider<Integer> counter =
      new Provider<Integer>() {
        int next = 1;

        @Override
        public Integer get() {
          return next++;
        }
      };

  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              MapBinder.newMapBinder(binder(), String.class, Integer.class)
                  .addBinding("one")
                  .toProvider(counter)
                  .asEagerSingleton();
            }
          });

  assertEquals(1, (int) injector.getInstance(Key.get(mapOfInteger)).get("one"));
  assertEquals(1, (int) injector.getInstance(Key.get(mapOfInteger)).get("one"));
}
项目:guice    文件:MapBinderTest.java   
public void testSourceLinesInMapBindings() {
  try {
    Guice.createInjector(
        new AbstractModule() {
          @Override
          protected void configure() {
            MapBinder.newMapBinder(binder(), String.class, Integer.class).addBinding("one");
          }
        });
    fail();
  } catch (CreationException expected) {
    assertContains(
        expected.getMessage(),
        "1) No implementation for java.lang.Integer",
        "at " + getClass().getName());
  }
}
项目:guice    文件:MapBinderTest.java   
public void testDeduplicateMapBindings() {
  Module module =
      new AbstractModule() {
        @Override
        protected void configure() {
          MapBinder<String, String> mapbinder =
              MapBinder.newMapBinder(binder(), String.class, String.class);
          mapbinder.addBinding("a").toInstance("A");
          mapbinder.addBinding("a").toInstance("A");
          mapbinder.addBinding("b").toInstance("B");
          mapbinder.addBinding("b").toInstance("B");
        }
      };
  Injector injector = Guice.createInjector(module);
  assertEquals(mapOf("a", "A", "b", "B"), injector.getInstance(Key.get(mapOfString)));
  assertMapVisitor(
      Key.get(mapOfString),
      stringType,
      stringType,
      setOf(module),
      BOTH,
      false,
      0,
      instance("a", "A"),
      instance("b", "B"));
}
项目:guice    文件:MapBinderTest.java   
/** Ensure there are no initialization race conditions in basic map injection. */
public void testBasicMapDependencyInjection() {
  final AtomicReference<Map<String, String>> injectedMap =
      new AtomicReference<Map<String, String>>();
  final Object anObject =
      new Object() {
        @Inject
        void initialize(Map<String, String> map) {
          injectedMap.set(map);
        }
      };
  Module abc =
      new AbstractModule() {
        @Override
        protected void configure() {
          requestInjection(anObject);
          MapBinder<String, String> multibinder =
              MapBinder.newMapBinder(binder(), String.class, String.class);
          multibinder.addBinding("a").toInstance("A");
          multibinder.addBinding("b").toInstance("B");
          multibinder.addBinding("c").toInstance("C");
        }
      };
  Guice.createInjector(abc);
  assertEquals(mapOf("a", "A", "b", "B", "c", "C"), injectedMap.get());
}
项目:guice    文件:MultibinderTest.java   
public void testSetAndMapValueAreDistinct() {
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              Multibinder.newSetBinder(binder(), String.class).addBinding().toInstance("A");

              MapBinder.newMapBinder(binder(), String.class, String.class)
                  .addBinding("B")
                  .toInstance("b");

              OptionalBinder.newOptionalBinder(binder(), String.class)
                  .setDefault()
                  .toInstance("C");
              OptionalBinder.newOptionalBinder(binder(), String.class)
                  .setBinding()
                  .toInstance("D");
            }
          });

  assertEquals(ImmutableSet.of("A"), injector.getInstance(Key.get(setOfString)));
  assertEquals(ImmutableMap.of("B", "b"), injector.getInstance(Key.get(mapOfStringString)));
  assertEquals(Optional.of("D"), injector.getInstance(Key.get(optionalOfString)));
}
项目:hula-web    文件:HulaWebServletModule.java   
@Override
protected void configureServlets()
{
    // bind the properties
    Names.bindProperties(binder(), this.configProperties);

    // setup services
    bind(SessionService.class).to(SessionServiceImpl.class);
    bind(ScriptService.class).to(ScriptServiceImpl.class);
    bind(RouteService.class).to(RouteServiceImpl.class);

    // response processors
    MapBinder<String, ResponseProcessor> responseProcessorMap = MapBinder.newMapBinder(binder(), String.class, ResponseProcessor.class);
    responseProcessorMap.addBinding(ShowPageRunResult.class.getSimpleName()).to(ShowPageProcessor.class);
    responseProcessorMap.addBinding(ReturnContentRunResult.class.getSimpleName()).to(ReturnContentProcessor.class);
    responseProcessorMap.addBinding(RedirectRunResult.class.getSimpleName()).to(RedirectProcessor.class);

    // filter
    filter("/*").through(HulaWebFilter.class);

    // servlet
    serve("/exec*").with(HulaWebServlet.class);

}
项目:staash    文件:EurekaModule.java   
@Override
protected void configure() {
    LOG.info("Configuring EurekaModule");

    // Initialize eureka
    // TODO: Move this to a bootstrap thingy
    DiscoveryManager.getInstance().initComponent(
            new CloudInstanceConfig(),
            new DefaultEurekaClientConfig());

    // Eureka - Astyanax integration
    MapBinder<String, HostSupplierProvider> hostSuppliers = MapBinder.newMapBinder(binder(), String.class, HostSupplierProvider.class);
    hostSuppliers.addBinding("eureka").to(EurekaAstyanaxHostSupplier.class);

    //bind(ClusterDiscoveryService.class).to(EurekaClusterDiscoveryService.class).asEagerSingleton();

}
项目:caarray    文件:AbstractFileManagementServiceIntegrationTest.java   
@BeforeClass
public static void registerFileAccessServiceStub() {
    final ServiceLocatorStub locatorStub = ServiceLocatorStub.registerEmptyLocator();
    locatorStub.addLookup(FileAccessService.JNDI_NAME, new FileAccessServiceStub());
    InjectorFactory.addPlatform(new AbstractModule() {
        @Override
        protected void configure() {
            final MapBinder<String, DataStorage> mapBinder =
                    MapBinder.newMapBinder(binder(), String.class, DataStorage.class);
            mapBinder.addBinding(FileAccessServiceStub.SCHEME)
                    .toProvider(
                            ServiceLocatorFactory.serviceProvider(FileAccessServiceStub.class,
                                    FileAccessService.JNDI_NAME));
        }
    });
}
项目:caarray    文件:AffymetrixArrayDesignServiceIntegrationTest.java   
@BeforeClass
public static void registerAffymetrix() {
    InjectorFactory.setPlatformTransactionModule(new AbstractModule() {
        @Override
        protected void configure() {
            bind(SessionTransactionManager.class).to(LocalSessionTransactionManager.class);
        }
    });
    InjectorFactory.addPlatform(new AffymetrixModule());
    InjectorFactory.addPlatform(new AbstractModule() {
        @Override
        protected void configure() {
            final MapBinder<String, DataStorage> mapBinder = MapBinder.newMapBinder(binder(), String.class,
                    DataStorage.class);
            bind(FileAccessServiceStub.class).in(Scopes.SINGLETON);
            mapBinder.addBinding(FileAccessServiceStub.SCHEME).to(FileAccessServiceStub.class).in(Scopes.SINGLETON);
        }
    });
}
项目:druid-api    文件:PolyBind.java   
/**
 * Binds an option for a specific choice.  The choice must already be registered on the injector for this to work.
 *
 * @param binder the binder for the injector that is being configured
 * @param interfaceKey the interface that will have an option added to it.  This must equal the
 *                     Key provided to createChoice
 * @param <T> interface type
 * @return A MapBinder that can be used to create the actual option bindings.
 */
public static <T> MapBinder<String, T> optionBinder(Binder binder, Key<T> interfaceKey)
{
  final TypeLiteral<T> interfaceType = interfaceKey.getTypeLiteral();

  if (interfaceKey.getAnnotation() != null) {
    return MapBinder.newMapBinder(
        binder, TypeLiteral.get(String.class), interfaceType, interfaceKey.getAnnotation()
    );
  }
  else if (interfaceKey.getAnnotationType() != null) {
    return MapBinder.newMapBinder(
        binder, TypeLiteral.get(String.class), interfaceType, interfaceKey.getAnnotationType()
    );
  }
  else {
    return MapBinder.newMapBinder(binder, TypeLiteral.get(String.class), interfaceType);
  }
}
项目:joynr    文件:ServletMessagingModule.java   
@Override
protected void configure() {
    install(new HttpMessagingModule());
    bind(MessageListeners.class).to(MessageListenersImpl.class).asEagerSingleton();
    bind(ServletMessageReceiver.class).to(ServletMessageReceiverImpl.class);
    bind(MessageReceiver.class).to(ServletMessageReceiverImpl.class);
    MapBinder<Class<? extends Address>, IMessagingSkeleton> messagingSkeletonFactory;
    messagingSkeletonFactory = MapBinder.newMapBinder(binder(), new TypeLiteral<Class<? extends Address>>() {
    }, new TypeLiteral<IMessagingSkeleton>() {
    }, Names.named(MessagingSkeletonFactory.MIDDLEWARE_MESSAGING_SKELETONS));
    messagingSkeletonFactory.addBinding(ChannelAddress.class).to(ChannelMessagingSkeleton.class);

    Multibinder<GlobalAddressFactory<? extends Address>> globalAddresses;
    globalAddresses = Multibinder.newSetBinder(binder(),
                                               new TypeLiteral<GlobalAddressFactory<? extends Address>>() {
                                               },
                                               Names.named(GlobalAddressProvider.GLOBAL_ADDRESS_PROVIDER));
    globalAddresses.addBinding().to(ServletHttpGlobalAddressFactory.class);
    Multibinder<GlobalAddressFactory<? extends Address>> replyToAddresses;
    replyToAddresses = Multibinder.newSetBinder(binder(),
                                                new TypeLiteral<GlobalAddressFactory<? extends Address>>() {
                                                },
                                                Names.named(ReplyToAddressProvider.REPLY_TO_ADDRESS_PROVIDER));
    replyToAddresses.addBinding().to(ServletHttpGlobalAddressFactory.class);
}
项目:spoofax    文件:SpoofaxModule.java   
@Override protected void configure() {
    super.configure();

    parserBinder = MapBinder.newMapBinder(binder(), new TypeLiteral<String>() {},
        new TypeLiteral<IParser<ISpoofaxInputUnit, ISpoofaxParseUnit>>() {});
    spoofaxParserBinder = MapBinder.newMapBinder(binder(), String.class, ISpoofaxParser.class);
    analyzerBinder = MapBinder.newMapBinder(binder(), new TypeLiteral<String>() {},
        new TypeLiteral<IAnalyzer<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate>>() {});
    spoofaxAnalyzerBinder = MapBinder.newMapBinder(binder(), String.class, ISpoofaxAnalyzer.class);

    Multibinder.newSetBinder(binder(), ClassLoader.class).permitDuplicates();

    bindUnit();
    bindSyntax();
    bindParsers(parserBinder, spoofaxParserBinder);
    bindAnalyzers(analyzerBinder, spoofaxAnalyzerBinder);
    bindCompletion();
    bindAction();
    bindTransformer();
    bindCategorizer();
    bindStyler();
    bindTracing();
    bindOutline();
    bindMenu();
}
项目:spoofax    文件:SpoofaxModule.java   
private void bindAnalyzers(
    MapBinder<String, IAnalyzer<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate>> analyzerBinder,
    MapBinder<String, ISpoofaxAnalyzer> spoofaxAnalyzerBinder) {
    bind(StrategoAnalyzer.class).in(Singleton.class);
    bind(TaskEngineAnalyzer.class).in(Singleton.class);
    bind(ConstraintSingleFileAnalyzer.class).in(Singleton.class);
    bind(ConstraintMultiFileAnalyzer.class).in(Singleton.class);

    analyzerBinder.addBinding(StrategoAnalyzer.name).to(StrategoAnalyzer.class);
    spoofaxAnalyzerBinder.addBinding(StrategoAnalyzer.name).to(StrategoAnalyzer.class);
    analyzerBinder.addBinding(TaskEngineAnalyzer.name).to(TaskEngineAnalyzer.class);
    spoofaxAnalyzerBinder.addBinding(TaskEngineAnalyzer.name).to(TaskEngineAnalyzer.class);
    analyzerBinder.addBinding(ConstraintSingleFileAnalyzer.name).to(ConstraintSingleFileAnalyzer.class);
    spoofaxAnalyzerBinder.addBinding(ConstraintSingleFileAnalyzer.name).to(ConstraintSingleFileAnalyzer.class);
    analyzerBinder.addBinding(ConstraintMultiFileAnalyzer.name).to(ConstraintMultiFileAnalyzer.class);
    spoofaxAnalyzerBinder.addBinding(ConstraintMultiFileAnalyzer.name).to(ConstraintMultiFileAnalyzer.class);
}
项目:outland    文件:RedisModule.java   
@Override
protected void configure() {
  bind(RedisManaged.class).asEagerSingleton();
  RedisProviders providers = new RedisProviders(configuration);
  bind(RedisProviders.class).toInstance(providers);
  bind(RedisHealthCheck.class);

  MapBinder<String, RedisProvider> mapBinder
      = MapBinder.newMapBinder(binder(), String.class, RedisProvider.class);

  final Map<String, RedisProvider> providerMap = providers.getProviders();
  for (Map.Entry<String, RedisProvider> entry : providerMap.entrySet()) {
    mapBinder.addBinding(entry.getKey()).toInstance(entry.getValue());
  }
}
项目:SemanticRelationsEditor    文件:CustomModule.java   
@Override
protected void bindAbstractContentPartAdapters(MapBinder<AdapterKey<?>, Object> adapterMapBinder) {
    super.bindAbstractContentPartAdapters(adapterMapBinder);
    adapterMapBinder.addBinding(AdapterKey.defaultRole()).to(FocusAndSelectOnClickHandler.class);
    adapterMapBinder.addBinding(AdapterKey.defaultRole()).to(SelectFocusedOnTypeHandler.class);
    adapterMapBinder
            .addBinding(AdapterKey.role(DefaultHoverIntentHandlePartFactory.HOVER_INTENT_HANDLES_GEOMETRY_PROVIDER))
            .to(ShapeBoundsProvider.class);
}