Search in sources :

Example 1 with MapBinder

use of com.google.inject.multibindings.MapBinder in project druid by druid-io.

the class PolyBindTest method testSanity.

@Test
public void testSanity() throws Exception {
    setUp(new Module() {

        @Override
        public void configure(Binder binder) {
            final MapBinder<String, Gogo> gogoBinder = PolyBind.optionBinder(binder, Key.get(Gogo.class));
            gogoBinder.addBinding("a").to(GoA.class);
            gogoBinder.addBinding("b").to(GoB.class);
            final MapBinder<String, GogoSally> gogoSallyBinder = PolyBind.optionBinder(binder, Key.get(GogoSally.class));
            gogoSallyBinder.addBinding("a").to(GoA.class);
            gogoSallyBinder.addBinding("b").to(GoB.class);
            PolyBind.createChoice(binder, "billy", Key.get(Gogo.class, Names.named("reverse")), Key.get(GoB.class));
            final MapBinder<String, Gogo> annotatedGogoBinder = PolyBind.optionBinder(binder, Key.get(Gogo.class, Names.named("reverse")));
            annotatedGogoBinder.addBinding("a").to(GoB.class);
            annotatedGogoBinder.addBinding("b").to(GoA.class);
        }
    });
    Assert.assertEquals("A", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("B", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    props.setProperty("billy", "b");
    Assert.assertEquals("B", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("A", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    props.setProperty("billy", "a");
    Assert.assertEquals("A", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("B", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    props.setProperty("billy", "b");
    Assert.assertEquals("B", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("A", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    props.setProperty("billy", "c");
    Assert.assertEquals("A", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("B", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    // test default property value
    Assert.assertEquals("B", injector.getInstance(GogoSally.class).go());
    props.setProperty("sally", "a");
    Assert.assertEquals("A", injector.getInstance(GogoSally.class).go());
    props.setProperty("sally", "b");
    Assert.assertEquals("B", injector.getInstance(GogoSally.class).go());
    props.setProperty("sally", "c");
    try {
        injector.getInstance(GogoSally.class).go();
        // should never be reached
        Assert.fail();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof ProvisionException);
        Assert.assertTrue(e.getMessage().contains("Unknown provider[c] of Key[type=io.druid.guice.PolyBindTest$GogoSally"));
    }
}
Also used : Binder(com.google.inject.Binder) MapBinder(com.google.inject.multibindings.MapBinder) ProvisionException(com.google.inject.ProvisionException) MapBinder(com.google.inject.multibindings.MapBinder) Module(com.google.inject.Module) ProvisionException(com.google.inject.ProvisionException) Test(org.junit.Test)

Example 2 with MapBinder

use of com.google.inject.multibindings.MapBinder in project cdap by caskdata.

the class JobQueueDatasetTest method beforeClass.

@BeforeClass
public static void beforeClass() throws IOException, DatasetManagementException {
    CConfiguration cConf = CConfiguration.create();
    cConf.set(Constants.CFG_LOCAL_DATA_DIR, TEMP_FOLDER.newFolder().getAbsolutePath());
    txManager = new TransactionManager(new Configuration());
    txManager.startAndWait();
    Injector injector = Guice.createInjector(new ConfigModule(cConf), new LocationRuntimeModule().getInMemoryModules(), new SystemDatasetRuntimeModule().getInMemoryModules(), new AbstractModule() {

        @Override
        protected void configure() {
            // Add the app-fabric Dataset module, which is where the JobQueueDataset is defined
            MapBinder<String, DatasetModule> datasetModuleBinder = MapBinder.newMapBinder(binder(), String.class, DatasetModule.class, Constants.Dataset.Manager.DefaultDatasetModules.class);
            datasetModuleBinder.addBinding("app-fabric").toInstance(new AppFabricDatasetModule());
            install(new FactoryModuleBuilder().implement(DatasetDefinitionRegistry.class, DefaultDatasetDefinitionRegistry.class).build(DatasetDefinitionRegistryFactory.class));
            bind(DatasetFramework.class).to(InMemoryDatasetFramework.class);
            bind(NamespaceQueryAdmin.class).to(InMemoryNamespaceClient.class).in(Scopes.SINGLETON);
        }
    });
    DatasetFramework datasetFramework = injector.getInstance(DatasetFramework.class);
    DatasetsUtil.createIfNotExists(datasetFramework, Schedulers.JOB_QUEUE_DATASET_ID, JobQueueDataset.class.getName(), DatasetProperties.EMPTY);
    jobQueue = datasetFramework.getDataset(Schedulers.JOB_QUEUE_DATASET_ID, new HashMap<String, String>(), null);
    txExecutor = new DynamicTransactionExecutorFactory(new InMemoryTxSystemClient(txManager)).createExecutor(Collections.<TransactionAware>singleton(jobQueue));
}
Also used : CConfiguration(co.cask.cdap.common.conf.CConfiguration) Configuration(org.apache.hadoop.conf.Configuration) HashMap(java.util.HashMap) ConfigModule(co.cask.cdap.common.guice.ConfigModule) FactoryModuleBuilder(com.google.inject.assistedinject.FactoryModuleBuilder) DynamicTransactionExecutorFactory(co.cask.cdap.data.runtime.DynamicTransactionExecutorFactory) AppFabricDatasetModule(co.cask.cdap.internal.app.AppFabricDatasetModule) DatasetModule(co.cask.cdap.api.dataset.module.DatasetModule) DatasetFramework(co.cask.cdap.data2.dataset2.DatasetFramework) InMemoryDatasetFramework(co.cask.cdap.data2.dataset2.InMemoryDatasetFramework) DefaultDatasetDefinitionRegistry(co.cask.cdap.data2.dataset2.DefaultDatasetDefinitionRegistry) Injector(com.google.inject.Injector) NamespaceQueryAdmin(co.cask.cdap.common.namespace.NamespaceQueryAdmin) SystemDatasetRuntimeModule(co.cask.cdap.data.runtime.SystemDatasetRuntimeModule) InMemoryDatasetFramework(co.cask.cdap.data2.dataset2.InMemoryDatasetFramework) LocationRuntimeModule(co.cask.cdap.common.guice.LocationRuntimeModule) AppFabricDatasetModule(co.cask.cdap.internal.app.AppFabricDatasetModule) DefaultDatasetDefinitionRegistry(co.cask.cdap.data2.dataset2.DefaultDatasetDefinitionRegistry) DatasetDefinitionRegistry(co.cask.cdap.api.dataset.module.DatasetDefinitionRegistry) InMemoryTxSystemClient(org.apache.tephra.inmemory.InMemoryTxSystemClient) CConfiguration(co.cask.cdap.common.conf.CConfiguration) AbstractModule(com.google.inject.AbstractModule) TransactionManager(org.apache.tephra.TransactionManager) TransactionAware(org.apache.tephra.TransactionAware) MapBinder(com.google.inject.multibindings.MapBinder) BeforeClass(org.junit.BeforeClass)

Example 3 with MapBinder

use of com.google.inject.multibindings.MapBinder in project guice by google.

the class MapBinderTest method testMultibinderDependenciesInToolStage.

/**
 * Check that the dependencies are correct in the Tool Stage.
 */
public void testMultibinderDependenciesInToolStage() {
    Injector injector = Guice.createInjector(Stage.TOOL, new AbstractModule() {

        @Override
        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;
    Set<Dependency<?>> actualDependencies = withDependencies.getDependencies();
    // We expect two dependencies, because the dependencies are annotated with
    // Element, which has a uniqueId, it's difficult to directly compare them.
    // Instead we will manually compare all the fields except the uniqueId
    assertEquals(2, actualDependencies.size());
    for (Dependency<?> dependency : actualDependencies) {
        Key<?> key = dependency.getKey();
        assertEquals(new TypeLiteral<String>() {
        }, key.getTypeLiteral());
        Annotation annotation = dependency.getKey().getAnnotation();
        assertTrue(annotation instanceof Element);
        Element element = (Element) annotation;
        assertEquals("", element.setName());
        assertEquals(Element.Type.MAPBINDER, element.type());
        assertEquals("java.lang.Integer", element.keyType());
    }
}
Also used : Dependency(com.google.inject.spi.Dependency) HasDependencies(com.google.inject.spi.HasDependencies) BindingAnnotation(com.google.inject.BindingAnnotation) Annotation(java.lang.annotation.Annotation) AbstractModule(com.google.inject.AbstractModule) Injector(com.google.inject.Injector) MapBinder(com.google.inject.multibindings.MapBinder) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 4 with MapBinder

use of com.google.inject.multibindings.MapBinder in project guice by google.

the class MapBinderTest method testMapBinderMatching.

@Marker
public void testMapBinderMatching() throws Exception {
    Method m = MapBinderTest.class.getDeclaredMethod("testMapBinderMatching");
    assertNotNull(m);
    final Annotation marker = m.getAnnotation(Marker.class);
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        public void configure() {
            MapBinder<Integer, Integer> mb1 = MapBinder.newMapBinder(binder(), Integer.class, Integer.class, Marker.class);
            MapBinder<Integer, Integer> mb2 = MapBinder.newMapBinder(binder(), Integer.class, Integer.class, marker);
            mb1.addBinding(1).toInstance(1);
            mb2.addBinding(2).toInstance(2);
            // This assures us that the two binders are equivalent, so we expect the instance added to
            // each to have been added to one set.
            assertEquals(mb1, mb2);
        }
    });
    TypeLiteral<Map<Integer, Integer>> t = new TypeLiteral<Map<Integer, Integer>>() {
    };
    Map<Integer, Integer> s1 = injector.getInstance(Key.get(t, Marker.class));
    Map<Integer, Integer> s2 = injector.getInstance(Key.get(t, marker));
    // This assures us that the two sets are in fact equal.  They may not be same set (as in Java
    // object identical), but we shouldn't expect that, since probably Guice creates the set each
    // time in case the elements are dependent on scope.
    assertEquals(s1, s2);
    // This ensures that MultiBinder is internally using the correct set name --
    // making sure that instances of marker annotations have the same set name as
    // MarkerAnnotation.class.
    Map<Integer, Integer> expected = new HashMap<>();
    expected.put(1, 1);
    expected.put(2, 2);
    assertEquals(expected, s1);
}
Also used : HashMap(java.util.HashMap) Method(java.lang.reflect.Method) BindingAnnotation(com.google.inject.BindingAnnotation) Annotation(java.lang.annotation.Annotation) AbstractModule(com.google.inject.AbstractModule) TypeLiteral(com.google.inject.TypeLiteral) Injector(com.google.inject.Injector) MapBinder(com.google.inject.multibindings.MapBinder) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 5 with MapBinder

use of com.google.inject.multibindings.MapBinder in project cdap by caskdata.

the class DefaultPreviewManager method createPreviewInjector.

/**
 * Create injector for the given application id.
 */
@VisibleForTesting
Injector createPreviewInjector(ApplicationId applicationId) throws IOException {
    CConfiguration previewCConf = CConfiguration.copy(cConf);
    java.nio.file.Path previewDirPath = Paths.get(cConf.get(Constants.CFG_LOCAL_DATA_DIR), "preview").toAbsolutePath();
    Files.createDirectories(previewDirPath);
    java.nio.file.Path previewDir = Files.createDirectories(Paths.get(previewDirPath.toAbsolutePath().toString(), applicationId.getApplication()));
    previewCConf.set(Constants.CFG_LOCAL_DATA_DIR, previewDir.toString());
    Configuration previewHConf = new Configuration(hConf);
    previewHConf.set(Constants.CFG_LOCAL_DATA_DIR, previewDir.toString());
    previewCConf.setIfUnset(Constants.CFG_DATA_LEVELDB_DIR, previewDir.toString());
    previewCConf.setBoolean(Constants.Explore.EXPLORE_ENABLED, false);
    return Guice.createInjector(new ConfigModule(previewCConf, previewHConf), new IOModule(), new AuthenticationContextModules().getMasterModule(), new SecurityModules().getStandaloneModules(), new PreviewSecureStoreModule(secureStore), new PreviewStreamAdminModule(streamAdmin), new PreviewDiscoveryRuntimeModule(discoveryService), new LocationRuntimeModule().getStandaloneModules(), new ConfigStoreModule().getStandaloneModule(), new PreviewRunnerModule(artifactRepository, artifactStore, authorizerInstantiator, authorizationEnforcer, privilegesManager, streamCoordinatorClient, preferencesStore), new ProgramRunnerRuntimeModule().getStandaloneModules(), new PreviewDataModules().getDataFabricModule(transactionManager), new PreviewDataModules().getDataSetsModule(datasetFramework), new DataSetServiceModules().getStandaloneModules(), new MetricsClientRuntimeModule().getStandaloneModules(), new LoggingModules().getStandaloneModules(), new NamespaceStoreModule().getStandaloneModules(), new MessagingServerRuntimeModule().getInMemoryModules(), new AbstractModule() {

        @Override
        protected void configure() {
            // Bind system datasets defined in App-fabric.
            // Have to do it here as public binding, instead of inside PreviewRunnerModule due to Guice 3
            // doesn't support exporting multi-binder from private module
            MapBinder<String, DatasetModule> datasetModuleBinder = MapBinder.newMapBinder(binder(), String.class, DatasetModule.class, Constants.Dataset.Manager.DefaultDatasetModules.class);
            datasetModuleBinder.addBinding("app-fabric").toInstance(new AppFabricDatasetModule());
            bind(ArtifactRepository.class).annotatedWith(Names.named(AppFabricServiceRuntimeModule.NOAUTH_ARTIFACT_REPO)).to(DefaultArtifactRepository.class).in(Scopes.SINGLETON);
        }

        @Provides
        @Named(Constants.Service.MASTER_SERVICES_BIND_ADDRESS)
        @SuppressWarnings("unused")
        public InetAddress providesHostname(CConfiguration cConf) {
            String address = cConf.get(Constants.Preview.ADDRESS);
            return Networks.resolve(address, new InetSocketAddress("localhost", 0).getAddress());
        }
    });
}
Also used : IOModule(co.cask.cdap.common.guice.IOModule) DataSetServiceModules(co.cask.cdap.data.runtime.DataSetServiceModules) CConfiguration(co.cask.cdap.common.conf.CConfiguration) Configuration(org.apache.hadoop.conf.Configuration) PreviewDataModules(co.cask.cdap.data.runtime.preview.PreviewDataModules) PreviewSecureStoreModule(co.cask.cdap.security.guice.preview.PreviewSecureStoreModule) PreviewDiscoveryRuntimeModule(co.cask.cdap.common.guice.preview.PreviewDiscoveryRuntimeModule) ConfigModule(co.cask.cdap.common.guice.ConfigModule) InetSocketAddress(java.net.InetSocketAddress) NamespaceStoreModule(co.cask.cdap.store.guice.NamespaceStoreModule) PreviewRunnerModule(co.cask.cdap.app.preview.PreviewRunnerModule) MessagingServerRuntimeModule(co.cask.cdap.messaging.guice.MessagingServerRuntimeModule) MetricsClientRuntimeModule(co.cask.cdap.metrics.guice.MetricsClientRuntimeModule) SecurityModules(co.cask.cdap.security.guice.SecurityModules) AppFabricDatasetModule(co.cask.cdap.internal.app.AppFabricDatasetModule) DatasetModule(co.cask.cdap.api.dataset.module.DatasetModule) ConfigStoreModule(co.cask.cdap.config.guice.ConfigStoreModule) Named(com.google.inject.name.Named) AuthenticationContextModules(co.cask.cdap.security.auth.context.AuthenticationContextModules) LocationRuntimeModule(co.cask.cdap.common.guice.LocationRuntimeModule) AppFabricDatasetModule(co.cask.cdap.internal.app.AppFabricDatasetModule) Provides(com.google.inject.Provides) CConfiguration(co.cask.cdap.common.conf.CConfiguration) LoggingModules(co.cask.cdap.logging.guice.LoggingModules) AbstractModule(com.google.inject.AbstractModule) ProgramRunnerRuntimeModule(co.cask.cdap.app.guice.ProgramRunnerRuntimeModule) MapBinder(com.google.inject.multibindings.MapBinder) PreviewStreamAdminModule(co.cask.cdap.data.stream.preview.PreviewStreamAdminModule) InetAddress(java.net.InetAddress) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

MapBinder (com.google.inject.multibindings.MapBinder)11 AbstractModule (com.google.inject.AbstractModule)8 Injector (com.google.inject.Injector)7 HashMap (java.util.HashMap)6 Map (java.util.Map)6 ImmutableMap (com.google.common.collect.ImmutableMap)5 Binder (com.google.inject.Binder)3 DatasetModule (co.cask.cdap.api.dataset.module.DatasetModule)2 CConfiguration (co.cask.cdap.common.conf.CConfiguration)2 ConfigModule (co.cask.cdap.common.guice.ConfigModule)2 LocationRuntimeModule (co.cask.cdap.common.guice.LocationRuntimeModule)2 AppFabricDatasetModule (co.cask.cdap.internal.app.AppFabricDatasetModule)2 BindingAnnotation (com.google.inject.BindingAnnotation)2 Provides (com.google.inject.Provides)2 Annotation (java.lang.annotation.Annotation)2 Set (java.util.Set)2 DatasetDefinitionRegistry (co.cask.cdap.api.dataset.module.DatasetDefinitionRegistry)1 ProgramRunnerRuntimeModule (co.cask.cdap.app.guice.ProgramRunnerRuntimeModule)1 PreviewRunnerModule (co.cask.cdap.app.preview.PreviewRunnerModule)1 IOModule (co.cask.cdap.common.guice.IOModule)1