use of com.google.inject.Key in project roboguice by roboguice.
the class InjectorSpiTest method testExistingBinding.
public void testExistingBinding() {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(Foo.class);
bind(Baz.class);
}
});
// Sanity check -- ensure we return the proper binding for all existing bindings.
for (Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet()) {
assertSame(entry.getValue(), injector.getExistingBinding(entry.getKey()));
}
// Now run through specifics...
Binding<?> binding;
// 1) non-Provider Foo.class
binding = injector.getExistingBinding(Key.get(Foo.class));
assertNotNull(binding);
assertEquals(Foo.class, binding.getKey().getTypeLiteral().getRawType());
// 2) Provider<Foo> class (should already exist, because Baz @Injects it).
// the assertTrue is a bit stricter than necessary, but makes sure this works for pre-existing Provider bindings
assertTrue(injector.getAllBindings().containsKey(Key.get(new TypeLiteral<Provider<Foo>>() {
})));
binding = injector.getExistingBinding(Key.get(new TypeLiteral<Provider<Foo>>() {
}));
assertNotNull(binding);
assertEquals(Provider.class, binding.getKey().getTypeLiteral().getRawType());
assertEquals(Foo.class, ((Provider) binding.getProvider().get()).get().getClass());
// 3) non-Provider Baz.class
binding = injector.getExistingBinding(Key.get(Baz.class));
assertNotNull(binding);
assertEquals(Baz.class, binding.getKey().getTypeLiteral().getRawType());
// 4) Provider<Baz> class (should not already exist, because nothing used it yet).
// the assertFalse is a bit stricter than necessary, but makes sure this works for non-pre-existing Provider bindings
assertFalse(injector.getAllBindings().containsKey(Key.get(new TypeLiteral<Provider<Baz>>() {
})));
binding = injector.getExistingBinding(Key.get(new TypeLiteral<Provider<Baz>>() {
}));
assertNotNull(binding);
assertEquals(Provider.class, binding.getKey().getTypeLiteral().getRawType());
assertEquals(Baz.class, ((Provider) binding.getProvider().get()).get().getClass());
// 5) non-Provider Bar, doesn't exist.
assertNull(injector.getExistingBinding(Key.get(Bar.class)));
// 6) Provider Bar, doesn't exist.
assertNull(injector.getExistingBinding(Key.get(new TypeLiteral<Provider<Bar>>() {
})));
}
use of com.google.inject.Key in project roboguice by roboguice.
the class ProviderMethodsTest method testProviderMethods.
@SuppressWarnings("unchecked")
public void testProviderMethods() {
Injector injector = Guice.createInjector(this);
Bob bob = injector.getInstance(Bob.class);
assertEquals("A Bob", bob.getName());
Bob clone = injector.getInstance(Bob.class);
assertEquals("A Bob", clone.getName());
assertNotSame(bob, clone);
assertSame(bob.getDaughter(), clone.getDaughter());
Key soleBobKey = Key.get(Bob.class, Sole.class);
assertSame(injector.getInstance(soleBobKey), injector.getInstance(soleBobKey));
}
use of com.google.inject.Key in project roboguice by roboguice.
the class OverrideModuleTest method testFailsIfOverridenScopeInstanceHasBeenUsed.
public void testFailsIfOverridenScopeInstanceHasBeenUsed() {
final Scope scope = new Scope() {
public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
return unscoped;
}
@Override
public String toString() {
return "ORIGINAL SCOPE";
}
};
final Module original = new AbstractModule() {
@Override
protected void configure() {
bindScope(TestScopeAnnotation.class, scope);
bind(Date.class).in(scope);
bind(String.class).in(scope);
}
};
Module originalWrapper = new AbstractModule() {
@Override
protected void configure() {
install(original);
}
};
Module replacements = new AbstractModule() {
@Override
protected void configure() {
bindScope(TestScopeAnnotation.class, new SingleUseScope());
}
};
try {
createInjector(Modules.override(originalWrapper).with(replacements));
fail("Exception expected");
} catch (CreationException e) {
assertContains(e.getMessage(), "1) The scope for @TestScopeAnnotation is bound directly and cannot be overridden.", "original binding at " + original.getClass().getName() + ".configure(", asModuleChain(originalWrapper.getClass(), original.getClass()), "bound directly at " + original.getClass().getName() + ".configure(", asModuleChain(originalWrapper.getClass(), original.getClass()), "bound directly at " + original.getClass().getName() + ".configure(", asModuleChain(originalWrapper.getClass(), original.getClass()), "at ", replacements.getClass().getName() + ".configure(", asModuleChain(Modules.OverrideModule.class, replacements.getClass()));
}
}
use of com.google.inject.Key in project roboguice by roboguice.
the class ContextScope method scope.
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
return new Provider<T>() {
public T get() {
synchronized (ContextScope.class) {
final Stack<WeakReference<Context>> stack = getContextStack();
// The context should never be finalized as long as the provider is still in memory
final Context context = stack.peek().get();
final Map<Key<?>, Object> objectsForScope = getScopedObjectMap(context);
if (objectsForScope == null)
// May want to consider throwing an exception here (if provider is used after onDestroy())
return null;
@SuppressWarnings({ "unchecked" }) T current = (T) objectsForScope.get(key);
if (current == null && !objectsForScope.containsKey(key)) {
current = unscoped.get();
objectsForScope.put(key, current);
}
return current;
}
}
};
}
use of com.google.inject.Key in project roboguice by roboguice.
the class SpiUtils method optionalModuleTest.
@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> void optionalModuleTest(Key<T> keyType, Iterable<? extends Module> modules, int expectedOtherOptionalBindings, BindResult<?> expectedDefault, BindResult<?> expectedActual, BindResult<?> expectedUserLinkedActual) {
if (expectedUserLinkedActual != null) {
assertNull("cannot have actual if expecting user binding", expectedActual);
assertNull("cannot have default if expecting user binding", expectedDefault);
}
Set<Element> elements = ImmutableSet.copyOf(Elements.getElements(modules));
Map<Key<?>, Binding<?>> indexed = index(elements);
Key<Optional<T>> optionalKey = keyType.ofType(OptionalBinder.optionalOf(keyType.getTypeLiteral()));
Key<?> javaOptionalKey = HAS_JAVA_OPTIONAL ? keyType.ofType(OptionalBinder.javaOptionalOf(keyType.getTypeLiteral())) : null;
Visitor visitor = new Visitor();
OptionalBinderBinding<Optional<T>> optionalBinder = null;
OptionalBinderBinding<?> javaOptionalBinder = null;
Key<?> defaultKey = null;
Key<?> actualKey = null;
Binding optionalBinding = indexed.get(optionalKey);
optionalBinder = (OptionalBinderBinding<Optional<T>>) optionalBinding.acceptTargetVisitor(visitor);
if (HAS_JAVA_OPTIONAL) {
Binding javaOptionalBinding = indexed.get(javaOptionalKey);
javaOptionalBinder = (OptionalBinderBinding) javaOptionalBinding.acceptTargetVisitor(visitor);
}
// Locate the defaultKey & actualKey
for (Element element : elements) {
if (optionalBinder.containsElement(element) && element instanceof Binding) {
Binding binding = (Binding) element;
if (isSourceEntry(binding, Source.DEFAULT)) {
defaultKey = binding.getKey();
} else if (isSourceEntry(binding, Source.ACTUAL)) {
actualKey = binding.getKey();
}
}
}
assertNotNull(optionalBinder);
if (HAS_JAVA_OPTIONAL) {
assertNotNull(javaOptionalBinder);
}
assertEquals(expectedDefault == null, defaultKey == null);
assertEquals(expectedActual == null, actualKey == null);
Key<Optional<javax.inject.Provider<T>>> optionalJavaxProviderKey = keyType.ofType(optionalOfJavaxProvider(keyType.getTypeLiteral()));
Key<?> javaOptionalJavaxProviderKey = HAS_JAVA_OPTIONAL ? keyType.ofType(javaOptionalOfJavaxProvider(keyType.getTypeLiteral())) : null;
Key<Optional<Provider<T>>> optionalProviderKey = keyType.ofType(optionalOfProvider(keyType.getTypeLiteral()));
Key<?> javaOptionalProviderKey = HAS_JAVA_OPTIONAL ? keyType.ofType(javaOptionalOfProvider(keyType.getTypeLiteral())) : null;
boolean keyMatch = false;
boolean optionalKeyMatch = false;
boolean javaOptionalKeyMatch = false;
boolean optionalJavaxProviderKeyMatch = false;
boolean javaOptionalJavaxProviderKeyMatch = false;
boolean optionalProviderKeyMatch = false;
boolean javaOptionalProviderKeyMatch = false;
boolean defaultMatch = false;
boolean actualMatch = false;
List<Object> otherOptionalElements = Lists.newArrayList();
List<Element> otherContains = Lists.newArrayList();
List<Element> nonContainedElements = Lists.newArrayList();
for (Element element : elements) {
boolean contains = optionalBinder.containsElement(element);
if (HAS_JAVA_OPTIONAL) {
assertEquals(contains, javaOptionalBinder.containsElement(element));
}
if (!contains) {
nonContainedElements.add(element);
}
Key key = null;
Binding b = null;
if (element instanceof Binding) {
b = (Binding) element;
key = b.getKey();
Object visited = b.acceptTargetVisitor(visitor);
if (visited instanceof OptionalBinderBinding) {
if (visited.equals(optionalBinder)) {
assertTrue(contains);
} else if (HAS_JAVA_OPTIONAL && visited.equals(javaOptionalBinder)) {
assertTrue(contains);
} else {
otherOptionalElements.add(visited);
}
}
} else if (element instanceof ProviderLookup) {
key = ((ProviderLookup) element).getKey();
}
if (key != null && key.equals(keyType)) {
// keyType might match because a user bound it
// (which is possible in a purely absent OptionalBinder)
assertEquals(expectedDefault != null || expectedActual != null, contains);
if (contains) {
keyMatch = true;
}
} else if (key != null && key.equals(optionalKey)) {
assertTrue(contains);
optionalKeyMatch = true;
} else if (key != null && key.equals(javaOptionalKey)) {
assertTrue(contains);
javaOptionalKeyMatch = true;
} else if (key != null && key.equals(optionalJavaxProviderKey)) {
assertTrue(contains);
optionalJavaxProviderKeyMatch = true;
} else if (key != null && key.equals(javaOptionalJavaxProviderKey)) {
assertTrue(contains);
javaOptionalJavaxProviderKeyMatch = true;
} else if (key != null && key.equals(optionalProviderKey)) {
assertTrue(contains);
optionalProviderKeyMatch = true;
} else if (key != null && key.equals(javaOptionalProviderKey)) {
assertTrue(contains);
javaOptionalProviderKeyMatch = true;
} else if (key != null && key.equals(defaultKey)) {
assertTrue(contains);
if (b != null) {
// otherwise it might just be a ProviderLookup into it
assertTrue("expected: " + expectedDefault + ", but was: " + b, matches(b, expectedDefault));
defaultMatch = true;
}
} else if (key != null && key.equals(actualKey)) {
assertTrue(contains);
if (b != null) {
// otherwise it might just be a ProviderLookup into it
assertTrue("expected: " + expectedActual + ", but was: " + b, matches(b, expectedActual));
actualMatch = true;
}
} else if (contains) {
otherContains.add(element);
}
}
// only expect a keymatch if either default or actual are set
assertEquals(expectedDefault != null || expectedActual != null, keyMatch);
assertTrue(optionalKeyMatch);
assertTrue(optionalJavaxProviderKeyMatch);
assertTrue(optionalProviderKeyMatch);
assertEquals(HAS_JAVA_OPTIONAL, javaOptionalKeyMatch);
assertEquals(HAS_JAVA_OPTIONAL, javaOptionalJavaxProviderKeyMatch);
assertEquals(HAS_JAVA_OPTIONAL, javaOptionalProviderKeyMatch);
assertEquals(expectedDefault != null, defaultMatch);
assertEquals(expectedActual != null, actualMatch);
assertEquals(otherContains.toString(), 0, otherContains.size());
assertEquals("other OptionalBindings found: " + otherOptionalElements, expectedOtherOptionalBindings, otherOptionalElements.size());
// Validate that we can construct an injector out of the remaining bindings.
Guice.createInjector(Elements.getModule(nonContainedElements));
}
Aggregations