use of com.google.inject.Binding in project roboguice by roboguice.
the class SpiUtils method mapModuleTest.
@SuppressWarnings("unchecked")
private static <T> void mapModuleTest(Key<T> mapKey, TypeLiteral<?> keyType, TypeLiteral<?> valueType, Iterable<? extends Module> modules, boolean allowDuplicates, int expectedMapBindings, MapResult... results) {
Set<Element> elements = ImmutableSet.copyOf(Elements.getElements(modules));
Visitor<T> visitor = new Visitor<T>();
MapBinderBinding<T> mapbinder = null;
Map<Key<?>, Binding<?>> keyMap = Maps.newHashMap();
for (Element element : elements) {
if (element instanceof Binding) {
Binding<?> binding = (Binding<?>) element;
keyMap.put(binding.getKey(), binding);
if (binding.getKey().equals(mapKey)) {
mapbinder = (MapBinderBinding<T>) ((Binding<T>) binding).acceptTargetVisitor(visitor);
}
}
}
assertNotNull(mapbinder);
assertEquals(keyType, mapbinder.getKeyTypeLiteral());
assertEquals(valueType, mapbinder.getValueTypeLiteral());
List<MapResult> mapResults = Lists.newArrayList(results);
Key<?> mapOfProvider = mapKey.ofType(mapOfProviderOf(keyType, valueType));
Key<?> mapOfSetOfProvider = mapKey.ofType(mapOfSetOfProviderOf(keyType, valueType));
Key<?> mapOfSet = mapKey.ofType(mapOf(keyType, setOf(valueType)));
Key<?> setOfEntry = mapKey.ofType(setOf(entryOfProviderOf(keyType, valueType)));
Key<?> collectionOfProvidersOfEntry = mapKey.ofType(collectionOfProvidersOf(entryOfProviderOf(keyType, valueType)));
boolean entrySetMatch = false;
boolean entryProviderCollectionMatch = false;
boolean mapProviderMatch = false;
boolean mapSetMatch = false;
boolean mapSetProviderMatch = false;
List<Object> otherMapBindings = Lists.newArrayList();
List<Element> otherMatches = Lists.newArrayList();
List<Element> otherElements = Lists.newArrayList();
Indexer indexer = new Indexer(null);
Multimap<Object, IndexedBinding> indexedEntries = MultimapBuilder.hashKeys().hashSetValues().build();
int duplicates = 0;
for (Element element : elements) {
boolean contains = mapbinder.containsElement(element);
if (!contains) {
otherElements.add(element);
}
boolean matched = false;
Key key = null;
Binding b = null;
if (element instanceof Binding) {
b = (Binding) element;
if (b instanceof ProviderInstanceBinding) {
ProviderInstanceBinding<?> pb = (ProviderInstanceBinding<?>) b;
if (pb.getUserSuppliedProvider() instanceof ProviderMapEntry) {
// weird casting required to workaround jdk6 compilation problems
ProviderMapEntry<?, ?> pme = (ProviderMapEntry<?, ?>) (Provider) pb.getUserSuppliedProvider();
Binding<?> valueBinding = keyMap.get(pme.getValueKey());
if (indexer.isIndexable(valueBinding) && !indexedEntries.put(pme.getKey(), valueBinding.acceptTargetVisitor(indexer))) {
duplicates++;
}
}
}
key = b.getKey();
Object visited = b.acceptTargetVisitor(visitor);
if (visited instanceof MapBinderBinding) {
matched = true;
if (visited.equals(mapbinder)) {
assertTrue(contains);
} else {
otherMapBindings.add(visited);
}
}
} else if (element instanceof ProviderLookup) {
key = ((ProviderLookup) element).getKey();
}
if (!matched && key != null) {
if (key.equals(mapOfProvider)) {
matched = true;
assertTrue(contains);
mapProviderMatch = true;
} else if (key.equals(mapOfSet)) {
matched = true;
assertTrue(contains);
mapSetMatch = true;
} else if (key.equals(mapOfSetOfProvider)) {
matched = true;
assertTrue(contains);
mapSetProviderMatch = true;
} else if (key.equals(setOfEntry)) {
matched = true;
assertTrue(contains);
entrySetMatch = true;
// Validate that this binding is also a MultibinderBinding.
if (b != null) {
assertTrue(b.acceptTargetVisitor(visitor) instanceof MultibinderBinding);
}
} else if (key.equals(collectionOfProvidersOfEntry)) {
matched = true;
assertTrue(contains);
entryProviderCollectionMatch = true;
}
}
if (!matched && contains) {
otherMatches.add(element);
}
}
int otherMatchesSize = otherMatches.size();
if (allowDuplicates) {
// allow for 1 duplicate binding
otherMatchesSize--;
}
// value, ProviderLookup per value, Map.Entry per value
otherMatchesSize = otherMatchesSize / 3;
assertEquals("incorrect number of contains, leftover matches: " + otherMatches, mapResults.size() + duplicates, otherMatchesSize);
assertTrue(entrySetMatch);
assertTrue(entryProviderCollectionMatch);
assertTrue(mapProviderMatch);
assertEquals(allowDuplicates, mapSetMatch);
assertEquals(allowDuplicates, mapSetProviderMatch);
assertEquals("other MapBindings found: " + otherMapBindings, expectedMapBindings, otherMapBindings.size());
// Validate that we can construct an injector out of the remaining bindings.
Guice.createInjector(Elements.getModule(otherElements));
}
use of com.google.inject.Binding in project roboguice by roboguice.
the class ServletDefinitionPathsTest method pathInfoWithRegexMatching.
public final void pathInfoWithRegexMatching(final String requestUri, final String contextPath, String mapping, final String expectedPathInfo, final String servletPath) throws IOException, ServletException {
Injector injector = createMock(Injector.class);
Binding binding = createMock(Binding.class);
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
final boolean[] run = new boolean[1];
//get an instance of this servlet
expect(injector.getInstance(Key.get(HttpServlet.class))).andReturn(new HttpServlet() {
@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
final String path = servletRequest.getPathInfo();
if (null == expectedPathInfo) {
assertNull(String.format("expected [%s] but was [%s]", expectedPathInfo, path), path);
} else {
assertEquals(String.format("expected [%s] but was [%s]", expectedPathInfo, path), expectedPathInfo, path);
}
//assert memoizer
//noinspection StringEquality
assertSame("memo field did not work", path, servletRequest.getPathInfo());
run[0] = true;
}
});
expect(request.getRequestURI()).andReturn(requestUri);
expect(request.getServletPath()).andReturn(servletPath).anyTimes();
expect(request.getContextPath()).andReturn(contextPath);
expect(request.getAttribute(REQUEST_DISPATCHER_REQUEST)).andReturn(null);
replay(injector, binding, request);
ServletDefinition servletDefinition = new ServletDefinition(mapping, Key.get(HttpServlet.class), UriPatternType.get(UriPatternType.REGEX, mapping), new HashMap<String, String>(), null);
servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
servletDefinition.doService(request, response);
assertTrue("Servlet did not run!", run[0]);
verify(injector, binding, request);
}
use of com.google.inject.Binding in project roboguice by roboguice.
the class ServletDefinitionTest method testServletInitAndConfig.
public final void testServletInitAndConfig() throws ServletException {
Injector injector = createMock(Injector.class);
Binding binding = createMock(Binding.class);
expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
final HttpServlet mockServlet = new HttpServlet() {
};
expect(injector.getInstance(Key.get(HttpServlet.class))).andReturn(mockServlet).anyTimes();
replay(injector, binding);
//some init params
//noinspection SSBasedInspection
final Map<String, String> initParams = new ImmutableMap.Builder<String, String>().put("ahsd", "asdas24dok").put("ahssd", "asdasd124ok").build();
String pattern = "/*";
final ServletDefinition servletDefinition = new ServletDefinition(pattern, Key.get(HttpServlet.class), UriPatternType.get(UriPatternType.SERVLET, pattern), initParams, null);
ServletContext servletContext = createMock(ServletContext.class);
final String contextName = "thing__!@@44__SRV" + getClass();
expect(servletContext.getServletContextName()).andReturn(contextName);
replay(servletContext);
servletDefinition.init(servletContext, injector, Sets.<HttpServlet>newIdentityHashSet());
assertNotNull(mockServlet.getServletContext());
assertEquals(contextName, mockServlet.getServletContext().getServletContextName());
assertEquals(Key.get(HttpServlet.class).toString(), mockServlet.getServletName());
final ServletConfig servletConfig = mockServlet.getServletConfig();
final Enumeration names = servletConfig.getInitParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
assertTrue(initParams.containsKey(name));
assertEquals(initParams.get(name), servletConfig.getInitParameter(name));
}
verify(injector, binding, servletContext);
}
use of com.google.inject.Binding in project roboguice by roboguice.
the class ServletPipelineRequestDispatcherTest method testIncludeManagedServlet.
public final void testIncludeManagedServlet() throws IOException, ServletException {
String pattern = "blah.html";
final ServletDefinition servletDefinition = new ServletDefinition(pattern, Key.get(HttpServlet.class), UriPatternType.get(UriPatternType.SERVLET, pattern), new HashMap<String, String>(), null);
final Injector injector = createMock(Injector.class);
final Binding binding = createMock(Binding.class);
final HttpServletRequest requestMock = createMock(HttpServletRequest.class);
expect(requestMock.getAttribute(A_KEY)).andReturn(A_VALUE);
requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true);
requestMock.removeAttribute(REQUEST_DISPATCHER_REQUEST);
final boolean[] run = new boolean[1];
final HttpServlet mockServlet = new HttpServlet() {
protected void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
run[0] = true;
final Object o = request.getAttribute(A_KEY);
assertEquals("Wrong attrib returned - " + o, A_VALUE, o);
}
};
expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
expect(injector.getInstance(HTTP_SERLVET_KEY)).andReturn(mockServlet);
final Key<ServletDefinition> servetDefsKey = Key.get(TypeLiteral.get(ServletDefinition.class));
Binding<ServletDefinition> mockBinding = createMock(Binding.class);
expect(injector.findBindingsByType(eq(servetDefsKey.getTypeLiteral()))).andReturn(ImmutableList.<Binding<ServletDefinition>>of(mockBinding));
Provider<ServletDefinition> bindingProvider = Providers.of(servletDefinition);
expect(mockBinding.getProvider()).andReturn(bindingProvider);
replay(injector, binding, requestMock, mockBinding);
// Have to init the Servlet before we can dispatch to it.
servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
final RequestDispatcher dispatcher = new ManagedServletPipeline(injector).getRequestDispatcher(pattern);
assertNotNull(dispatcher);
dispatcher.include(requestMock, createMock(HttpServletResponse.class));
assertTrue("Include did not dispatch to our servlet!", run[0]);
verify(injector, requestMock, mockBinding);
}
use of com.google.inject.Binding in project roboguice by roboguice.
the class ServletScopesTest method testIsRequestScopedPositive.
public void testIsRequestScopedPositive() {
final Key<String> a = Key.get(String.class, named("A"));
final Key<String> b = Key.get(String.class, named("B"));
final Key<String> c = Key.get(String.class, named("C"));
final Key<String> d = Key.get(String.class, named("D"));
final Key<Object> e = Key.get(Object.class, named("E"));
final Key<String> f = Key.get(String.class, named("F"));
final Key<String> g = Key.get(String.class, named("G"));
Module requestScopedBindings = new AbstractModule() {
@Override
protected void configure() {
bind(a).to(b);
bind(b).to(c);
bind(c).toProvider(Providers.of("c")).in(ServletScopes.REQUEST);
bind(d).toProvider(Providers.of("d")).in(RequestScoped.class);
bind(e).to(AnnotatedRequestScopedClass.class);
install(new PrivateModule() {
@Override
protected void configure() {
bind(f).toProvider(Providers.of("f")).in(RequestScoped.class);
expose(f);
}
});
}
@Provides
@Named("G")
@RequestScoped
String provideG() {
return "g";
}
};
// we know the module contains only bindings
@SuppressWarnings("unchecked") List<Element> moduleBindings = Elements.getElements(requestScopedBindings);
ImmutableMap<Key<?>, Binding<?>> map = indexBindings(moduleBindings);
// linked bindings are not followed by modules
assertFalse(ServletScopes.isRequestScoped(map.get(a)));
assertFalse(ServletScopes.isRequestScoped(map.get(b)));
assertTrue(ServletScopes.isRequestScoped(map.get(c)));
assertTrue(ServletScopes.isRequestScoped(map.get(d)));
// annotated classes are not followed by modules
assertFalse(ServletScopes.isRequestScoped(map.get(e)));
assertTrue(ServletScopes.isRequestScoped(map.get(f)));
assertTrue(ServletScopes.isRequestScoped(map.get(g)));
Injector injector = Guice.createInjector(requestScopedBindings, new ServletModule());
assertTrue(ServletScopes.isRequestScoped(injector.getBinding(a)));
assertTrue(ServletScopes.isRequestScoped(injector.getBinding(b)));
assertTrue(ServletScopes.isRequestScoped(injector.getBinding(c)));
assertTrue(ServletScopes.isRequestScoped(injector.getBinding(d)));
assertTrue(ServletScopes.isRequestScoped(injector.getBinding(e)));
assertTrue(ServletScopes.isRequestScoped(injector.getBinding(f)));
assertTrue(ServletScopes.isRequestScoped(injector.getBinding(g)));
}
Aggregations