com.google.inject.Binding Java Examples

The following examples show how to use com.google.inject.Binding. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Injectors.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static <K, T> Map<K, T> mapInstancesOf(Injector injector, Class<T> type, final Function<T, K> keyFunction) {
	Preconditions.checkNotNull(injector, "injector");
	Preconditions.checkNotNull(type, "type");
	Preconditions.checkNotNull(keyFunction, "keyFunction");

	final Map<K, T> results = new LinkedHashMap<K, T>();
	visitBindings(injector, type, new BindingVisitor<T>() {
	   @Override
	   public void visit(Binding<T> binding) {
		   T value = binding.getProvider().get();
		   K key = keyFunction.apply(value);
		   results.put(key, value);
        }
	});
	return results;
}
 
Example #2
Source File: ModulesSupport.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
private static boolean checkBindingRemoveRequired(final ConfigurationContext context,
                                                  final Binding binding,
                                                  final List<Class<?>> extensions,
                                                  final Multimap<Key, LinkedKeyBinding> linkedBindings) {
    final Key key = binding.getKey();
    if (isPossibleExtension(key)) {
        context.stat().count(Stat.AnalyzedBindingsCount, 1);
        final Class type = key.getTypeLiteral().getRawType();
        if (ExtensionsSupport.registerExtensionBinding(context, type,
                binding, BindingUtils.getTopDeclarationModule(binding))) {
            LOGGER.debug("Extension detected from guice binding: {}", type.getSimpleName());
            extensions.add(type);
            return !context.isExtensionEnabled(type);
        }
    }
    // note if linked binding recognized as extension by its key - it would not be counted (not needed)
    if (binding instanceof LinkedKeyBinding) {
        // remember all linked bindings (do not recognize on first path to avoid linked binding check before
        // real binding)
        final LinkedKeyBinding linkedBind = (LinkedKeyBinding) binding;
        linkedBindings.put(linkedBind.getLinkedKey(), linkedBind);
    }
    return false;
}
 
Example #3
Source File: DefaultApplicationContextTest.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    DefaultApplicationContext applicationContext = newApplicationContext();
    try {
        Injector injector = applicationContext.getInjector();
        Map<Key<?>, Binding<?>> bindings = injector.getBindings();
        for (Map.Entry<Key<?>, Binding<?>> e : bindings.entrySet()) {
            Key<?> key = e.getKey();
            Binding<?> binding = e.getValue();

            if (isPinpointBinding(key)) {
                boolean isSingletonScoped = Scopes.isSingleton(binding);
                Assert.assertTrue("Binding " + key + " is not Singleton scoped", isSingletonScoped);
            }
        }
        AgentInfoSender instance1 = injector.getInstance(AgentInfoSender.class);
        AgentInfoSender instance2 = injector.getInstance(AgentInfoSender.class);
        Assert.assertSame(instance1, instance2);
    } finally {
        applicationContext.close();
    }
}
 
Example #4
Source File: EndpointsModuleTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigureEndpoints_withoutInterceptor() {
  Injector injector = Guice.createInjector(module, new DummyModule());

  Visitor visitor = new Visitor();
  for (Binding<?> binding : injector.getAllBindings().values()) {
    binding.acceptTargetVisitor(visitor);
  }

  assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size());
  LinkedServletBinding servletBinding = visitor.linkedServlets.get(0);
  assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern());
  assertEquals("Wrong initialization parameter provided", "false",
      servletBinding.getInitParams().get("restricted"));
  assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider);

  ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get();
  Collection<Object> services = serviceMap.getServices();
  assertEquals("Incorrect number of services provided", 1, services.size());
  assertEquals("Service not provided correctly.", SERVICES.toArray()[0],
      services.toArray()[0].getClass());
}
 
Example #5
Source File: EndpointsModuleTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigureEndpoints_withInterceptor() {
  Injector injector = Guice.createInjector(module, new InterceptorModule());

  Visitor visitor = new Visitor();
  for (Binding<?> binding : injector.getAllBindings().values()) {
    binding.acceptTargetVisitor(visitor);
  }

  assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size());
  LinkedServletBinding servletBinding = visitor.linkedServlets.get(0);
  assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern());
  assertEquals("Wrong initialization parameter provided", "false",
      servletBinding.getInitParams().get("restricted"));
  assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider);

  ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get();
  Collection<Object> services = serviceMap.getServices();
  assertEquals("Incorrect number of services provided", 1, services.size());
  assertEquals("Service not enhanced correctly.", SERVICES.toArray()[0],
      ((Class<?>) services.toArray()[0].getClass()).getSuperclass());
}
 
