private static String instantiation(Binding<?> binding) { if (binding instanceof InstanceBinding<?>) { return instanceLiteral((InstanceBinding<?>) binding); } else if (binding instanceof ProviderKeyBinding<?>) { return providerCall(((ProviderKeyBinding<?>) binding).getProviderKey()) + ".get()"; } else if (binding instanceof LinkedKeyBinding<?>) { return providerCall(((LinkedKeyBinding<?>) binding).getLinkedKey()); } else if (binding instanceof ConstructorBinding<?>) { return constructorCall((ConstructorBinding<?>) binding); } else if (binding instanceof ProviderBinding<?>) { return provider((ProviderBinding<?>) binding); } else if (binding instanceof ProviderInstanceBinding<?>) { return instantiation((ProviderInstanceBinding<?>) binding); } else { throw new DeguicifierException(); } }
private static String instanceLiteral(InstanceBinding<?> binding) { Object instance = binding.getInstance(); if (instance instanceof Boolean) { return instance.toString(); } else if (instance instanceof Character) { return "'" + instance.toString() + "'"; } else if (instance instanceof Byte) { return instance.toString(); } else if (instance instanceof Short) { return instance.toString(); } else if (instance instanceof Integer) { return instance.toString(); } else if (instance instanceof Long) { return instance.toString() + "L"; } else if (instance instanceof Float) { return instance.toString() + "f"; } else if (instance instanceof Double) { return instance.toString() + "d"; } else if (instance instanceof String) { return "\"" + escape(instance.toString()) + "\""; } else { throw new DeguicifierException(); } }
private static String scoped(final Binding<?> binding, final String statement) { return binding.acceptScopingVisitor(new BindingScopingVisitor<String>() { @Override public String visitEagerSingleton() { if (binding instanceof InstanceBinding<?>) { return statement; } throw new DeguicifierException(); } @Override public String visitScope(Scope scope) { return scopeFieldName(scope) + ".scope(null, " + guicify(statement) + ")"; } @Override public String visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) { throw new DeguicifierException(); } @Override public String visitNoScoping() { return statement; } }); }
@Override public <T> void onProvision(ProvisionInvocation<T> provision) { keys.add(provision.getBinding().getKey()); T provisioned = provision.provision(); // InstanceBindings are the only kind of binding where the key can // be an instanceof the provisioned, because it isn't linked to any // direct implementation. I guess maybe it'd also be possible // with a toConstructor binding... but we don't use that in our tests. if (provision.getBinding() instanceof InstanceBinding) { Class<? super T> expected = provision.getBinding().getKey().getRawType(); assertTrue( "expected instanceof: " + expected + ", but was: " + provisioned, expected.isInstance(provisioned)); } else { assertEquals(provision.getBinding().getKey().getRawType(), provisioned.getClass()); } }
@SuppressWarnings("rawtypes") public void testGetEntries() { List<com.google.inject.spi.Element> elements = Elements.getElements(new MapBinderWithTwoEntriesModule()); // Get the MapBinderBinding MapBinderBinding<?> mapBinderBinding = getMapBinderBinding(elements); // Execute the call to getEntries List<Map.Entry<?, Binding<?>>> mapEntries = mapBinderBinding.getEntries(elements); // Assert on the results Map.Entry<?, Binding<?>> firstEntry = mapEntries.get(0); assertEquals("keyOne", firstEntry.getKey()); Binding<?> firstBinding = firstEntry.getValue(); assertEquals("valueOne", ((InstanceBinding) firstBinding).getInstance()); Map.Entry<?, Binding<?>> secondEntry = mapEntries.get(1); assertEquals("keyTwo", secondEntry.getKey()); Binding<?> secondBinding = secondEntry.getValue(); assertEquals("valueTwo", ((InstanceBinding) secondBinding).getInstance()); }
/** Ensure bindings do not rehash their keys once returned from {@link Elements#getElements}. */ public void testBindingKeysFixedOnReturnFromGetElements() { final List<String> list = Lists.newArrayList(); Module m = new AbstractModule() { @Override protected void configure() { OptionalBinder<List<String>> b = OptionalBinder.newOptionalBinder(binder(), listOfStrings); b.setDefault().toInstance(list); list.add("A"); list.add("B"); } }; InstanceBinding<?> binding = Iterables.getOnlyElement(Iterables.filter(Elements.getElements(m), InstanceBinding.class)); Key<?> keyBefore = binding.getKey(); assertEquals(listOfStrings, keyBefore.getTypeLiteral()); list.add("C"); Key<?> keyAfter = binding.getKey(); assertSame(keyBefore, keyAfter); }
/** Ensure bindings do not rehash their keys once returned from {@link Elements#getElements}. */ public void testBindingKeysFixedOnReturnFromGetElements() { final List<String> list = Lists.newArrayList(); Module ab = new AbstractModule() { @Override protected void configure() { Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings); multibinder.addBinding().toInstance(list); list.add("A"); list.add("B"); } }; InstanceBinding<?> binding = Iterables.getOnlyElement(Iterables.filter(Elements.getElements(ab), InstanceBinding.class)); Key<?> keyBefore = binding.getKey(); assertEquals(listOfStrings, keyBefore.getTypeLiteral()); list.add("C"); Key<?> keyAfter = binding.getKey(); assertSame(keyBefore, keyAfter); }
/** * Ensure bindings do not rehash their keys once returned from {@link Elements#getElements}. */ public void testBindingKeysFixedOnReturnFromGetElements() { final List<String> list = Lists.newArrayList(); Module m = new AbstractModule() { @Override protected void configure() { OptionalBinder<List<String>> b = OptionalBinder.newOptionalBinder(binder(), listOfStrings); b.setDefault().toInstance(list); list.add("A"); list.add("B"); } }; InstanceBinding<?> binding = Iterables.getOnlyElement( Iterables.filter(Elements.getElements(m), InstanceBinding.class)); Key<?> keyBefore = binding.getKey(); assertEquals(listOfStrings, keyBefore.getTypeLiteral()); assertFalse(RehashableKeys.Keys.needsRehashing(keyBefore)); list.add("C"); Key<?> keyAfter = binding.getKey(); assertSame(keyBefore, keyAfter); assertTrue(RehashableKeys.Keys.needsRehashing(keyAfter)); }
/** * Ensure bindings do not rehash their keys once returned from {@link Elements#getElements}. */ public void testBindingKeysFixedOnReturnFromGetElements() { final List<String> list = Lists.newArrayList(); Module ab = new AbstractModule() { @Override protected void configure() { Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings); multibinder.addBinding().toInstance(list); list.add("A"); list.add("B"); } }; InstanceBinding<?> binding = Iterables.getOnlyElement( Iterables.filter(Elements.getElements(ab), InstanceBinding.class)); Key<?> keyBefore = binding.getKey(); assertEquals(listOfStrings, keyBefore.getTypeLiteral()); assertFalse(RehashableKeys.Keys.needsRehashing(keyBefore)); list.add("C"); Key<?> keyAfter = binding.getKey(); assertSame(keyBefore, keyAfter); assertTrue(RehashableKeys.Keys.needsRehashing(keyAfter)); }
public static <T> Optional<TypeLiteral<? extends T>> targetType(Injector injector, Binding<T> binding) { if(binding instanceof UntargettedBinding) { return Optional.of(binding.getKey().getTypeLiteral()); } else if(binding instanceof ConstructorBinding) { return Optional.of((TypeLiteral<? extends T>) ((ConstructorBinding) binding).getConstructor().getDeclaringType()); } else if(binding instanceof InstanceBinding) { return Optional.of(TypeLiteral.get((Class<T>) ((InstanceBinding) binding).getInstance().getClass())); } else if(binding instanceof LinkedKeyBinding) { return targetType(injector, injector.getBinding(((LinkedKeyBinding) binding).getLinkedKey())); } else if(binding instanceof ExposedBinding) { return targetType(((ExposedBinding) binding).getPrivateElements().getInjector(), binding.getKey()); } return Optional.empty(); }
/** * Adds the list of inteceptors classes from * Wrapper instances bound with a named key * equals to the name of the module. */ void addInterceptorsFromModules(Injector injector) { for (Entry<Key<?>, Binding<?>> entry : injector.getBindings().entrySet()) { Key<?> key = entry.getKey(); Binding<?> binding = entry.getValue(); if (binding instanceof InstanceBinding && isAWrapperBindingKey(key)) { Object instance = ((InstanceBinding<?>) binding).getInstance(); if (instance instanceof Wrapper) { interceptorClasses.addAll(((Wrapper) instance).interceptorClasses); } } } }
public Void visit(InstanceBinding<? extends T> instanceBinding) { T instance = instanceBinding.getInstance(); if (BindConstantBinding.isConstantKey(targetKey)) { Context context = Context.forElement(instanceBinding); bindingsCollection.addBinding(targetKey, bindingFactory.getBindConstantBinding(targetKey, instance, context)); } else { messages.add(new Message(instanceBinding.getSource(), PrettyPrinter.format("Instance binding not supported; key=%s, inst=%s", targetKey, instance))); } return null; }
@Test public void binds_instance() { given(module = new AbstractModule() { @Override protected void configure() { bind(Interface.class).toInstance(new Implementation()); } }); given(injector = Guice.createInjector(module)); when(injector.getBinding(Interface.class)); thenReturned(instanceOf(InstanceBinding.class)); }
/** * Visitor for {@link InstanceBinding}. We then render any dependency edgess that the instance * may have, which come either from {@link InjectionPoint}s (method and field) on the instance, * or on {@link Dependency}s the instance declares through the {@link HasDependencies} * interface. */ @Override public Collection<Edge> visit(InstanceBinding<?> binding) { return new ImmutableList.Builder<Edge>() .add( new BindingEdge( NodeId.newTypeId(binding.getKey()), NodeId.newInstanceId(binding.getKey()), BindingEdge.Type.NORMAL)) .addAll(newDependencyEdges(NodeId.newInstanceId(binding.getKey()), binding)) .build(); }
public void testVisitInstance() { Binding<?> binding = getBinding(Key.get(ConstructedClass.class), new InstanceModule()); Collection<Key<?>> dependencies = visitor.visit((InstanceBinding<?>) binding); // Dependencies will only be on the field- and method-injected classes. assertDependencies(dependencies, Key.get(A.class), Key.get(D.class)); }
public void testVisitInstance_instanceHasDependencies() { Binding<?> binding = getBinding(Key.get(Interface.class), new HasDependenciesModule()); Collection<Key<?>> dependencies = visitor.visit((InstanceBinding<?>) binding); // Dependencies should only be on the stated // HasDependencies#getDependencies() values assertDependencies(dependencies, Key.get(G.class)); }
@Override public String toString() { return MoreObjects.toStringHelper(InstanceBinding.class) .add("key", getKey()) .add("source", getSource()) .add("instance", instance) .toString(); }
protected void checkNotScoped() { // Scoping isn't allowed when we have only one instance. if (binding instanceof InstanceBinding) { binder.addError(SINGLE_INSTANCE_AND_SCOPE); return; } if (binding.getScoping().isExplicitlyScoped()) { binder.addError(SCOPE_ALREADY_SET); } }
private Set<String> recurseForDependencies(Injector injector, HasDependencies hasDependencies) { Set<String> elements = Sets.newHashSet(); for (Dependency<?> dependency : hasDependencies.getDependencies()) { Binding<?> binding = injector.getBinding(dependency.getKey()); HasDependencies deps = (HasDependencies) binding; if (binding instanceof InstanceBinding) { elements.add((String) ((InstanceBinding<?>) binding).getInstance()); } else { elements.addAll(recurseForDependencies(injector, deps)); } } return elements; }
public void testTwoMapBindersAreDistinct() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { MapBinder.newMapBinder(binder(), String.class, String.class) .addBinding("A") .toInstance("a"); MapBinder.newMapBinder(binder(), Integer.class, String.class) .addBinding(1) .toInstance("b"); } }); Collector collector = new Collector(); Binding<Map<String, String>> map1 = injector.getBinding(Key.get(mapOfString)); map1.acceptTargetVisitor(collector); assertNotNull(collector.mapbinding); MapBinderBinding<?> map1Binding = collector.mapbinding; Binding<Map<Integer, String>> map2 = injector.getBinding(Key.get(mapOfIntString)); map2.acceptTargetVisitor(collector); assertNotNull(collector.mapbinding); MapBinderBinding<?> map2Binding = collector.mapbinding; List<Binding<String>> bindings = injector.findBindingsByType(stringType); assertEquals("should have two elements: " + bindings, 2, bindings.size()); Binding<String> a = bindings.get(0); Binding<String> b = bindings.get(1); assertEquals("a", ((InstanceBinding<String>) a).getInstance()); assertEquals("b", ((InstanceBinding<String>) b).getInstance()); // Make sure the correct elements belong to their own sets. assertTrue(map1Binding.containsElement(a)); assertFalse(map1Binding.containsElement(b)); assertFalse(map2Binding.containsElement(a)); assertTrue(map2Binding.containsElement(b)); }
@SuppressWarnings("rawtypes") public void testGetEntriesWithDuplicateKeys() { // Set up the module Module module = new AbstractModule() { @Override protected void configure() { MapBinder<String, String> mapBinder = MapBinder.newMapBinder(binder(), String.class, String.class); mapBinder.addBinding("A").toInstance("a1"); mapBinder.addBinding("A").toInstance("a2"); mapBinder.permitDuplicates(); } }; // Get the MapBinderBinding List<com.google.inject.spi.Element> elements = Elements.getElements(module); MapBinderBinding<?> mapBinderBinding = getMapBinderBinding(elements); // Execute the call to getEntries List<Map.Entry<?, Binding<?>>> mapEntries = mapBinderBinding.getEntries(elements); // Assert on the results Map.Entry<?, Binding<?>> firstEntry = mapEntries.get(0); assertEquals("A", firstEntry.getKey()); Binding<?> firstBinding = firstEntry.getValue(); assertEquals("a1", ((InstanceBinding) firstBinding).getInstance()); Map.Entry<?, Binding<?>> secondEntry = mapEntries.get(1); assertEquals("A", secondEntry.getKey()); Binding<?> secondBinding = secondEntry.getValue(); assertEquals("a2", ((InstanceBinding) secondBinding).getInstance()); }
@SuppressWarnings("rawtypes") public void testGetEntriesWithDuplicateValues() { // Set up the module 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"); } }; // Get the MapBinderBinding List<com.google.inject.spi.Element> elements = Elements.getElements(module); MapBinderBinding<?> mapBinderBinding = getMapBinderBinding(elements); // Execute the call to getEntries List<Map.Entry<?, Binding<?>>> mapEntries = mapBinderBinding.getEntries(elements); // Assert on the results Map.Entry<?, Binding<?>> firstEntry = mapEntries.get(0); assertEquals("A", firstEntry.getKey()); Binding<?> firstBinding = firstEntry.getValue(); assertEquals("a", ((InstanceBinding) firstBinding).getInstance()); Map.Entry<?, Binding<?>> secondEntry = mapEntries.get(1); assertEquals("A", secondEntry.getKey()); Binding<?> secondBinding = secondEntry.getValue(); assertEquals("a", ((InstanceBinding) secondBinding).getInstance()); }
/** * Will find and return the {@link com.google.inject.spi.Element} that is an {@link * InstanceBinding} and binds {@code vToFind}. */ private static com.google.inject.spi.Element getInstanceBindingForValue( Object vToFind, Iterable<com.google.inject.spi.Element> elements) { for (com.google.inject.spi.Element element : elements) { if (element instanceof InstanceBinding) { Object instanceFromBinding = ((InstanceBinding<?>) element).getInstance(); if (vToFind.equals(instanceFromBinding)) { return element; } } } // No matching binding found return null; }
@SuppressWarnings("rawtypes") private Set<String> recurseForDependencies(Injector injector, HasDependencies hasDependencies) { Set<String> elements = Sets.newHashSet(); for (Dependency<?> dependency : hasDependencies.getDependencies()) { Binding<?> binding = injector.getBinding(dependency.getKey()); HasDependencies deps = (HasDependencies) binding; if (binding instanceof InstanceBinding) { elements.add((String) ((InstanceBinding) binding).getInstance()); } else { elements.addAll(recurseForDependencies(injector, deps)); } } return elements; }
private static boolean matches(Binding<?> item, BindResult<?> result) { switch (result.type) { case INSTANCE: if (item instanceof InstanceBinding && ((InstanceBinding) item).getInstance().equals(result.instance)) { return true; } break; case LINKED: if (item instanceof LinkedKeyBinding && ((LinkedKeyBinding) item).getLinkedKey().equals(result.key)) { return true; } break; case PROVIDER_INSTANCE: if (item instanceof ProviderInstanceBinding && Objects.equal( ((ProviderInstanceBinding) item).getUserSuppliedProvider().get(), result.instance)) { return true; } break; case PROVIDER_KEY: if (item instanceof ProviderKeyBinding && ((ProviderKeyBinding) item).getProviderKey().equals(result.key)) { return true; } break; } return false; }
/** * Visitor for {@link InstanceBinding}. We then render any dependency edgess that the instance * may have, which come either from {@link InjectionPoint}s (method and field) on the instance, * or on {@link Dependency}s the instance declares through the {@link HasDependencies} * interface. */ @Override public Collection<Edge> visit(InstanceBinding<?> binding) { return new ImmutableList.Builder<Edge>() .add(new BindingEdge(NodeId.newTypeId(binding.getKey()), NodeId.newInstanceId(binding.getKey()), BindingEdge.Type.NORMAL)) .addAll(newDependencyEdges(NodeId.newInstanceId(binding.getKey()), binding)) .build(); }
public void testVisitInstance() { Binding<?> binding = getBinding(Key.get(ConstructedClass.class), new InstanceModule()); Collection<Key<?>> dependencies = visitor.visit( (InstanceBinding<?>) binding); // Dependencies will only be on the field- and method-injected classes. assertDependencies(dependencies, Key.get(A.class), Key.get(D.class)); }
public void testVisitInstance_instanceHasDependencies() { Binding<?> binding = getBinding(Key.get(Interface.class), new HasDependenciesModule()); Collection<Key<?>> dependencies = visitor.visit( (InstanceBinding<?>) binding); // Dependencies should only be on the stated // HasDependencies#getDependencies() values assertDependencies(dependencies, Key.get(G.class)); }
private Set<String> recurseForDependencies(Injector injector, HasDependencies hasDependencies) { Set<String> elements = Sets.newHashSet(); for (Dependency<?> dependency : hasDependencies.getDependencies()) { Binding<?> binding = injector.getBinding(dependency.getKey()); HasDependencies deps = (HasDependencies) binding; if (binding instanceof InstanceBinding) { elements.add((String) ((InstanceBinding) binding).getInstance()); } else { elements.addAll(recurseForDependencies(injector, deps)); } } return elements; }
public void testTwoMapBindersAreDistinct() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { MapBinder.newMapBinder(binder(), String.class, String.class) .addBinding("A").toInstance("a"); MapBinder.newMapBinder(binder(), Integer.class, String.class) .addBinding(1).toInstance("b"); } }); Collector collector = new Collector(); Binding<Map<String, String>> map1 = injector.getBinding(Key.get(mapOfString)); map1.acceptTargetVisitor(collector); assertNotNull(collector.mapbinding); MapBinderBinding<?> map1Binding = collector.mapbinding; Binding<Map<Integer, String>> map2 = injector.getBinding(Key.get(mapOfIntString)); map2.acceptTargetVisitor(collector); assertNotNull(collector.mapbinding); MapBinderBinding<?> map2Binding = collector.mapbinding; List<Binding<String>> bindings = injector.findBindingsByType(stringType); assertEquals("should have two elements: " + bindings.toString(), 2, bindings.size()); Binding<String> a = bindings.get(0); Binding<String> b = bindings.get(1); assertEquals("a", ((InstanceBinding<String>) a).getInstance()); assertEquals("b", ((InstanceBinding<String>) b).getInstance()); // Make sure the correct elements belong to their own sets. assertTrue(map1Binding.containsElement(a)); assertFalse(map1Binding.containsElement(b)); assertFalse(map2Binding.containsElement(a)); assertTrue(map2Binding.containsElement(b)); }
private static boolean matches(Binding<?> item, BindResult<?> result) { switch (result.type) { case INSTANCE: if (item instanceof InstanceBinding && ((InstanceBinding) item).getInstance().equals(result.instance)) { return true; } break; case LINKED: if (item instanceof LinkedKeyBinding && ((LinkedKeyBinding) item).getLinkedKey().equals(result.key)) { return true; } break; case PROVIDER_INSTANCE: if (item instanceof ProviderInstanceBinding && Objects.equal(((ProviderInstanceBinding) item).getUserSuppliedProvider().get(), result.instance)) { return true; } break; case PROVIDER_KEY: if (item instanceof ProviderKeyBinding && ((ProviderKeyBinding) item).getProviderKey().equals(result.key)) { return true; } break; } return false; }
@Override public String toString() { return Objects.toStringHelper(InstanceBinding.class) .add("key", getKey()) .add("source", getSource()) .add("instance", instance) .toString(); }
public <T> void onProvision(ProvisionInvocation<T> provision) { keys.add(provision.getBinding().getKey()); T provisioned = provision.provision(); // InstanceBindings are the only kind of binding where the key can // be an instanceof the provisioned, because it isn't linked to any // direct implementation. I guess maybe it'd also be possible // with a toConstructor binding... but we don't use that in our tests. if (provision.getBinding() instanceof InstanceBinding) { Class<? super T> expected = provision.getBinding().getKey().getRawType(); assertTrue("expected instanceof: " + expected + ", but was: " + provisioned, expected.isInstance(provisioned)); } else { assertEquals(provision.getBinding().getKey().getRawType(), provisioned.getClass()); } }
public void testSetAndMapValueAreDistinctInSpi() { 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"); } }); Collector collector = new Collector(); Binding<Map<String, String>> mapbinding = injector.getBinding(Key.get(mapOfStringString)); mapbinding.acceptTargetVisitor(collector); assertNotNull(collector.mapbinding); Binding<Set<String>> setbinding = injector.getBinding(Key.get(setOfString)); setbinding.acceptTargetVisitor(collector); assertNotNull(collector.setbinding); // Capture the value bindings and assert we have them right -- // they'll always be in the right order because we preserve // binding order. List<Binding<String>> bindings = injector.findBindingsByType(stringType); assertEquals(2, bindings.size()); Binding<String> a = bindings.get(0); Binding<String> b = bindings.get(1); assertEquals("A", ((InstanceBinding<String>)a).getInstance()); assertEquals("b", ((InstanceBinding<String>)b).getInstance()); // Now make sure "A" belongs only to the set binding, // and "b" only belongs to the map binding. assertFalse(collector.mapbinding.containsElement(a)); assertTrue(collector.mapbinding.containsElement(b)); assertTrue(collector.setbinding.containsElement(a)); assertFalse(collector.setbinding.containsElement(b)); }