@SuppressWarnings("unchecked") public static <T> void bindInstance( Binder binder, Key<T> bindKey, T instance ) { binder.bind(bindKey).toInstance(instance); final ParameterizedType supType = Types.newParameterizedType(Supplier.class, bindKey.getTypeLiteral().getType()); final Key supplierKey; if (bindKey.getAnnotationType() != null) { supplierKey = Key.get(supType, bindKey.getAnnotationType()); } else if (bindKey.getAnnotation() != null) { supplierKey = Key.get(supType, bindKey.getAnnotation()); } else { supplierKey = Key.get(supType); } binder.bind(supplierKey).toInstance(Suppliers.ofInstance(instance)); }
@Override public String toString(Key key) { if (key.getAnnotationType() != null) { return key.getTypeLiteral() + " annotated with " + (key.getAnnotation() != null ? key.getAnnotation() : key.getAnnotationType()); } else { return key.getTypeLiteral().toString(); } } });
void error(Key<T> key, Throwable x) { if (verbose) { LOGGER.log(Level.WARNING, "Failed to instantiate " + key + "; skipping this component", x); } else { LOGGER.log(Level.INFO, "Failed to instantiate optional component {0}; skipping", key.getTypeLiteral()); LOGGER.log(Level.FINE, key.toString(), x); } } };
/** * Returns a key that doesn't hold any references to parent classes. This is necessary for * anonymous keys, so ensure we don't hold a ref to the containing module (or class) forever. */ public static <T> Key<T> canonicalizeKey(Key<T> key) { // If we know this isn't a subclass, return as-is. // Otherwise, recreate the key to avoid the subclass if (key.getClass() == Key.class) { return key; } else if (key.getAnnotation() != null) { return Key.get(key.getTypeLiteral(), key.getAnnotation()); } else if (key.getAnnotationType() != null) { return Key.get(key.getTypeLiteral(), key.getAnnotationType()); } else { return Key.get(key.getTypeLiteral()); } }
@Test public void testExcludesCurrentNode() throws Exception .initialize(); ServiceSelector selector = injector.getInstance(Key.get(ServiceSelector.class, serviceType("presto"))); assertEquals(selector.selectAllServices().size(), 1); HeartbeatFailureDetector detector = injector.getInstance(HeartbeatFailureDetector.class); detector.updateMonitoredServices(); assertEquals(detector.getTotalCount(), 0); assertEquals(detector.getActiveCount(), 0); assertEquals(detector.getFailedCount(), 0); assertTrue(detector.getFailed().isEmpty());
@Test public void testMultiConditionalBind_cat() { props.setProperty("animal.type", "cat"); Injector injector = Guice.createInjector(new Module() { @Override public void configure(Binder binder) { ConditionalMultibind.create(props, binder, Animal.class) .addConditionBinding(ANIMAL_TYPE, Predicates.equalTo("cat"), Cat.class) .addConditionBinding(ANIMAL_TYPE, Predicates.equalTo("dog"), Dog.class); } }); Set<Animal> animalSet = injector.getInstance(Key.get(new TypeLiteral<Set<Animal>>() { })); Assert.assertEquals(1, animalSet.size()); Assert.assertEquals(animalSet, ImmutableSet.<Animal>of(new Cat())); }
@Override public Emitter apply(String s) { return injector.getInstance(Key.get(Emitter.class, Names.named(s))); } }
@Override public void configure(Binder binder) { JsonConfigProvider.bindInstance( binder, Key.get(DruidNode.class, Self.class), node ); binder.bind(Integer.class).annotatedWith(Names.named("port")).toInstance(node.getPlaintextPort()); binder.bind(JettyServerInitializer.class).to(TestJettyServerInitializer.class).in(LazySingleton.class); Jerseys.addResource(binder, SimpleResource.class); LifecycleModule.register(binder, Server.class); } }
@BeforeClass public static void setup() throws InterruptedException, IOException { new MockNodeProbe(); injector = Guice.createInjector(new BRTestModule()); filesystem = (FakeBackupFileSystem) injector.getInstance( Key.get(IBackupFileSystem.class, Names.named("backup"))); }
public ModuleList(Injector baseInjector) { this.baseInjector = baseInjector; this.modulesConfig = baseInjector.getInstance(ModulesConfig.class); this.jsonMapper = baseInjector.getInstance(Key.get(ObjectMapper.class, Json.class)); this.smileMapper = baseInjector.getInstance(Key.get(ObjectMapper.class, Smile.class)); this.modules = new ArrayList<>(); }
@Test public void testLinkedViewBindsViewAndContextSuppliers() { Injector injector = Guice.createInjector(linkView(new DummyView(contextFor(IntegrationTestClient.class)))); assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient")))); assertNotNull(injector.getExistingBinding(Key.get(VIEW_SUPPLIER, Names.named("IntegrationTestClient")))); }
@AfterClass private void close() throws IOException { ListeningExecutorService user = injector.getInstance(Key.get(ListeningExecutorService.class, named(PROPERTY_USER_THREADS))); ListeningExecutorService io = injector.getInstance(Key.get(ListeningExecutorService.class, named(PROPERTY_IO_WORKER_THREADS))); injector.getInstance(Closer.class).close(); assertTrue(user.isShutdown()); assertTrue(io.isShutdown()); }
@Override public void configure(Binder binder) { binder.bind(RequestLogger.class).toProvider(RequestLoggerProvider.class).in(ManageLifecycle.class); binder.bind(Key.get(String.class, Names.named("serviceName"))).toInstance("some service"); binder.bind(Key.get(Integer.class, Names.named("servicePort"))).toInstance(0); binder.bind(Key.get(Integer.class, Names.named("tlsServicePort"))).toInstance(-1); JsonConfigProvider.bind(binder, propertyPrefix, RequestLoggerProvider.class); } }
@Override public void configure(Binder binder) { binder.bind(Key.get(String.class, Names.named("serviceName"))).toInstance("some service"); binder.bind(Key.get(Integer.class, Names.named("servicePort"))).toInstance(0); binder.bind(Key.get(Integer.class, Names.named("tlsServicePort"))).toInstance(-1); } }
public static void bindAnnouncer( final Binder binder, final Class<? extends Annotation> annotation, final DiscoverySideEffectsProvider provider ) { binder.bind(DiscoverySideEffectsProvider.Child.class) .annotatedWith(annotation) .toProvider(provider) .in(LazySingleton.class); LifecycleModule.registerKey(binder, Key.get(DiscoverySideEffectsProvider.Child.class, annotation)); }
@Override public void configure(Binder binder) { JsonConfigProvider.bind(binder, "druid.monitoring", DruidMonitorSchedulerConfig.class); JsonConfigProvider.bind(binder, "druid.monitoring", MonitorsConfig.class); DruidBinders.metricMonitorBinder(binder); // get the binder so that it will inject the empty set at a minimum. binder.bind(DataSourceTaskIdHolder.class).in(LazySingleton.class); binder.bind(EventReceiverFirehoseRegister.class).in(LazySingleton.class); binder.bind(ExecutorServiceMonitor.class).in(LazySingleton.class); // Instantiate eagerly so that we get everything registered and put into the Lifecycle binder.bind(Key.get(MonitorScheduler.class, Names.named("ForTheEagerness"))) .to(MonitorScheduler.class) .asEagerSingleton(); }
@Override public void configure(Binder binder) { createBindingChoices(binder, TYPE); super.configure(binder); binder.bind(MetadataStorage.class).toProvider(NoopMetadataStorageProvider.class); PolyBind.optionBinder(binder, Key.get(MetadataStorageProvider.class)) .addBinding(TYPE) .to(DerbyMetadataStorageProvider.class) .in(LazySingleton.class); PolyBind.optionBinder(binder, Key.get(MetadataStorageConnector.class)) .addBinding(TYPE) .to(DerbyConnector.class) .in(LazySingleton.class); PolyBind.optionBinder(binder, Key.get(SQLMetadataConnector.class)) .addBinding(TYPE) .to(DerbyConnector.class) .in(LazySingleton.class); PolyBind.optionBinder(binder, Key.get(MetadataStorageActionHandlerFactory.class)) .addBinding(TYPE) .to(DerbyMetadataStorageActionHandlerFactory.class) .in(LazySingleton.class); } }
@Override public void configure(Binder binder) { Jerseys.addResource(binder, ChatHandlerResource.class); LifecycleModule.register(binder, ChatHandlerResource.class); if (properties.containsKey(MAX_CHAT_REQUESTS_PROPERTY)) { final int maxRequests = Integer.parseInt(properties.getProperty(MAX_CHAT_REQUESTS_PROPERTY)); JettyBindings.addQosFilter(binder, "/druid/worker/v1/chat/*", maxRequests); } Multibinder.newSetBinder(binder, ServletFilterHolder.class).addBinding().to(TaskIdResponseHeaderFilterHolder.class); /** * We bind {@link DruidNode} annotated with {@link RemoteChatHandler} to {@literal @}{@link Self} {@link DruidNode} * so that same Jetty Server is used for querying as well as ingestion. */ binder.bind(DruidNode.class).annotatedWith(RemoteChatHandler.class).to(Key.get(DruidNode.class, Self.class)); binder.bind(ServerConfig.class).annotatedWith(RemoteChatHandler.class).to(Key.get(ServerConfig.class)); binder.bind(TLSServerConfig.class).annotatedWith(RemoteChatHandler.class).to(Key.get(TLSServerConfig.class)); }