Example #6
Source File: AdapterInjector.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Infers the type of the given adapter, evaluating either the related
 * bindings or the runtime type of the adapter.
 *
 * @param adapterKey
 *            The key of the map binding, which is an {@link AdapterKey}.
 * @param binding
 *            The binding related to the {@link AdapterKey}.
 * @param adapter
 *            The adapter instance.
 * @param issues
 *            A list of issues that might be filled with error and warning
 *            messages.
 *
 * @return A {@link TypeToken} representing the type of the given adapter
 *         instance.
 */
private TypeToken<?> inferAdapterType(AdapterKey<?> adapterKey,
		Binding<?> binding, Object adapter, List<String> issues) {
	// try to infer the actual type of the adapter from the binding
	TypeToken<?> bindingInferredType = binding
			.acceptTargetVisitor(ADAPTER_TYPE_INFERRER);

	// perform some sanity checks
	validateAdapterBinding(adapterKey, binding, adapter,
			bindingInferredType, issues);

	// The key type always takes precedence. Otherwise, if we could
	// infer a type from the binding, we use that before falling back to
	// inferring the type from the adapter instance itself.
	TypeToken<?> bindingKeyType = adapterKey.getKey();
	return bindingKeyType != null ? bindingKeyType
			: (bindingInferredType != null ? bindingInferredType
					: TypeToken.of(adapter.getClass()));
}
 
Example #7
Source File: MultipleSingletonPluginUITest.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isSingleton(Binding<?> b) {
	return b.acceptScopingVisitor(new DefaultBindingScopingVisitor<Boolean>() {
		@Override
		public Boolean visitEagerSingleton() {
			return Boolean.TRUE;
		}

		@Override
		public Boolean visitScope(Scope scope) {
			return Scopes.SINGLETON.equals(scope);
		}

		@Override
		protected Boolean visitOther() {
			return Boolean.FALSE;
		}
	});
}
 
Example #8
Source File: SecurityModule.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    for (Element element : privateElements.getElements()) {
        if (element instanceof Binding && isExcluded(((Binding<?>) element).getKey())) {
            continue;
        }
        element.applyTo(binder());
    }

    for (Key<?> exposedKey : privateElements.getExposedKeys()) {
        if (isExcluded(exposedKey)) {
            continue;
        }
        expose(exposedKey);
    }
}
 
Example #9
Source File: BindingUtils.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
/**
 * Resolve binding declaration source string, if possible.
 *
 * @param binding binding
 * @return binding declaration source
 */
public static String getDeclarationSource(final Binding binding) {
    String res = "UNKNOWN";
    final Object source = binding.getSource();
    if (source instanceof ElementSource) {
        final ElementSource src = (ElementSource) source;
        StackTraceElement traceElement = null;
        if (src.getDeclaringSource() instanceof StackTraceElement) {
            traceElement = (StackTraceElement) src.getDeclaringSource();
        } else if (src.getDeclaringSource() instanceof Method) {
            traceElement = (StackTraceElement) StackTraceElements.forMember((Method) src.getDeclaringSource());
        }
        if (traceElement != null) {
            res = traceElement.toString();
        }
    } else if (source instanceof Class) {
        res = ((Class) source).getName();
    }
    return res;
}
 
Example #10
Source File: Scoper.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Void visit(ExposedBinding<? extends T> binding) {
    final PrivateBinder privateBinder = this.binder.newPrivateBinder();
    final Scoper scoper = new Scoper(privateBinder, scoping);
    for(Element element : binding.getPrivateElements().getElements()) {
        if(element instanceof Binding) {
            ((Binding) element).acceptTargetVisitor(scoper);
        } else {
            element.applyTo(privateBinder);
        }
    }
    for(Key key : binding.getPrivateElements().getExposedKeys()) {
        privateBinder.expose(key);
    }
    return null;
}
 
Example #11
Source File: Bootstrap.java    From javalite with Apache License 2.0 6 votes vote down vote up
/**
 * Close all services from Guice that implement {@link Destroyable} interface.
 */
synchronized void destroy() {
    LOGGER.warn("Shutting off all services");
    Injector injector = getInjector();
    if (injector != null) {
        Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();
        bindings.forEach((key, binding) -> {
            Provider p = binding.getProvider();
            if (p != null) {
                Object service = p.get();
                if (service != null) {
                    if (Destroyable.class.isAssignableFrom(service.getClass())) {
                        try {
                            LOGGER.warn("Shutting off: " + service);
                            ((Destroyable) service).destroy();
                        } catch (Exception ex) {
                            LOGGER.error("Failed to gracefully destroy " + service + ". Moving on to destroy the rest.", ex);
                        }
                    }
                }
            }
        });
    }
}
 
Example #12
Source File: WebMappingsRenderer.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
private void renderGuiceWeb(final TreeNode filter) throws Exception {
    final List<String> servlets = new ArrayList<>();
    final List<String> filters = new ArrayList<>();

    for (Element element : Elements.getElements(Stage.TOOL, modules)) {
        if (!(element instanceof Binding)) {
            continue;
        }
        @SuppressWarnings("unchecked") final WebElementModel model =
                (WebElementModel) ((Binding) element).acceptTargetVisitor(VISITOR);
        if (model == null) {
            continue;
        }
        final String line = renderGuiceWebElement(model, element);
        if (model.getType().equals(WebElementType.FILTER)) {
            filters.add(line);
        } else {
            servlets.add(line);
        }
    }
    renderGucieWebElements(servlets, filters, filter);
}
 
Example #13
Source File: EndpointsModuleTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigureEndpoints_defaultInitParameters() {
  module = new EndpointsModule() {
    @Override
    protected void configureServlets() {
      super.configureServlets();
      configureEndpoints(URL_PATTERN, SERVICES, true);
    }
  };
  Injector injector = Guice.createInjector(module, new DummyModule());

  Visitor visitor = new Visitor();
  for (Binding<?> binding : injector.getAllBindings().values()) {
    binding.acceptTargetVisitor(visitor);
  }

  assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size());
  LinkedServletBinding servletBinding = visitor.linkedServlets.get(0);
  assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern());
  assertEquals("Wrong initialization parameter provided", "true",
      servletBinding.getInitParams().get("restricted"));
  assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider);

  ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get();
  Collection<Object> services = serviceMap.getServices();
  assertEquals("Incorrect number of services provided", 1, services.size());
  assertEquals("Service not provided correctly.", SERVICES.toArray()[0],
      services.toArray()[0].getClass());
}
 
Example #14
Source File: CodeBuilderFactory.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Create an injector that override the given injectors with the modules.
 *
 * @param originalInjector the original injector.
 * @param modules the overriding modules.
 * @return the new injector.
 */
public static Injector createOverridingInjector(Injector originalInjector, com.google.inject.Module module) {
	final Map<Key<?>, Binding<?>> bindings = originalInjector.getBindings();
	return Guice.createInjector(Modules2.mixin((binder) -> {
		for(Binding<?> binding: bindings.values()) {
			final Type typeLiteral = binding.getKey().getTypeLiteral().getType();
			if (typeLiteral != null) {
				final String typeName = typeLiteral.getTypeName();
				if (isValid(typeName)) {
					binding.applyTo(binder);
				}
			}
		}
	}, module));
}
 
Example #15
Source File: JerseyProviderInstaller.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public <T> void manualBinding(final Binder binder, final Class<T> type, final Binding<T> binding) {
    // no need to bind in case of manual binding
    final boolean hkManaged = isJerseyExtension(type);
    Preconditions.checkState(!hkManaged,
            // intentially no "at" before stacktrtace because idea may hide error in some cases
            "Provider annotated as jersey managed is declared manually in guice: %s (%s)",
            type.getName(), BindingUtils.getDeclarationSource(binding));
}
 
Example #16
Source File: ValidationModule.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
private Matcher<? super Binding<?>> staticValidationMatcher() {
    return new AbstractMatcher<Binding<?>>() {
        @Override
        public boolean matches(Binding<?> binding) {
            Class<?> candidate = binding.getKey().getTypeLiteral().getRawType();
            for (Field field : candidate.getDeclaredFields()) {
                for (Annotation annotation : field.getAnnotations()) {
                    if (hasConstraintOrValidAnnotation(annotation)) {
                        return true;
                    }
                }
            }
            return false;
        }
    };
}
 
Example #17
Source File: ModulesAnalyzedEvent.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@SuppressWarnings("checkstyle:ParameterNumber")
public ModulesAnalyzedEvent(final EventsContext context,
                            final List<Module> analyzedModules,
                            final List<Class<?>> extensions,
                            final List<Class<? extends Module>> transitiveModulesRemoved,
                            final List<Binding> bindingsRemoved) {
    super(GuiceyLifecycle.ModulesAnalyzed, context);
    this.analyzedModules = analyzedModules;
    this.extensions = extensions;
    this.transitiveModulesRemoved = transitiveModulesRemoved;
    this.bindingsRemoved = bindingsRemoved;
}
 
Example #18
Source File: ResourceInstaller.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public <T> void manualBinding(final Binder binder, final Class<T> type, final Binding<T> binding) {
    // no need to bind in case of manual binding
    final boolean hkManaged = isJerseyExtension(type);
    Preconditions.checkState(!hkManaged,
            // intentially no "at" before stacktrtace because idea may hide error in some cases
            "Resource annotated as jersey managed is declared manually in guice: %s (%s)",
            type.getName(), BindingUtils.getDeclarationSource(binding));
}
 
Example #19
Source File: InlineTaskManager.java    From staash with Apache License 2.0 5 votes vote down vote up
@Inject
public InlineTaskManager(Injector injector, EventBus eventBus) {
    this.injector = injector;
    
    LOG.info("SyncTaskManager " + this.injector);
    for (Entry<Key<?>, Binding<?>> key : this.injector.getBindings().entrySet()) {
        LOG.info("SyncTaskManager " + key.toString());
    }
}
 
Example #20
Source File: ExtensionsSupport.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
/**
 * Register extension from guice binding. Extensions annotated with {@link InvisibleForScanner} are ignored.
 *
 * @param context              configuration context
 * @param type                 extension type
 * @param manualBinding        guice binding from module
 * @param topDeclarationModule top declaration module (which was manually added by user)
 * @return true if extension recognized by installers, false otherwise
 */
public static boolean registerExtensionBinding(final ConfigurationContext context,
                                               final Class<?> type,
                                               final Binding<?> manualBinding,
                                               final Class<? extends Module> topDeclarationModule) {
    if (FeatureUtils.hasAnnotation(type, InvisibleForScanner.class)) {
        // manually hidden annotation from scanning
        return false;
    }
    final FeatureInstaller installer = findInstaller(type, context.getExtensionsHolder());
    final boolean recognized = installer != null;
    if (recognized) {
        // important to force config creation for extension from scan to allow disabling by matcher
        final ExtensionItemInfoImpl info = context.getOrRegisterBindingExtension(type, topDeclarationModule);

        // set values to unify cases of binding only extension and already known extensions (manually registered)
        info.setLazy(type.isAnnotationPresent(LazyBinding.class));
        info.setJerseyManaged(JerseyBinding.isJerseyManaged(type, context.option(JerseyExtensionsManagedByGuice)));

        Preconditions.checkState(!info.isLazy(),
                "@%s annotation must not be used on manually bound extension: %s",
                LazyBinding.class.getSimpleName(), type.getName());
        Preconditions.checkState(!info.isJerseyManaged(),
                "Extension manually bound in guice module can't be marked as jersey managed (@%s): %s",
                JerseyManaged.class.getSimpleName(), type.getName());

        info.setManualBinding(manualBinding);
        info.setInstaller(installer);
    }
    return recognized;
}
 
Example #21
Source File: DefaultJoynrRuntimeFactoryTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Test
public void testJoynrMessageProcessorAdded() throws Exception {
    createFixture();
    Injector injector = fixture.getInjector();
    List<Binding<JoynrMessageProcessor>> bindings = injector.findBindingsByType(new TypeLiteral<JoynrMessageProcessor>() {
    });
    assertEquals(1, bindings.size());
}
 
Example #22
Source File: EndpointsModuleTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private void testServletClass(
    EndpointsModule module, Class<?> expectedClass) {
  Injector injector = Guice.createInjector(module, new DummyModule());

  Visitor visitor = new Visitor();
  for (Binding<?> binding : injector.getAllBindings().values()) {
    binding.acceptTargetVisitor(visitor);
  }

  assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size());
  LinkedServletBinding servletBinding = visitor.linkedServlets.get(0);
  assertEquals("Wrong servlet class", expectedClass,
      servletBinding.getLinkedKey().getTypeLiteral().getRawType());
}
 
Example #23
Source File: XtextDocumentReconcileStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
private void initializeStrategyFactories(Injector injector) {
	List<Binding<IReconcileStrategyFactory>> bindingsByType = injector == null ? Lists
			.<Binding<IReconcileStrategyFactory>> newArrayList() : injector.findBindingsByType(TypeLiteral
			.get(IReconcileStrategyFactory.class));
	for (Binding<IReconcileStrategyFactory> binding : bindingsByType) {
		try {
			strategyFactories.add(binding.getProvider().get());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
 
Example #24
Source File: KaryonAbstractInjectorGrapher.java    From karyon with Apache License 2.0 5 votes vote down vote up
@Override
public final void graph(Injector injector, Set<Key<?>> root)
        throws IOException {
    reset();

    Iterable<Binding<?>> bindings = getBindings(injector, root);
    Map<NodeId, NodeId> aliases = resolveAliases(aliasCreator
            .createAliases(bindings));
    createNodes(nodeCreator.getNodes(bindings), aliases);
    createEdges(edgeCreator.getEdges(bindings), aliases);
    postProcess();
}
 
Example #25
Source File: IPreferenceStoreInitializer.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void initialize(IPreferenceStoreAccess access) {
	List<Binding<IPreferenceStoreInitializer>> list = injector.findBindingsByType(TypeLiteral
			.get(IPreferenceStoreInitializer.class));
	for (Binding<IPreferenceStoreInitializer> binding : list) {
		IPreferenceStoreInitializer storeInitializer = injector.getInstance(binding.getKey());
		storeInitializer.initialize(access);
	}
}
 
Example #26
Source File: IActionContributor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void contributeActions(XtextEditor editor) {
	List<Binding<IActionContributor>> bindingsByType = injector.findBindingsByType(TypeLiteral.get(IActionContributor.class));
	for (Binding<IActionContributor> binding : bindingsByType) {
		IActionContributor actionContributor = injector.getInstance(binding.getKey());
		actionContributor.contributeActions(editor);
		children.add(actionContributor);
	}
}
 
Example #27
Source File: IQuickOutlineContribution.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
protected void initialize(Injector injector) {
	contributions = Lists.newArrayList();
	List<Binding<IQuickOutlineContribution>> bindings = injector.findBindingsByType(TypeLiteral
			.get(IQuickOutlineContribution.class));
	for (Binding<IQuickOutlineContribution> binding : bindings) {
		contributions.add(injector.getInstance(binding.getKey()));
	}
}
 
Example #28
Source File: Injectors.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static <T> T findInstanceOf(Injector injector, Class<T> type) {
	for(Binding<?> binding: collectBindings(injector)) {
		if(type.isAssignableFrom(binding.getKey().getTypeLiteral().getRawType())) {
			return (T) binding.getProvider().get();
		}
	}
	throw new IllegalStateException("No implementation of [" + type + "] found!");
}
 
Example #29
Source File: AbstractComposite.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
public AbstractComposite(Class<T> clazz, Injector injector) {
	List<Binding<T>> bindingsByType = injector.findBindingsByType(TypeLiteral
			.get(clazz));
	for (Binding<T> binding : bindingsByType) {
		try {
			elements.add(binding.getProvider().get());
		} catch (RuntimeException e) {
			handle(e);
		}
	}
}
 
Example #30
Source File: IOutlineContribution.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
protected void initialize(Injector injector) {
          contributions = Lists.newArrayList();
	List<Binding<IOutlineContribution>> bindings = injector.findBindingsByType(TypeLiteral
			.get(IOutlineContribution.class));
	for (Binding<IOutlineContribution> binding : bindings) {
		contributions.add(injector.getInstance(binding.getKey()));
	}
}