Java Examples for com.google.inject.Key

The following java examples will help you to understand the usage of com.google.inject.Key. These source code samples are taken from different open source projects.

Example 1
Project: kazuki-master  File: H2KeyValueStorageTest.java View source code
@Test
public void testDemo() throws Exception {
    final Lifecycle lifecycle = inject.getInstance(com.google.inject.Key.get(Lifecycle.class, Names.named("foo")));
    KeyValueStore store = inject.getInstance(com.google.inject.Key.get(KeyValueStore.class, Names.named("foo")));
    SchemaStore manager = inject.getInstance(com.google.inject.Key.get(SchemaStore.class, Names.named("foo")));
    lifecycle.init();
    store.clear(false, false);
    lifecycle.stop();
    lifecycle.shutdown();
    lifecycle.init();
    lifecycle.start();
    KazukiManager kzManager = inject.getBinding(com.google.inject.Key.get(KazukiManager.class, Names.named("foo"))).getProvider().get();
    Map<Class, Object> components = new LinkedHashMap<Class, Object>();
    for (ComponentDescriptor desc : kzManager.getComponents()) {
        components.put(desc.getClazz(), desc.getInstance());
    }
    Assert.assertEquals(components.get(Lifecycle.class), ((KazukiComponent) lifecycle).getComponentDescriptor().getInstance());
    Assert.assertEquals(components.get(KeyValueStore.class), ((KazukiComponent) store).getComponentDescriptor().getInstance());
    Assert.assertEquals(components.get(SchemaStore.class), ((KazukiComponent) manager).getComponentDescriptor().getInstance());
    Assert.assertFalse(store.iterators().iterator("$schema", Schema.class, SortDirection.ASCENDING).hasNext());
    manager.createSchema("foo", Foo.FOO_SCHEMA);
    try (KeyValueIterator<Schema> sIter = store.iterators().iterator("$schema", Schema.class, SortDirection.ASCENDING)) {
        Assert.assertTrue(sIter.hasNext());
        sIter.next();
        Assert.assertFalse(sIter.hasNext());
    }
    KeyValuePair<Foo> foo1KeyValuePair = store.create("foo", Foo.class, new Foo("k", "v"), TypeValidation.STRICT);
    Key foo1Key = foo1KeyValuePair.getKey();
    log.info("created key = " + foo1Key);
    Assert.assertNotNull(store.retrieve(foo1Key, Foo.class));
    KeyValuePair<Foo> foo2KeyValuePair = store.create("foo", Foo.class, new Foo("a", "b"), TypeValidation.STRICT);
    Key foo2Key = foo2KeyValuePair.getKey();
    log.info("created key = " + foo2Key);
    Assert.assertNotNull(store.retrieve(foo2Key, Foo.class));
    try (KeyValueIterator<Foo> iter = store.iterators().iterator("foo", Foo.class, SortDirection.ASCENDING)) {
        Assert.assertTrue(iter.hasNext());
        while (iter.hasNext()) {
            Foo theNext = iter.next();
            Assert.assertNotNull(theNext);
            log.info("dump all : " + dump(theNext));
        }
    }
    Foo foo1Found = store.retrieve(foo1Key, Foo.class);
    log.info("retrieved value 1 = " + dump(foo1Found));
    Foo foo2Found = store.retrieve(foo2Key, Foo.class);
    log.info("retrieved value 2 = " + dump(foo2Found));
    Map<Key, Foo> multiFound = store.multiRetrieve(ImmutableList.of(foo1Key, foo2Key), Foo.class);
    log.info("multi-retrieved values = " + dump(multiFound));
    Assert.assertEquals(multiFound.size(), 2);
    Assert.assertEquals(multiFound.get(foo1Key), foo1Found);
    Assert.assertEquals(multiFound.get(foo2Key), foo2Found);
    boolean updated = store.update(foo1Key, Foo.class, new Foo("x", "y"));
    log.info("updated? " + updated);
    Assert.assertTrue(updated);
    Foo foo1FoundAgain = store.retrieve(foo1Key, Foo.class);
    log.info("retrieved value = " + dump(foo1FoundAgain));
    Assert.assertNotSame(foo1FoundAgain, foo1Found);
    boolean deleted = store.delete(foo1Key);
    log.info("deleted? " + deleted);
    Assert.assertTrue(deleted);
    foo1Found = store.retrieve(foo1Key, Foo.class);
    log.info("retrieved value = " + dump(foo1Found));
    Assert.assertNull(foo1Found);
    lifecycle.stop();
    lifecycle.shutdown();
    lifecycle.init();
    lifecycle.start();
    foo1Found = store.retrieve(foo1Key, Foo.class);
    log.info("retrieved value = " + dump(foo1Found));
    Assert.assertNull(foo1Found);
    foo1Found = store.retrieve(foo2Key, Foo.class);
    log.info("retrieved value = " + dump(foo2Found));
    Assert.assertNotNull(foo2Found);
    store.clear(false, false);
}
Example 2
Project: play2-guice-module-master  File: RequestScopedAction.java View source code
@Override
public Result call(final Http.Context ctx) throws Throwable {
    // 1. Create a callable to define the request scope
    Callable<Result> resultCallable = ServletScopes.scopeRequest(new Callable<Result>() {

        @Override
        public Result call() throws Exception {
            try {
                // 2. Call the controller Action
                return delegate.call(ctx);
            } catch (Throwable throwable) {
                throw new RuntimeException(throwable);
            }
        }
    }, new HashMap<Key<?>, Object>());
    // 3. Run it
    return resultCallable.call();
}
Example 3
Project: ProjectAres-master  File: ComponentRendererRegistry.java View source code
@Override
public ComponentRenderer load(final Class<? extends BaseComponent> type) throws Exception {
    ConfigurationException originalException = null;
    for (Class c = type; BaseComponent.class.isAssignableFrom(c); c = c.getSuperclass()) {
        try {
            return (ComponentRenderer) injector.getInstance(Key.get(ComponentRenderers.rendererType(c)));
        } catch (ConfigurationException e) {
            if (originalException == null)
                originalException = e;
        }
    }
    throw new IllegalStateException("Can't find a renderer for component type " + type, originalException);
}
Example 4
Project: krail-master  File: DefaultViewFactory.java View source code
/* (non-Javadoc)
     * @see uk.q3c.krail.core.view.ViewFactory#get(java.lang.Class)
     */
@Override
public <T extends KrailView> T get(Class<T> viewClass) {
    TypeLiteral<T> typeLiteral = TypeLiteral.get(viewClass);
    Key<T> key = Key.get(typeLiteral);
    log.debug("getting or retrieving instance of {}", viewClass);
    T view = injector.getInstance(key);
    log.debug("Calling view.readFromEnvironment()");
    view.init();
    return view;
}
Example 5
Project: woinject-master  File: WORequestScope.java View source code
/*
     * (non-Javadoc)
     * 
     * @see com.google.inject.Scope#scope(com.google.inject.Key,
     * com.google.inject.Provider)
     */
public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
    final String name = key.toString();
    return new Provider<T>() {

        public T get() {
            WORequest request = request();
            if (request == null) {
                throw new OutOfScopeException("Cannot access scoped object. Either the request has not been dispatched yet, or its cycle has ended.");
            }
            synchronized (request) {
                Object object = request.userInfoForKey(name);
                if (object == NullValue) {
                    return null;
                }
                @SuppressWarnings("unchecked") T t = (T) object;
                if (t == null) {
                    t = creator.get();
                    request.setUserInfoForKey(t == null ? NullValue : t, name);
                }
                return t;
            }
        }
    };
}
Example 6
Project: airlift-master  File: GuiceInjectorIterator.java View source code
private void checkReset() {
    if (!needsReset) {
        return;
    }
    needsReset = false;
    currentClass = null;
    if (currentDependencyIterator != null) {
        if (currentDependencyIterator.hasNext()) {
            currentClass = currentDependencyIterator.next();
        } else {
            currentDependencyIterator = null;
        }
    }
    while ((currentClass == null) && keyIterator.hasNext()) {
        Key<?> key = keyIterator.next();
        currentClass = parseKey(visited, key);
        if (currentClass == null) {
            continue;
        }
        currentDependencyIterator = new GuiceDependencyIterator(key.getTypeLiteral());
        currentDependencyIterator = currentDependencyIterator.substituteVisitedSet(visited);
    }
}
Example 7
Project: che-master  File: ConfigurationProperties.java View source code
public Map<String, String> getProperties(String namePattern) {
    final Pattern pattern = Pattern.compile(namePattern);
    final Map<String, String> result = new HashMap<>();
    for (Map.Entry<Key<?>, Binding<?>> keyBindingEntry : injectorProvider.get().getAllBindings().entrySet()) {
        final Key<?> key = keyBindingEntry.getKey();
        final Annotation annotation = key.getAnnotation();
        if (annotation instanceof com.google.inject.name.Named && key.getTypeLiteral().getRawType() == String.class) {
            final String name = ((com.google.inject.name.Named) annotation).value();
            if (name != null && pattern.matcher(name).matches()) {
                final String value = (String) keyBindingEntry.getValue().getProvider().get();
                result.put(name, value);
            }
        }
    }
    return result;
}
Example 8
Project: DevTools-master  File: ConfigurationProperties.java View source code
public Map<String, String> getProperties(String namePattern) {
    final Pattern pattern = Pattern.compile(namePattern);
    final Map<String, String> result = new HashMap<>();
    for (Map.Entry<Key<?>, Binding<?>> keyBindingEntry : injectorProvider.get().getAllBindings().entrySet()) {
        final Key<?> key = keyBindingEntry.getKey();
        final Annotation annotation = key.getAnnotation();
        if (annotation instanceof com.google.inject.name.Named && key.getTypeLiteral().getRawType() == String.class) {
            final String name = ((com.google.inject.name.Named) annotation).value();
            if (name != null && pattern.matcher(name).matches()) {
                final String value = (String) keyBindingEntry.getValue().getProvider().get();
                result.put(name, value);
            }
        }
    }
    return result;
}
Example 9
Project: fabricator-master  File: NamedDeserializerTest.java View source code
@Test
public void testConfiguredDeserializer() throws Exception {
    final Properties props = new Properties();
    props.put("1.foo.type", "impl");
    props.put("1.foo.serializer", "jackson");
    props.put("2.foo.type", "impl");
    props.put("2.foo.serializer", "base64");
    props.put("3.foo.type", "impl");
    props.put("3.foo.serializer", "string");
    props.put("4.foo.type", "impl");
    props.put("4.foo.serializer", "custom");
    ConfigurationManager.loadProperties(props);
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            install(new ArchaiusConfigurationModule());
            install(new FooModule());
            install(new ComponentModuleBuilder<SomeType>().manager(SynchronizedComponentManager.class).implementation(SomeTypeImpl1.class).build(SomeType.class));
            bind(Foo.class).annotatedWith(Names.named("custom")).toInstance(new Foo() {

                @Override
                public <T> String call(T entity) throws Exception {
                    return "custom";
                }
            });
        }
    });
    ComponentManager<SomeType> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeType>>() {
    }));
    SomeType o1 = manager.get("1");
    SomeType o2 = manager.get("2");
    SomeType o3 = manager.get("3");
    SomeType o4 = manager.get("4");
    LOG.info(o1.serialize("foo"));
    LOG.info(o2.serialize("foo"));
    LOG.info(o3.serialize("foo"));
    LOG.info(o4.serialize("foo"));
}
Example 10
Project: github-android-master  File: ScopeBase.java View source code
public T get() {
    Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key);
    @SuppressWarnings("unchecked") T current = (T) scopedObjects.get(key);
    if (current == null && !scopedObjects.containsKey(key)) {
        current = unscoped.get();
        scopedObjects.put(key, current);
    }
    return current;
}
Example 11
Project: google-gin-master  File: GenericsGinModule.java View source code
protected void configure() {
    // Example of TypeLiteral --> TypeLiteral
    bind(new TypeLiteral<List<String>>() {
    }).to(new TypeLiteral<ArrayList<String>>() {
    });
    // Example of TypeLiteral --> Key
    // Note that this will make it resolve to what we bound LinkedList to below
    bind(new TypeLiteral<List<Integer>>() {
    }).to(Key.get(new TypeLiteral<LinkedList<Integer>>() {
    }));
    bindConstant().annotatedWith(Names.named("foo")).to("foo");
    bindConstant().annotatedWith(Names.named("bar")).to(3);
    bind(new TypeLiteral<List<? super String>>() {
    }).to(CharSequenceList.class);
}
Example 12
Project: LimeWire-Pirate-Edition-master  File: Modules.java View source code
@SuppressWarnings("unchecked")
public void configure(Binder binder) {
    // These types cannot be rebound.
    Key loggerKey = Key.get(Logger.class);
    Key injectorKey = Key.get(Injector.class);
    Key stageKey = Key.get(Stage.class);
    for (Map.Entry<Key<?>, Binding<?>> entry : parent.getAllBindings().entrySet()) {
        Key key = entry.getKey();
        Binding<?> binding = entry.getValue();
        Scope scope = MoreScopes.getLinkedScope(binding);
        if (!key.equals(loggerKey) && !key.equals(injectorKey) && !key.equals(stageKey) && !key.getTypeLiteral().getRawType().equals(Provider.class)) {
            binder.bind(key).toProvider(binding.getProvider()).in(scope);
        }
    }
}
Example 13
Project: limewire5-ruby-master  File: LimeWireCoreModuleTest.java View source code
public void testConnectionDispatcher() {
    Injector injector = Guice.createInjector(new LimeWireCoreModule(ActivityCallbackAdapter.class));
    ConnectionDispatcher globalInstance = injector.getInstance(Key.get(ConnectionDispatcher.class, Names.named("global")));
    ConnectionDispatcher localInstance = injector.getInstance(Key.get(ConnectionDispatcher.class, Names.named("local")));
    assertNotSame(globalInstance, localInstance);
    Provider<ConnectionDispatcher> localProvider = injector.getProvider(Key.get(ConnectionDispatcher.class, Names.named("local")));
    assertSame(localInstance, localProvider.get());
    assertSame(localProvider.get(), localProvider.get());
    Provider<ConnectionDispatcher> globalProvider = injector.getProvider(Key.get(ConnectionDispatcher.class, Names.named("global")));
    assertSame(globalInstance, globalProvider.get());
    assertSame(globalProvider.get(), globalProvider.get());
}
Example 14
Project: netflix-commons-master  File: ConcurrencyModuleTest.java View source code
@Test
public void shouldUseOverrideModule() {
    Injector injector = LifecycleInjector.builder().withRootModule(ConcurrencyModule.class).withBootstrapModule(new BootstrapModule() {

        @Override
        public void configure(BootstrapBinder binder) {
            binder.bind(ConcurrencyModule.class).toInstance(new ConcurrencyModule() {

                @Override
                protected void configure() {
                }
            });
        }
    }).build().createInjector();
    try {
        ScheduledExecutorService service = injector.getInstance(Key.get(ScheduledExecutorService.class, Background.class));
        Assert.fail("Binding shouldn't exist");
    } catch (ConfigurationException e) {
    }
}
Example 15
Project: sisu.inject-master  File: URLTypeConverterTest.java View source code
public void testURLConversion() {
    final URL url = Guice.createInjector(new URLTypeConverter(), new AbstractModule() {

        @Override
        protected void configure() {
            bindConstant().annotatedWith(Names.named("url")).to("http://127.0.0.1/");
        }
    }).getInstance(Key.get(URL.class, Names.named("url")));
    assertEquals("http://127.0.0.1/", url.toString());
}
Example 16
Project: sitebricks-master  File: PersistAopModule.java View source code
@Override
protected void configure() {
    Key<Persister> persisterKey = module.selectorKey(Persister.class);
    WorkInterceptor workInterceptor = new WorkInterceptor(persisterKey);
    TransactionInterceptor transactionInterceptor = new TransactionInterceptor(persisterKey);
    requestInjection(workInterceptor);
    requestInjection(transactionInterceptor);
    Matcher<AnnotatedElement> workMatcher = annotatedWith(Work.class);
    Matcher<AnnotatedElement> txnMatcher = annotatedWith(Transactional.class);
    // Visible persistence APIs.
    if (module.selector != null) {
        workMatcher = workMatcher.and(annotatedWith(module.selector));
        txnMatcher = txnMatcher.and(annotatedWith(module.selector));
    }
    bindInterceptor(any(), workMatcher, workInterceptor);
    bindInterceptor(any(), txnMatcher, transactionInterceptor);
}
Example 17
Project: test-injector-master  File: Keys.java View source code
private static Key<?> getFieldKey(Field field, TypeLiteral<?> typeLiteral) {
    List<Annotation> annotations = getElementAnnotations(field, BindingAnnotation.class);
    if (annotations.size() == 0) {
        return Key.get(typeLiteral);
    }
    if (annotations.size() == 1) {
        return Key.get(typeLiteral, annotations.get(0));
    }
    throw new MoreThanOneBindingAnnotationException(field, annotations);
}
Example 18
Project: thucydides-master  File: Listeners.java View source code
public static StepListener getStatisticsListener() {
    try {
        return Injectors.getInjector().getInstance(Key.get(StepListener.class, Statistics.class));
    } catch (Throwable statisticsListenerException) {
        LOGGER.error("Failed to create the statistics listener - possible database configuration issue", statisticsListenerException);
    }
    return null;
}
Example 19
Project: guice-master  File: MultiModuleDispatchIntegrationTest.java View source code
public final void testDispatchRequestToManagedPipeline() throws ServletException, IOException {
    final Injector injector = Guice.createInjector(new ServletModule() {

        @Override
        protected void configureServlets() {
            filter("/*").through(TestFilter.class);
            // These filters should never fire
            filter("*.jsp").through(Key.get(TestFilter.class));
        }
    }, new ServletModule() {

        @Override
        protected void configureServlets() {
            filter("*.html").through(TestFilter.class);
            filter("/*").through(Key.get(TestFilter.class));
            // These filters should never fire
            filter("/index/*").through(Key.get(TestFilter.class));
        }
    });
    final FilterPipeline pipeline = injector.getInstance(FilterPipeline.class);
    pipeline.initPipeline(null);
    //create ourselves a mock request with test URI
    HttpServletRequest requestMock = createMock(HttpServletRequest.class);
    expect(requestMock.getRequestURI()).andReturn("/index.html").anyTimes();
    expect(requestMock.getContextPath()).andReturn("").anyTimes();
    //dispatch request
    replay(requestMock);
    pipeline.dispatch(requestMock, null, createMock(FilterChain.class));
    pipeline.destroyPipeline();
    verify(requestMock);
    assertTrue("lifecycle states did not" + " fire correct number of times-- inits: " + inits + "; dos: " + doFilters + "; destroys: " + destroys, inits == 1 && doFilters == 3 && destroys == 1);
}
Example 20
Project: sisu-guice-master  File: TestScope.java View source code
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> provider) {
    return new Provider<T>() {

        @Override
        @SuppressWarnings({ "unchecked" })
        public T get() {
            T t = (T) inScopeObjectsMap.get(key);
            if (t == null) {
                t = provider.get();
                inScopeObjectsMap.put(key, t);
            }
            return t;
        }
    };
}
Example 21
Project: acai-master  File: TestScope.java View source code
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscopedProvider) {
    return () -> {
        Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key);
        @SuppressWarnings("unchecked") T scopedObject = (T) scopedObjects.get(key);
        if (scopedObject == null && !scopedObjects.containsKey(key)) {
            scopedObject = unscopedProvider.get();
            scopedObjects.put(key, scopedObject);
        }
        return scopedObject;
    };
}
Example 22
Project: agit-master  File: ScopeBase.java View source code
public T get() {
    Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key);
    @SuppressWarnings("unchecked") T current = (T) scopedObjects.get(key);
    if (current == null && !scopedObjects.containsKey(key)) {
        current = unscoped.get();
        scopedObjects.put(key, current);
    }
    return current;
}
Example 23
Project: Android_Example_Projects-master  File: ScopeBase.java View source code
public T get() {
    Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key);
    @SuppressWarnings("unchecked") T current = (T) scopedObjects.get(key);
    if (current == null && !scopedObjects.containsKey(key)) {
        current = unscoped.get();
        scopedObjects.put(key, current);
    }
    return current;
}
Example 24
Project: aokp-gerrit-master  File: OptionHandlers.java View source code
private static ImmutableMap<Class<?>, Provider<OptionHandlerFactory<?>>> build(Injector i) {
    ImmutableMap.Builder<Class<?>, Provider<OptionHandlerFactory<?>>> map = ImmutableMap.builder();
    for (; i != null; i = i.getParent()) {
        for (Entry<Key<?>, Binding<?>> e : i.getBindings().entrySet()) {
            TypeLiteral<?> type = e.getKey().getTypeLiteral();
            if (type.getRawType() == OptionHandlerFactory.class && e.getKey().getAnnotation() == null && type.getType() instanceof ParameterizedType) {
                map.put(getType(type), cast(e.getValue()).getProvider());
            }
        }
    }
    return map.build();
}
Example 25
Project: autobind-master  File: ExampleApp.java View source code
@Override
public void run() {
    Injector injector = Guice.createInjector(StartupModule.create(ASMClasspathScanner.class, PackageFilter.create(ExampleApp.class)));
    System.out.println(injector.getInstance(Key.get(Example.class, FirstMarker.class)).sayHello());
    System.out.println(injector.getInstance(Key.get(Example.class, SecondMarker.class)).sayHello());
}
Example 26
Project: browsermob-proxy-master  File: ConfigModule.java View source code
@Override
public void configure(Binder binder) {
    OptionParser parser = new OptionParser();
    ArgumentAcceptingOptionSpec<Integer> portSpec = parser.accepts("port", "The port to listen on").withOptionalArg().ofType(Integer.class).defaultsTo(8080);
    ArgumentAcceptingOptionSpec<Integer> userAgentCacheSpec = parser.accepts("uaCache", "The number of days to cache a database of User-Agent records from http://user-agent-string.info").withOptionalArg().ofType(Integer.class).defaultsTo(1);
    parser.acceptsAll(asList("help", "?"), "This help text");
    OptionSet options = parser.parse(args);
    if (options.has("?")) {
        try {
            parser.printHelpOn(System.out);
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }
    binder.bind(Key.get(Integer.class, new NamedImpl("port"))).toInstance(portSpec.value(options));
    Integer userAgentCacheDays = userAgentCacheSpec.value(options);
    if (BrowserMobHttpClient.PARSER instanceof OnlineUpdateUASparser) {
        ((OnlineUpdateUASparser) BrowserMobHttpClient.PARSER).setUpdateInterval(1000 * 60 * 60 * 24 * userAgentCacheDays);
    }
}
Example 27
Project: CC-master  File: HadoopCounterTest.java View source code
/**Checks that counters do not carry their values between pipeline stages. */
@Test
public void testCounterResetsAcrossStages() throws IOException, InterruptedException {
    TableAdmin tableAdmin = Guice.createInjector(new UnibeModule()).getInstance(TableAdmin.class);
    try (Table<Integer> in = tableAdmin.createTemporaryTable(FAMILY);
        Table<Integer> eff = tableAdmin.createTemporaryTable(FAMILY)) {
        Module m = new CellsModule() {

            @Override
            protected void configure() {
                installCounter(IOExceptions.class, new HadoopCounterModule());
                installCounter(UsrExceptions.class, new HadoopCounterModule());
                installTable(In.class, new TypeLiteral<Integer>() {
                }, IntegerCodec.class, new HBaseStorage(), new HBaseTableModule<>(in));
            }
        };
        Injector inj = Guice.createInjector(m, new UnibeModule());
        try (Sink<Integer> s = inj.getInstance(Key.get(new TypeLiteral<Sink<Integer>>() {
        }, In.class))) {
            for (Integer i : LocalCounterTest.generateSequence(1000)) {
                s.write(i);
            }
        }
        HadoopPipeline<Integer, Integer> pipe = HadoopPipeline.fromTableToTable(inj.getInstance(Configuration.class), in, eff);
        inj.getInstance(LocalCounterTest.Runner.class).run(pipe);
    // TODO: add assertions.
    }
}
Example 28
Project: cdap-master  File: MetadataServiceModule.java View source code
@Override
protected void configure() {
    Multibinder<HttpHandler> handlerBinder = Multibinder.newSetBinder(binder(), HttpHandler.class, Names.named(Constants.Metadata.HANDLERS_NAME));
    CommonHandlers.add(handlerBinder);
    handlerBinder.addBinding().to(MetadataHttpHandler.class);
    handlerBinder.addBinding().to(LineageHandler.class);
    expose(Key.get(new TypeLiteral<Set<HttpHandler>>() {
    }, Names.named(Constants.Metadata.HANDLERS_NAME)));
    bind(MetadataAdmin.class).to(DefaultMetadataAdmin.class);
    expose(MetadataAdmin.class);
}
Example 29
Project: checklistbank-master  File: MyBatisServiceITBase.java View source code
@Before
public void init() throws Exception {
    Module module = new ChecklistBankServiceMyBatisModule(dbSetup.getProperties());
    injector = Guice.createInjector(module);
    if (annotationType != null) {
        service = injector.getInstance(Key.get(serviceClass, annotationType));
    } else {
        service = injector.getInstance(serviceClass);
    }
}
Example 30
Project: ChineseGithub-master  File: ScopeBase.java View source code
public T get() {
    Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key);
    @SuppressWarnings("unchecked") T current = (T) scopedObjects.get(key);
    if (current == null && !scopedObjects.containsKey(key)) {
        current = unscoped.get();
        scopedObjects.put(key, current);
    }
    return current;
}
Example 31
Project: cucumber-jvm-master  File: SequentialScenarioScope.java View source code
/**
     * Scopes a provider. The returned provider returns objects from this scope.
     * If an object does not exist in this scope, the provider can use the given
     * unscoped provider to retrieve one.
     * <p/>
     * <p>Scope implementations are strongly encouraged to override
     * {@link Object#toString} in the returned provider and include the backing
     * provider's {@code toString()} output.
     *
     * @param key      binding key
     * @param unscoped locates an instance when one doesn't already exist in this
     *                 scope.
     * @return a new provider which only delegates to the given unscoped provider
     *         when an instance of the requested object doesn't already exist in this
     *         scope
     */
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
    return new Provider<T>() {

        public T get() {
            if (scenarioValues == null) {
                throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
            }
            @SuppressWarnings("unchecked") T current = (T) scenarioValues.get(key);
            if (current == null && !scenarioValues.containsKey(key)) {
                current = unscoped.get();
                scenarioValues.put(key, current);
            }
            return current;
        }
    };
}
Example 32
Project: datakernel-master  File: StandardMBeansRegistrationTest.java View source code
@Test
public void itShouldRegisterStandardMBeans() throws Exception {
    final ServiceStub service = new ServiceStub();
    context.checking(new Expectations() {

        {
            oneOf(mBeanServer).registerMBean(with(service), with(objectname(domain + ":type=ServiceStub")));
        }
    });
    Key<?> key = Key.get(ServiceStub.class);
    jmxRegistry.registerSingleton(key, service, null);
}
Example 33
Project: gerrit-master  File: OptionHandlers.java View source code
private static ImmutableMap<Class<?>, Provider<OptionHandlerFactory<?>>> build(Injector i) {
    ImmutableMap.Builder<Class<?>, Provider<OptionHandlerFactory<?>>> map = ImmutableMap.builder();
    for (; i != null; i = i.getParent()) {
        for (Entry<Key<?>, Binding<?>> e : i.getBindings().entrySet()) {
            TypeLiteral<?> type = e.getKey().getTypeLiteral();
            if (type.getRawType() == OptionHandlerFactory.class && e.getKey().getAnnotation() == null && type.getType() instanceof ParameterizedType) {
                map.put(getType(type), cast(e.getValue()).getProvider());
            }
        }
    }
    return map.build();
}
Example 34
Project: google-guice-master  File: ContextScopeTest.java View source code
@Test
public void shouldHaveTwoItemsInScopeMapAfterOnCreate() throws Exception {
    final ActivityController<B> bController = Robolectric.buildActivity(B.class);
    final B b = bController.get();
    assertThat(b.getScopedObjectMap().size(), equalTo(0));
    bController.create();
    boolean found = false;
    for (Object o : b.getScopedObjectMap().values()) if (o == b)
        found = true;
    assertTrue("Couldn't find context in scope map", found);
    assertTrue(b.getScopedObjectMap().containsKey(Key.get(C.class)));
}
Example 35
Project: governator-master  File: ProvisionMetricsModuleTest.java View source code
@Test
public void confirmMetricsIncludePostConstruct() {
    try (LifecycleInjector injector = InjectorBuilder.fromModules(new ProvisionDebugModule(), new AbstractModule() {

        @Override
        protected void configure() {
            bind(Foo.class).asEagerSingleton();
        }
    }).traceEachElement(new ProvisionListenerTracingVisitor()).createInjector()) {
        ProvisionMetrics metrics = injector.getInstance(ProvisionMetrics.class);
        KeyTrackingVisitor keyTracker = new KeyTrackingVisitor(Key.get(Foo.class));
        metrics.accept(keyTracker);
        Assert.assertNotNull(keyTracker.getElement());
        Assert.assertTrue(keyTracker.getElement().getTotalDuration(TimeUnit.MILLISECONDS) > 300);
    }
}
Example 36
Project: guice-automatic-injection-master  File: ExampleApp.java View source code
@Override
public void run() {
    Injector injector = Guice.createInjector(StartupModule.create(ASMClasspathScanner.class, PackageFilter.create(ExampleApp.class)));
    System.out.println(injector.getInstance(Key.get(Example.class, FirstMarker.class)).sayHello());
    System.out.println(injector.getInstance(Key.get(Example.class, SecondMarker.class)).sayHello());
}
Example 37
Project: hudson.core-master  File: SmoothieExtensionLocator.java View source code
/**
     * Look up extension type lists by asking the container for types with any {@link javax.inject.Qualifier} adorned annotation.
     */
public <T> List<ExtensionComponent<T>> locate(final Class<T> type) {
    checkNotNull(type);
    if (log.isDebugEnabled()) {
        log.debug("Finding extensions: {}", type.getName());
    }
    List<ExtensionComponent<T>> components = new ArrayList<ExtensionComponent<T>>();
    for (BeanEntry<Annotation, T> item : container.locate(Key.get(type))) {
        try {
            // Use our container for extendability and logging simplicity.
            SmoothieComponent<T> component = new SmoothieComponent<T>(item);
            log.debug("Found: {}", component);
            if (component.getInstance() != null) {
                // filter out null components (ie. uninitialized @Extension fields)
                components.add(component);
            }
        } catch (Throwable e) {
            if (SmoothieComponent.isOptional(item)) {
                log.debug("Failed to create optional extension", e);
            } else {
                log.warn("Failed to create extension", e);
            }
        }
    }
    if (log.isDebugEnabled()) {
        if (components.isEmpty()) {
            log.debug("No components of type '{}' discovered", type.getName());
        } else {
            log.debug("Found {} {} components", components.size(), type.getName());
        }
    }
    return components;
}
Example 38
Project: jbehave-core-master  File: GuiceStepsFactory.java View source code
/**
     * Adds steps types from given injector and recursively its parent
     * 
     * @param injector the current Inject
     * @param types the List of steps types
     */
private void addTypes(Injector injector, List<Class<?>> types) {
    for (Binding<?> binding : injector.getBindings().values()) {
        Key<?> key = binding.getKey();
        Type type = key.getTypeLiteral().getType();
        if (hasAnnotatedMethods(type)) {
            types.add(((Class<?>) type));
        }
    }
    if (injector.getParent() != null) {
        addTypes(injector.getParent(), types);
    }
}
Example 39
Project: JibbrJabbr-master  File: CoreModuleTest.java View source code
@Test
public void testRunningBuild() {
    // this should be enough to test that the core module builds
    Injector injector = Guice.createInjector(Stage.PRODUCTION, new CoreModule(new String[0], new BootstrapClassPath()));
    // force it to try to instantiate everything
    injector.getInstance(JJServerLifecycle.class);
    // and for now this lives here - a vital inventory! we must have the emergency logger configured or we
    // will lose errors and have no idea what is broken
    Map<Class<? extends Annotation>, Logger> loggers = injector.getInstance(Key.get(new TypeLiteral<Map<Class<? extends Annotation>, Logger>>() {
    }));
    assertTrue(loggers.containsKey(EmergencyLogger.class));
}
Example 40
Project: jooby-master  File: AkkaTest.java View source code
@SuppressWarnings("unchecked")
@Test
public void defaults() throws Exception {
    new MockUnit(Env.class, Config.class, Binder.class, ActorSystem.class).expect( unit -> {
        unit.mockStatic(ActorSystem.class);
        expect(ActorSystem.create("default", unit.get(Config.class))).andReturn(unit.get(ActorSystem.class));
    }).expect( unit -> {
        Env env = unit.get(Env.class);
        expect(env.serviceKey()).andReturn(new Env.ServiceKey());
        ActorSystem sys = unit.get(ActorSystem.class);
        LinkedBindingBuilder<ActorSystem> lbbSys = unit.mock(LinkedBindingBuilder.class);
        lbbSys.toInstance(sys);
        lbbSys.toInstance(sys);
        Binder binder = unit.get(Binder.class);
        expect(binder.bind(Key.get(ActorSystem.class, Names.named("default")))).andReturn(lbbSys);
        expect(binder.bind(Key.get(ActorSystem.class))).andReturn(lbbSys);
    }).run( unit -> {
        new Akka().configure(unit.get(Env.class), unit.get(Config.class), unit.get(Binder.class));
    });
}
Example 41
Project: js-dossier-master  File: ExplicitScope.java View source code
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
    return () -> {
        if (scope == null) {
            throw new OutOfScopeException("Not in scope");
        }
        Object value = scope.get(key);
        if (value == null) {
            T provided = unscoped.get();
            if (provided instanceof CircularDependencyProxy) {
                return provided;
            }
            value = (provided == null) ? NULL_SENTINEL : provided;
            scope.put(key, value);
        }
        @SuppressWarnings("unchecked") T result = (value != NULL_SENTINEL) ? (T) value : null;
        return result;
    };
}
Example 42
Project: judochop-master  File: CustomShiroWebModule.java View source code
@Override
protected void configureShiroWeb() {
    addFilterChain("/logout", LOGOUT);
    addFilterChain("/VAADIN/*", AUTHC_BASIC);
    addFilterChain("/auth/**", Key.get(RestFilter.class));
    bindRealm().to(ShiroRealm.class).in(Singleton.class);
//        bindConstant().annotatedWith(Names.named("shiro.loginUrl")).to("/login.jsp");
//        bindConstant().annotatedWith(Names.named("shiro.globalSessionTimeout")).to(3600000L);//1 hour
//        bindConstant().annotatedWith(Names.named("shiro.usernameParam")).to("user");
//        bindConstant().annotatedWith(Names.named("shiro.passwordParam")).to("pass");
//        bindConstant().annotatedWith(Names.named("shiro.successUrl")).to("/index.jsp");
//        bindConstant().annotatedWith(Names.named("shiro.failureKeyAttribute")).to("shiroLoginFailure");
//        bindConstant().annotatedWith(Names.named("shiro.unauthorizedUrl")).to("/denied.jsp");
//        bindConstant().annotatedWith(Names.named("shiro.redirectUrl")).to("/login.jsp");
}
Example 43
Project: juzu-master  File: GuiceScope.java View source code
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
    return new Provider<T>() {

        public T get() {
            GuiceScoped scoped = (GuiceScoped) controller.get(scope, key);
            if (scoped == null) {
                scoped = new GuiceScoped(unscoped.get());
                controller.put(scope, key, scoped);
            }
            return (T) scoped.o;
        }
    };
}
Example 44
Project: komma-master  File: CompositionTestCase.java View source code
protected Module createModule() {
    return new CompositionModule<String>() {

        @Override
        protected void configure() {
            super.configure();
            bind(new Key<ObjectFactory<String>>() {
            }).to(new TypeLiteral<DefaultObjectFactory<String>>() {
            });
            bind(new TypeLiteral<ClassResolver<String>>() {
            });
        }

        @Override
        protected void initRoleMapper(RoleMapper<String> roleMapper, TypeFactory<String> typeFactory) {
            CompositionTestCase.this.roleMapper = roleMapper;
            super.initRoleMapper(roleMapper, typeFactory);
            CompositionTestCase.this.initRoleMapper(roleMapper);
        }

        @Provides
        @Singleton
        protected TypeFactory<String> provideTypeFactory() {
            return new TypeFactory<String>() {

                @Override
                public String createType(String type) {
                    return type;
                }

                @Override
                public String toString(String type) {
                    return type;
                }
            };
        }
    };
}
Example 45
Project: mini-git-server-master  File: RpcServletModule.java View source code
protected void rpc(final String name, Class<? extends RemoteJsonService> clazz) {
    final Key<GerritJsonServlet> srv = Key.get(GerritJsonServlet.class, UniqueAnnotations.create());
    final GerritJsonServletProvider provider = new GerritJsonServletProvider(clazz);
    bind(clazz);
    serve(prefix + name).with(srv);
    bind(srv).toProvider(provider).in(Scopes.SINGLETON);
}
Example 46
Project: ModernHub-master  File: ScopeBase.java View source code
public T get() {
    Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key);
    @SuppressWarnings("unchecked") T current = (T) scopedObjects.get(key);
    if (current == null && !scopedObjects.containsKey(key)) {
        current = unscoped.get();
        scopedObjects.put(key, current);
    }
    return current;
}
Example 47
Project: monticore-master  File: ScopeImpl.java View source code
@Override
@SuppressWarnings("unchecked")
public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
    return () -> {
        checkState(context != null, "Tried to retrieve " + key + " out of context");
        T object = (T) objects.get(context, key);
        if (object == null) {
            object = unscoped.get();
            objects.put(context, key, object);
        }
        return object;
    };
}
Example 48
Project: MoodCat.me-Core-master  File: AuthorizationFilter.java View source code
@Override
public void filter(final ContainerRequestContext containerRequestContext) throws IOException {
    final MultivaluedMap<String, String> parameters = containerRequestContext.getUriInfo().getQueryParameters();
    final String token = parameters.getFirst(TOKEN_PARAMETER);
    if (!Strings.isNullOrEmpty(token)) {
        try {
            final User user = userBackend.loginUsingSoundCloud(token);
            containerRequestContext.setProperty(Key.get(User.class, Names.named(CURRENT_USER_NAME)).toString(), user);
        } catch (final NotAuthorizedException e) {
            final Response response = notAuthorizedExceptionMapper.toResponse(e);
            containerRequestContext.abortWith(response);
        }
    }
}
Example 49
Project: Moogle-Muice-master  File: TestScope.java View source code
public <T> Provider<T> scope(final Key<T> key, final Provider<T> provider) {
    return new Provider<T>() {

        @SuppressWarnings({ "unchecked" })
        public T get() {
            T t = (T) inScopeObjectsMap.get(key);
            if (t == null) {
                t = provider.get();
                inScopeObjectsMap.put(key, t);
            }
            return t;
        }
    };
}
Example 50
Project: mycila-master  File: BindFieldTest.java View source code
@Test
public void test_bind() {
    MycilaTesting.from(getClass()).createNotifier(this).prepare();
    assertEquals(injector.getInstance(Key.get(String.class)), "helloa");
    assertEquals(injector.getInstance(Key.get(String.class, Named.class)), "hellob");
    b = "changedb";
    a = "changeda";
    assertEquals(injector.getInstance(Key.get(String.class)), "changeda");
    assertEquals(injector.getInstance(Key.get(String.class, Named.class)), "hellob");
    assertEquals(injector.getInstance(ServiceImpl2.class).go(), "impl1");
    assertEquals(injector.getInstance(Key.get(Service.class, Named.class)).go(), "impl2");
}
Example 51
Project: neo4j-mobile-android-master  File: DBInspectorApplication.java View source code
@Override
public void onCreate() {
    super.onCreate();
    Module defaultModule = RoboGuice.newDefaultRoboModule(this);
    Module dbInspectorModule = new DBInspectorModule();
    Module combinedModule = Modules.combine(defaultModule, dbInspectorModule);
    Injector injector = RoboGuice.setBaseApplicationInjector(this, RoboGuice.DEFAULT_STAGE, combinedModule);
    Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();
    for (Key<?> key : bindings.keySet()) {
        Binding<?> value = bindings.get(key);
        Ln.d("binding key '" + key + "', value '" + value + "'");
    }
    Ln.i("Application initialized.");
}
Example 52
Project: nuun-framework-master  File: KernelSuite7Test.java View source code
@Test
public void dependee_plugins_that_misses_should_be_source_of_error() {
    underTest = //
    Kernel.createKernel().withoutSpiPluginsLoader().withPlugins(//
    new DummyPlugin7_A(), //
    new DummyPlugin7_B()).build();
    //
    underTest.init();
    underTest.start();
    String resa = underTest.getMainInjector().getInstance(Key.get(String.class, Names.named("dep7a")));
    assertThat(resa).isNotNull();
    assertThat(resa).isEqualTo("dep7aOVER");
}
Example 53
Project: nuxeo-core-master  File: CoreScope.java View source code
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
    return new Provider<T>() {

        @Override
        public T get() {
            Map<Key<?>, Object> scopedMap = getScopedObjectMap(key);
            T current = (T) scopedMap.get(key);
            if (current == null && !scopedMap.containsKey(key)) {
                current = unscoped.get();
                scopedMap.put(key, current);
            }
            return current;
        }
    };
}
Example 54
Project: org.ops4j.pax.exam1-master  File: UpdateWithQuickbuildUsage.java View source code
public static void main(String... args) {
    try {
        Injector injector = Guice.createInjector(new DefaultQuickbuildModule());
        SnapshotBuilder snapshotBuilder = injector.getInstance(Key.get(SnapshotBuilder.class));
        Quickbuild build = injector.getInstance(Key.get(Quickbuild.class));
        Snapshot snapshot = snapshotBuilder.load(new FileInputStream(CreateSnapshotUsage.SNAPSHOT));
        // get updated thing:
        InputStream result = build.update(snapshot, new File(CreateSnapshotUsage.FOLDER_OF_CHANGE));
        assertNotNull(result);
        // Done. Now we just save the build to make it visible on disk..
        Store<InputStream> store = injector.getInstance(injector.findBindingsByType(new TypeLiteral<Store<InputStream>>() {
        }).get(0).getKey());
        Handle handle = store.store(result);
        System.out.println("Result has been written to " + store.getLocation(handle).toASCIIString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 55
Project: oxalis-master  File: LoggingHandler.java View source code
@Inject
@SuppressWarnings("unchecked")
public void load(Injector injector, Settings<LoggingConf> settings) {
    logger.debug("Logger config: {}", settings.getString(LoggingConf.CONFIG));
    if (settings.getString(LoggingConf.CONFIG) == null)
        return;
    logger.info("Logging service: {}", settings.getString(LoggingConf.SERVICE));
    injector.getInstance(Key.get(Configurator.class, settings.getNamed(LoggingConf.SERVICE))).execute();
}
Example 56
Project: palava-concurrent-master  File: BackgroundSchedulerModule.java View source code
@Override
@SuppressWarnings("deprecation")
public void configure(Binder binder) {
    binder.install(new SchedulerModule(BackgroundScheduler.class, BackgroundScheduler.NAME));
    final Key<ScheduledExecutorService> key = Key.get(ScheduledExecutorService.class, BackgroundScheduler.class);
    binder.bind(Executor.class).annotatedWith(Background.class).to(key).in(Singleton.class);
    binder.bind(ExecutorService.class).annotatedWith(Background.class).to(key).in(Singleton.class);
    binder.bind(ScheduledExecutorService.class).annotatedWith(Background.class).to(key).in(Singleton.class);
}
Example 57
Project: palava-ipc-master  File: DefaultConversationService.java View source code
@Override
public Conversation get(String name) {
    final String key = Key.get(Conversation.class, Names.named(name)).toString();
    final IpcSession session = currentSession.get();
    final Conversation present = (Conversation) session.get(key);
    if (present == null) {
        final Conversation conversation = new DefaultConversation(session, key);
        LOG.trace("Starting new conversation {}", conversation);
        session.put(key, conversation);
        return conversation;
    } else {
        LOG.trace("Found old conversation {} in session", present);
        return present;
    }
}
Example 58
Project: palava-jpa-master  File: AnnotatedJpaModule.java View source code
@Override
public void configure(Binder binder) {
    binder.bind(PersistenceService.class).annotatedWith(annotation).to(DefaultPersistenceService.class).in(Singleton.class);
    binder.bind(EntityManagerFactory.class).annotatedWith(annotation).to(Key.get(PersistenceService.class, annotation)).in(Singleton.class);
    binder.bind(EntityManager.class).annotatedWith(annotation).toProvider(Key.get(PersistenceService.class, annotation)).in(UnitOfWork.class);
}
Example 59
Project: PretendYoureXyzzy-master  File: JavascriptConfigServlet.java View source code
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    // We have to do this every time since it comes from the properties file and that can change...
    final StringBuilder builder = new StringBuilder(256);
    // Ideally we'd figure out how to make this Servlet itself injectable but I don't have time.
    final Injector injector = (Injector) getServletContext().getAttribute(StartupUtils.INJECTOR);
    final String cookieDomain = injector.getInstance(Key.get(String.class, CookieDomain.class));
    builder.append(String.format("cah.COOKIE_DOMAIN = '%s';\n", cookieDomain));
    resp.setContentType("text/javascript");
    final PrintWriter out = resp.getWriter();
    out.println(configString + builder.toString());
    out.flush();
    out.close();
}
Example 60
Project: riemann-client-master  File: InstrumentedClientModule.java View source code
@Override
protected void bindOutstandingMessagesQueue(Key<BlockingQueue<ReturnableMessage>> key) {
    bind(key).toProvider(new Provider<BlockingQueue<ReturnableMessage>>() {

        @Inject
        MetricsRegistry registry = null;

        @Override
        public BlockingQueue<ReturnableMessage> get() {
            final BlockingQueue<ReturnableMessage> queue = Queues.newLinkedBlockingQueue();
            registry.newGauge(new MetricName(getClass(), "unacked"), new Gauge<Integer>() {

                @Override
                public Integer value() {
                    return queue.size();
                }
            });
            return queue;
        }
    });
}
Example 61
Project: roboguice-master  File: TestScope.java View source code
public <T> Provider<T> scope(final Key<T> key, final Provider<T> provider) {
    return new Provider<T>() {

        @SuppressWarnings({ "unchecked" })
        public T get() {
            T t = (T) inScopeObjectsMap.get(key);
            if (t == null) {
                t = provider.get();
                inScopeObjectsMap.put(key, t);
            }
            return t;
        }
    };
}
Example 62
Project: sandboxes-master  File: ModularJFx.java View source code
private void putSceneOn(Stage stage) {
    FlowPane pane = new FlowPane();
    ViewContribution filterViewContribution = new ViewContribution() {

        @Override
        public void addTo(Pane pane) {
            TilePane tilePane = new TilePane();
            TextField seriesTextArea = new TextField();
            seriesTextArea.promptTextProperty().setValue("series");
            TextField seasonTextArea = new TextField();
            seasonTextArea.promptTextProperty().setValue("season");
            tilePane.getChildren().addAll(seriesTextArea, seasonTextArea);
            pane.getChildren().add(tilePane);
        //To change body of implemented methods use File | Settings | File Templates.
        }
    };
    for (ViewContribution viewContribution : injector.getInstance(Key.get(new TypeLiteral<AllContributors<ViewContribution>>() {
    }))) {
        viewContribution.addTo(pane);
    }
    filterViewContribution.addTo(pane);
    stage.setScene(new Scene(pane));
}
Example 63
Project: sangria-master  File: LazyScopes.java View source code
public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
    final Provider<T> singleton = Scopes.SINGLETON.scope(key, creator);
    return new Provider<T>() {

        public T get() {
            return singleton.get();
        }

        @Override
        public String toString() {
            return String.format("%s[%s]", creator, LAZY_SINGLETON);
        }
    };
}
Example 64
Project: seed-master  File: CryptoPluginTest.java View source code
@Test
public void testNativeUnitModule(@SuppressWarnings("unused") @Mocked final CryptoModule module) {
    final Map<Key<EncryptionService>, EncryptionService> encryptionServices = new HashMap<>();
    final Map<String, KeyStore> keyStores = new HashMap<>();
    final CryptoPlugin underTest = new CryptoPlugin();
    Deencapsulation.setField(underTest, "encryptionServices", encryptionServices);
    Deencapsulation.setField(underTest, "keyStores", keyStores);
    underTest.nativeUnitModule();
    new Verifications() {

        {
            new CryptoModule(encryptionServices, keyStores);
            times = 1;
        }
    };
}
Example 65
Project: Shindig-master  File: SocialApiGuiceModuleTest.java View source code
/**
   * Test default auth handler injection
   */
public void testAuthHandler() {
    injector.getInstance(AuthenticationHandlerProvider.class).get();
    AuthenticationHandlerProvider provider = injector.getInstance(AuthenticationHandlerProvider.class);
    assertEquals(3, provider.get().size());
    List<AuthenticationHandler> handlers = injector.getInstance(Key.get(new TypeLiteral<List<AuthenticationHandler>>() {
    }));
    assertEquals(3, handlers.size());
}
Example 66
Project: shiro-master  File: PathMatchingFilterProviderTest.java View source code
@Test
public void testPostProcess() {
    PathMatchingFilter filter = createMock(PathMatchingFilter.class);
    expect(filter.processPathConfig("/1", "first")).andReturn(filter);
    expect(filter.processPathConfig("/2", "second")).andReturn(filter);
    replay(filter);
    Map<String, String> pathConfigMap = new HashMap<String, String>();
    pathConfigMap.put("/1", "first");
    pathConfigMap.put("/2", "second");
    PathMatchingFilterProvider underTest = new PathMatchingFilterProvider(Key.get(PathMatchingFilter.class), pathConfigMap);
    underTest.postProcess(filter);
    verify(filter);
}
Example 67
Project: sisu.plexus-master  File: DefaultPlexusBeanLocator.java View source code
// ----------------------------------------------------------------------
// Public methods
// ----------------------------------------------------------------------
@SuppressWarnings("unchecked")
public <T> Iterable<PlexusBean<T>> locate(final TypeLiteral<T> role, final String... hints) {
    final Key<T> key = hints.length == 1 ? Key.get(role, Names.named(hints[0])) : Key.get(role, Named.class);
    Iterable<BeanEntry<Named, T>> beans = (Iterable<BeanEntry<Named, T>>) beanLocator.<Named, T>locate(key);
    if (PlexusConstants.REALM_VISIBILITY.equalsIgnoreCase(visibility)) {
        beans = new RealmFilteredBeans<T>(realmManager, beans);
    }
    return hints.length <= 1 ? new DefaultPlexusBeans<T>(beans) : new HintedPlexusBeans<T>(beans, role, hints);
}
Example 68
Project: solrmeter-master  File: StressTestScopeImpl.java View source code
public <T> Provider<T> scope(Key<T> key, final Provider<T> creator) {
    final String name = key.toString();
    return new Provider<T>() {

        public T get() {
            synchronized (providers) {
                verifyChangedStressTestId();
                @SuppressWarnings("unchecked") T provider = (T) providers.get(name);
                if (provider == null) {
                    provider = creator.get();
                    providers.put(name, provider);
                }
                return provider;
            }
        }
    };
}
Example 69
Project: tools_gerrit-master  File: RpcServletModule.java View source code
protected void rpc(final String name, Class<? extends RemoteJsonService> clazz) {
    final Key<GerritJsonServlet> srv = Key.get(GerritJsonServlet.class, UniqueAnnotations.create());
    final GerritJsonServletProvider provider = new GerritJsonServletProvider(clazz);
    bind(clazz);
    serve(prefix + name).with(srv);
    bind(srv).toProvider(provider).in(Scopes.SINGLETON);
}
Example 70
Project: user-master  File: MapModule.java View source code
@Override
protected void configure() {
    bind(MapManagerFactory.class).to(MapManagerFactoryImpl.class);
    bind(MapSerialization.class).to(MapSerializationImpl.class);
    Multibinder<Migration> migrationBinding = Multibinder.newSetBinder(binder(), Migration.class);
    migrationBinding.addBinding().to(Key.get(MapSerialization.class));
}
Example 71
Project: usergrid-master  File: MapModule.java View source code
@Override
protected void configure() {
    bind(MapManagerFactory.class).to(MapManagerFactoryImpl.class);
    bind(MapSerialization.class).to(MapSerializationImpl.class);
    Multibinder<Migration> migrationBinding = Multibinder.newSetBinder(binder(), Migration.class);
    migrationBinding.addBinding().to(Key.get(MapSerialization.class));
}
Example 72
Project: velocity-guice-master  File: InjectedTemplateGroup.java View source code
@Override
public Template find(String name) {
    // TODO: not terribly happy with looking up things in the injector at runtime
    Binding<Template> binding = injector.getExistingBinding(Key.get(Template.class, Names.named(prefix + "." + name)));
    if (binding == null) {
        return null;
    }
    return binding.getProvider().get();
}
Example 73
Project: webpie-master  File: PluginSetup.java View source code
/**
	 * This is where we wire in all plugin points EXCEPT the Startup one
	 * we can't inject them 
	 */
@SuppressWarnings("rawtypes")
public void wireInPluginPoints(Injector appInjector, Consumer<Injector> startupFunction) {
    Key<Set<EntityLookup>> key = Key.get(new TypeLiteral<Set<EntityLookup>>() {
    });
    Set<EntityLookup> lookupHooks = appInjector.getInstance(key);
    translator.install(lookupHooks);
    Key<Set<ObjectStringConverter>> key3 = Key.get(new TypeLiteral<Set<ObjectStringConverter>>() {
    });
    Set<ObjectStringConverter> converters = appInjector.getInstance(key3);
    translation.install(converters);
    Key<Set<BodyContentBinder>> key2 = Key.get(new TypeLiteral<Set<BodyContentBinder>>() {
    });
    Set<BodyContentBinder> bodyBinders = appInjector.getInstance(key2);
    loader.install(bodyBinders);
    //wire in startup and start the startables.  This is a function since Dev and Production differ
    //in that Development we have to make sure we don't run startup code twice as it is likely to
    //blow up....or should we make this configurable?
    startupFunction.accept(appInjector);
}
Example 74
Project: x-guice-master  File: XScopes.java View source code
@Override
public <T> Provider<T> scope(Key<T> key, final Provider<T> unscoped) {
    return new Provider<T>() {

        private final ThreadLocal<T> threadLocal = new ThreadLocal<T>();

        @Override
        public T get() {
            T t = threadLocal.get();
            if (t == null) {
                t = unscoped.get();
                threadLocal.set(t);
            }
            return t;
        }
    };
}
Example 75
Project: xades4j-master  File: QualifyingPropertyVerifiersMapperImpl.java View source code
@Override
public <TData extends PropertyDataObject> QualifyingPropertyVerifier<TData> getVerifier(TData p) throws QualifyingPropertyVerifierNotAvailableException {
    try {
        ParameterizedType pt = Types.newParameterizedType(QualifyingPropertyVerifier.class, p.getClass());
        return (QualifyingPropertyVerifier) injector.getInstance(Key.get(TypeLiteral.get(pt)));
    } catch (ConfigurationException ex) {
    } catch (ProvisionException ex) {
    }
    throw new QualifyingPropertyVerifierNotAvailableException(p);
}
Example 76
Project: Xpect-master  File: AbstractDelegatingModule.java View source code
@SuppressWarnings("unchecked")
protected <T> Class<? extends T> getOriginalType(Key<T> type) {
    try {
        Binding<T> binding = original.getBinding(type);
        if (binding instanceof LinkedKeyBinding<?>)
            return (Class<? extends T>) ((LinkedKeyBinding<T>) binding).getLinkedKey().getTypeLiteral().getRawType();
        if (binding instanceof ConstructorBinding<?>)
            return (Class<T>) ((ConstructorBinding<T>) binding).getConstructor().getDeclaringType().getRawType();
    } catch (ConfigurationException e) {
    }
    return null;
}
Example 77
Project: yajul-master  File: MicroContainer.java View source code
public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append(this.getClass().getSimpleName()).append("{");
    Map<Key<?>, Binding<?>> bindings = injector.getBindings();
    for (Map.Entry<Key<?>, Binding<?>> keyBindingEntry : bindings.entrySet()) {
        sb.append("\n ").append(keyBindingEntry.getKey().toString()).append(" -> ").append(keyBindingEntry.getValue().toString());
    }
    sb.append("\n}");
    return sb.toString();
}
Example 78
Project: dwr-master  File: AbstractSimpleContextScope.java View source code
public <T> boolean remove(C registry, Key<T> key, String keyString, InstanceProvider<T> creator) {
    synchronized (registry) {
        InstanceProvider<T> t = get(registry, key, keyString);
        if (t == creator) {
            // Assumes put(..., null) is equivalent to remove(...)
            put(registry, keyString, null);
            return true;
        } else {
            return false;
        }
    }
}
Example 79
Project: android-rackspacecloud-master  File: GoogleAppEngineConfigurationModuleTest.java View source code
public void testConfigureBindsClient() {
    final Properties properties = new PropertiesBuilder() {

        public PropertiesBuilder withEndpoint(URI endpoint) {
            return null;
        }

        public PropertiesBuilder withCredentials(String account, String key) {
            return null;
        }
    }.build();
    Injector i = Guice.createInjector(new GoogleAppEngineConfigurationModule() {

        @Override
        protected void configure() {
            Jsr330.bindProperties(binder(), properties);
            bind(Logger.LoggerFactory.class).toInstance(new LoggerFactory() {

                public Logger getLogger(String category) {
                    return Logger.NULL;
                }
            });
            bind(UriBuilder.class).to(UriBuilderImpl.class);
            super.configure();
        }
    });
    HttpCommandExecutorService client = i.getInstance(HttpCommandExecutorService.class);
    i.getInstance(Key.get(ExecutorService.class, Jsr330.named(Constants.PROPERTY_USER_THREADS)));
    // TODO check single threaded;
    assert client instanceof GaeHttpCommandExecutorService;
}
Example 80
Project: atmosphere-extensions-master  File: GuiceAtmosphereFramework.java View source code
@Override
protected void configureDetectedFramework(ReflectorServletProcessor rsp, boolean isJersey) {
    if (isJersey) {
        logger.info("Configuring Guice for Atmosphere Jersey");
        Injector injector = (Injector) getAtmosphereConfig().getServletContext().getAttribute(Injector.class.getName());
        GuiceContainer guiceServlet = injector.getInstance(GuiceContainer.class);
        rsp.setServlet(guiceServlet);
        try {
            Map<String, String> props = injector.getInstance(Key.get(new TypeLiteral<Map<String, String>>() {
            }, Names.named(PROPERTIES)));
            if (props != null) {
                for (String p : props.keySet()) {
                    addInitParameter(p, props.get(p));
                }
            }
        } catch (Exception ex) {
            logger.debug("failed to add Jersey init parameters to Atmosphere servlet", ex.getCause());
        }
    }
}
Example 81
Project: aurora-master  File: PubsubTestUtil.java View source code
/**
   * Starts the pubsub system and gets a handle to the event sink where pubsub events may be sent.
   *
   * @param injector Injector where the pubsub system was installed.
   * @return The pubsub event sink.
   * @throws Exception If the pubsub system failed to start.
   */
public static EventSink startPubsub(Injector injector) throws Exception {
    // TODO(wfarner): Make it easier to write a unit test wired for pubsub events.
    // In this case, a trade-off was made to avoid installing several distant modules and providing
    // required bindings that seem unrelated from this code.
    Set<Service> services = injector.getInstance(Key.get(new TypeLiteral<Set<Service>>() {
    }, AppStartup.class));
    for (Service service : services) {
        service.startAsync().awaitRunning();
    }
    return injector.getInstance(EventSink.class);
}
Example 82
Project: bees-cli-master  File: CommandScopeImpl.java View source code
public T get() {
    Map<Key, Object> table = SCOPED_OBJECTS.get();
    synchronized (table) {
        Object obj = table.get(key);
        if (obj == NULL) {
            return null;
        }
        T t = (T) obj;
        if (t == null) {
            t = creator.get();
            if (!(t instanceof CircularDependencyProxy)) {
                // not sure exactly what this marker interface means but I'm just following Scopes.SINGLETON
                table.put(key, (t != null) ? t : NULL);
            }
        }
        return t;
    }
}
Example 83
Project: candlepin-master  File: CandlepinRequestScope.java View source code
public T get() {
    Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key);
    @SuppressWarnings("unchecked") T current = (T) scopedObjects.get(key);
    if (current == null && !scopedObjects.containsKey(key)) {
        current = unscoped.get();
        scopedObjects.put(key, current);
    }
    return current;
}
Example 84
Project: cloud-master  File: Lifecycle.java View source code
synchronized List<LifecycleListener> getListeners() {
    if (listeners == null) {
        List<LifecycleListener> listeners = Lists.newArrayList();
        for (Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet()) {
            // final Binding<?> binding = entry.getValue();
            // Object instance = entry.getValue().getProvider().get();
            BindingScopingVisitor<Boolean> visitor = new IsSingletonBindingScopingVisitor();
            Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();
            for (Binding<?> binding : bindings.values()) {
                Key<?> key = binding.getKey();
                // log.debug("Checking binding " + key);
                Boolean foundSingleton = binding.acceptScopingVisitor(visitor);
                if (foundSingleton) {
                    Object instance = injector.getInstance(key);
                    if (instance instanceof LifecycleListener) {
                        if (listeners.contains(instance)) {
                            continue;
                        }
                        log.debug("Found binding " + key);
                        log.debug("Found lifecycle listener: {}", instance.getClass());
                        listeners.add((LifecycleListener) instance);
                    }
                }
            }
        // binding.acceptScopingVisitor(new
        // DefaultBindingScopingVisitor<Void>() {
        // @Override
        // public Void visitEagerSingleton() {
        // Object instance = binding.getProvider().get();
        // foundSingleton(instance);
        // return null;
        // }
        //
        // @Override
        // public Void visitScopeAnnotation(Class<? extends Annotation>
        // scopeAnnotation) {
        // return super.visitScopeAnnotation(scopeAnnotation);
        // }
        //
        // @Override
        // protected Void visitOther() {
        // return super.visitOther();
        // }
        //
        // @Override
        // public Void visitScope(Scope scope) {
        // return super.visitScope(scope);
        // }
        //
        // @Override
        // public Void visitNoScoping() {
        // return super.visitNoScoping();
        // }
        // });
        }
        this.listeners = listeners;
    }
    return listeners;
}
Example 85
Project: com.lowereast.guiceymongo-master  File: GridFSProviderModule.java View source code
private void cacheGuiceyBucket() throws Exception {
    String bucketKey = ((GuiceyMongoBucket) ((Key<?>) key).getAnnotation()).value();
    String clonedConfiguration = getInstance(_injector, Key.get(String.class, AnnotationUtil.clonedConfiguration(_configuration)));
    String bucket;
    if (clonedConfiguration == null)
        bucket = _injector.getInstance(Key.get(String.class, AnnotationUtil.configuredBucket(_configuration, bucketKey)));
    else
        bucket = _injector.getInstance(Key.get(String.class, AnnotationUtil.configuredBucket(clonedConfiguration, bucketKey)));
    _cachedGridFS = new GridFS(_databaseProvider.get(), bucket);
}
Example 86
Project: contextfw-master  File: PageScope.java View source code
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
    return new Provider<T>() {

        public T get() {
            WebApplicationPage page = currentPage.get();
            if (page != null) {
                T bean = (T) page.getBean(key);
                if (bean != null) {
                    return bean;
                } else {
                    return page.setBean(key, unscoped.get());
                }
            } else {
                throw new OutOfScopeException("PageScope does not exist!");
            }
        }
    };
}
Example 87
Project: dropwizard-guice-master  File: JerseyUtil.java View source code
/**
   * Registers any Guice-bound providers or root resources.
   */
public static void registerGuiceBound(Injector injector, final JerseyEnvironment environment) {
    while (injector != null) {
        for (Key<?> key : injector.getBindings().keySet()) {
            Type type = key.getTypeLiteral().getType();
            if (type instanceof Class) {
                Class<?> c = (Class) type;
                if (isProviderClass(c)) {
                    logger.info("Registering {} as a provider class", c.getName());
                    environment.register(c);
                } else if (isRootResourceClass(c)) {
                    // Including abstract classes and interfaces, even if there is a valid Guice binding.
                    if (Resource.isAcceptable(c)) {
                        logger.info("Registering {} as a root resource class", c.getName());
                        environment.register(c);
                    } else {
                        logger.warn("Class {} was not registered as a resource. Bind a concrete implementation instead.", c.getName());
                    }
                }
            }
        }
        injector = injector.getParent();
    }
}
Example 88
Project: druid-api-master  File: LifecycleScope.java View source code
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
    return new Provider<T>() {

        private volatile T value = null;

        @Override
        public synchronized T get() {
            if (value == null) {
                final T retVal = unscoped.get();
                synchronized (instances) {
                    if (lifecycle == null) {
                        instances.add(retVal);
                    } else {
                        try {
                            lifecycle.addMaybeStartManagedInstance(retVal, stage);
                        } catch (Exception e) {
                            log.warn(e, "Caught exception when trying to create a[%s]", key);
                            return null;
                        }
                    }
                }
                value = retVal;
            }
            return value;
        }
    };
}
Example 89
Project: EMB-master  File: InjectedPluginSource.java View source code
public <T> T newPlugin(Class<T> iface, PluginType type) throws PluginSourceNotMatchException {
    String name = type.getName();
    try {
        @SuppressWarnings("unchecked") PluginFactory<T> factory = (PluginFactory<T>) injector.getInstance(Key.get(PluginFactory.class, pluginFactoryName(iface, name)));
        return factory.newPlugin(injector);
    } catch (com.google.inject.ConfigurationException ex) {
        throw new PluginSourceNotMatchException();
    }
}
Example 90
Project: embulk-master  File: InjectedPluginSource.java View source code
public <T> T newPlugin(Class<T> iface, PluginType type) throws PluginSourceNotMatchException {
    String name = type.getName();
    try {
        @SuppressWarnings("unchecked") PluginFactory<T> factory = (PluginFactory<T>) injector.getInstance(Key.get(PluginFactory.class, pluginFactoryName(iface, name)));
        return factory.newPlugin(injector);
    } catch (com.google.inject.ConfigurationException ex) {
        throw new PluginSourceNotMatchException();
    }
}
Example 91
Project: eureka-master  File: Jersey2EurekaModuleTest.java View source code
@SuppressWarnings("deprecation")
@Test
public void testDI() {
    InstanceInfo instanceInfo = injector.getInstance(InstanceInfo.class);
    Assert.assertEquals(ApplicationInfoManager.getInstance().getInfo(), instanceInfo);
    EurekaClient eurekaClient = injector.getInstance(EurekaClient.class);
    DiscoveryClient discoveryClient = injector.getInstance(DiscoveryClient.class);
    Assert.assertEquals(DiscoveryManager.getInstance().getEurekaClient(), eurekaClient);
    Assert.assertEquals(DiscoveryManager.getInstance().getDiscoveryClient(), discoveryClient);
    Assert.assertEquals(eurekaClient, discoveryClient);
    EurekaClientConfig eurekaClientConfig = injector.getInstance(EurekaClientConfig.class);
    Assert.assertEquals(DiscoveryManager.getInstance().getEurekaClientConfig(), eurekaClientConfig);
    EurekaInstanceConfig eurekaInstanceConfig = injector.getInstance(EurekaInstanceConfig.class);
    Assert.assertEquals(DiscoveryManager.getInstance().getEurekaInstanceConfig(), eurekaInstanceConfig);
    Binding<TransportClientFactories> binding = injector.getExistingBinding(Key.get(TransportClientFactories.class));
    // has a binding for jersey2
    Assert.assertNotNull(binding);
    TransportClientFactories transportClientFactories = injector.getInstance(TransportClientFactories.class);
    Assert.assertTrue(transportClientFactories instanceof Jersey2TransportClientFactories);
}
Example 92
Project: event-collector-master  File: EventTapModule.java View source code
@Override
public void configure(Binder binder) {
    discoveryBinder(binder).bindSelector("eventTap");
    bindConfig(binder).to(EventTapConfig.class);
    jsonCodecBinder(binder).bindListJsonCodec(Event.class);
    bindConfig(binder).to(BatchProcessorConfig.class);
    binder.bind(BatchProcessorFactory.class).to(BatchProcessorFactoryImpl.class);
    binder.bind(BatchProcessorFactoryImpl.class).in(SINGLETON);
    binder.bind(EventTapFlowFactory.class).to(HttpEventTapFlowFactory.class);
    binder.bind(HttpEventTapFlowFactory.class).in(SINGLETON);
    binder.bind(EventTapWriter.class).in(SINGLETON);
    binder.bind(new TypeLiteral<QueueFactory<Event>>() {
    }).in(SINGLETON);
    String metricNamePrefix = new ObjectNameBuilder(this.getClass().getPackage().getName()).withProperty("type", "EventCollector.EventTap.Queue").build();
    httpClientBinder(binder).bindHttpClient("EventTap", EventTap.class);
    newExporter(binder).export(EventTapWriter.class).withGeneratedName();
    newSetBinder(binder, EventWriter.class).addBinding().to(Key.get(EventTapWriter.class)).in(SINGLETON);
}
Example 93
Project: extensibility-api-master  File: ExtensionList.java View source code
/**
     * Returns all the extension implementations in the specified injector.
     */
public List<T> list(Injector injector) {
    List<T> r = new ArrayList<T>();
    for (Injector i = injector; i != null; i = i.getParent()) {
        for (Entry<Key<?>, Binding<?>> e : i.getBindings().entrySet()) {
            if (e.getKey().getTypeLiteral().equals(type))
                r.add((T) e.getValue().getProvider().get());
        }
    }
    return r;
}
Example 94
Project: fx-guice-master  File: FxmlExampleAppController.java View source code
/**
     * This method will automatically be called by the FXML loader.
     * See Oracle's JavaFX/FXML documentation for further details about
     * that mechanism. (Note: it was necessary to implement {@ link Initializable})
     * int the past, but that mechanism has been deprecated.
     */
public void initialize() {
    // Use the guice injector to fetch our color code definitions.
    final String red = injector.getInstance(Key.get(String.class, Names.named("red-button-color-string")));
    final String green = injector.getInstance(Key.get(String.class, Names.named("green-button-color-string")));
    // We use the Guice-injected value for our desired color to update
    // the style of our FXML-injected button.
    redButton.setStyle(String.format("-fx-base: %s;", red));
    greenButton.setStyle(String.format("-fx-base: %s;", green));
}
Example 95
Project: gatein-shindig-master  File: AuthenticationProviderHandlerTest.java View source code
/**
   * Test that existing custom handlers won't be broken with the switch
   * to injecting List<ProviderHandler>.
   */
@Test
public void testCustomHandler() {
    Injector injector = Guice.createInjector(new SocialApiGuiceModule(), new CustomAuthHandlerProviderModule(), new PropertiesModule());
    AuthenticationHandlerProvider provider = injector.getInstance(AuthenticationHandlerProvider.class);
    assertEquals(0, provider.get().size());
    List<AuthenticationHandler> handlers = injector.getInstance(Key.get(new TypeLiteral<List<AuthenticationHandler>>() {
    }));
    assertEquals(0, handlers.size());
}
Example 96
Project: graceland-core-master  File: DropwizardModuleTest.java View source code
@Test
public void provides_dropwizard_components() {
    ObjectMapper objectMapper = mock(ObjectMapper.class);
    MetricRegistry metricRegistry = mock(MetricRegistry.class);
    when(environment.getObjectMapper()).thenReturn(objectMapper);
    when(environment.metrics()).thenReturn(metricRegistry);
    dropwizardModule.setup(configuration, environment);
    Injector injector = Guice.createInjector(dropwizardModule);
    PlatformConfiguration actualConfiguration = injector.getInstance(Key.get(PlatformConfiguration.class, Graceland.class));
    ObjectMapper actualObjectMapper = injector.getInstance(Key.get(ObjectMapper.class, Graceland.class));
    MetricRegistry actualMetricRegistry = injector.getInstance(Key.get(MetricRegistry.class, Graceland.class));
    Environment actualEnvironment = injector.getInstance(Key.get(Environment.class, Graceland.class));
    assertThat(actualConfiguration, is(configuration));
    assertThat(actualObjectMapper, is(objectMapper));
    assertThat(actualMetricRegistry, is(metricRegistry));
    assertThat(actualEnvironment, is(environment));
}
Example 97
Project: guice-ext-annotations-master  File: DynamicClassProvider.java View source code
@Override
public Object call(final InternalContext context) {
    // check if (possibly) child context contains anchor bean definition
    final boolean hasAnchor = injector.getExistingBinding(Key.get(AnchorBean.class)) != null;
    final Class<?> abstractType = context.getDependency().getKey().getTypeLiteral().getRawType();
    final Class<?> generatedType = DynamicClassGenerator.generate(abstractType, getScopeAnnotation(), hasAnchor ? AnchorBean.class : null);
    return injector.getInstance(generatedType);
}
Example 98
Project: guiceberry-master  File: TestScope.java View source code
public T get() {
    TestDescription actualTestCase = universe.currentTestDescriptionThreadLocal.get();
    if (actualTestCase == null) {
        throw new IllegalStateException("GuiceBerry can't find out what is the currently-running test. " + "There are a few reasons why this can happen, but a likely one " + "is that a GuiceBerry Injector is being asked to instantiate a " + "class in a thread not created by your test case.");
    }
    Map<Key<?>, Object> keyToInstanceProvider = testMap.get(actualTestCase);
    if (keyToInstanceProvider == null) {
        testMap.putIfAbsent(actualTestCase, new ConcurrentHashMap<Key<?>, Object>());
        keyToInstanceProvider = testMap.get(actualTestCase);
    }
    Object o = keyToInstanceProvider.get(key);
    if (o != null) {
        return (T) o;
    }
    // double checked locking -- handle with extreme care!
    synchronized (keyToInstanceProvider) {
        o = keyToInstanceProvider.get(key);
        if (o == null) {
            o = creator.get();
            keyToInstanceProvider.put(key, o);
        }
        return (T) o;
    }
}
Example 99
Project: guiceyfruit-master  File: ContextWithJsr250Test.java View source code
public void testContextIsReused() throws Exception {
    InputStream in = getClass().getResourceAsStream("jndi-example.properties");
    assertNotNull("Cannot find jndi-example.properties on the classpath!", in);
    Properties properties = new Properties();
    properties.load(in);
    InitialContext context = new InitialContext(new Hashtable(properties));
    Injector injector = (Injector) context.lookup(Injector.class.getName());
    assertNotNull("Should have an injector!", injector);
    Context actual = injector.getInstance(Context.class);
    if (verbose) {
        Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings().entrySet();
        for (Entry<Key<?>, Binding<?>> entry : entries) {
            System.out.println("key: " + entry.getKey() + " -> " + entry.getValue());
        }
        System.out.println("Context: " + actual);
        System.out.println("Context type: " + actual.getClass().getName());
    }
    MatcherAssert.assertThat(actual, Is.is(JndiContext.class));
}
Example 100
Project: gwt-test-utils-master  File: ServletDefinitionReader.java View source code
public HttpServlet getServletForPath(String uri) {
    for (ServletDefinition def : servletDefinitions) {
        if (def.shouldServe(uri)) {
            // by a few servlets, so it's a waste of resources to instantiate them all.
            if (!mapUriToServlets.containsKey(def)) {
                Key<? extends HttpServlet> key = GwtReflectionUtils.getPrivateFieldValue(def, "servletKey");
                try {
                    mapUriToServlets.put(def, injector.getInstance(key));
                } catch (Throwable t) {
                    throw new GwtTestConfigurationException("cannot instantiate servlet", t);
                }
            }
            return mapUriToServlets.get(def);
        }
    }
    throw new GwtTestConfigurationException("Cannot find servlet mapped to: " + uri);
}
Example 101
Project: io-addon-master  File: ParsersInternal.java View source code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Parser getParserFor(String templateName) {
    // Finds the template loader associated to the given template name
    TemplateLoader<?> templateLoader = null;
    for (TemplateLoader<?> tl : templateLoaders) {
        if (tl.contains(templateName)) {
            templateLoader = tl;
            break;
        }
    }
    // For parsers with template
    if (templateLoader != null) {
        if (StringUtils.isBlank(templateLoader.templateParser())) {
            throw SeedException.createNew(IoErrorCode.NO_PARSER_FOUND).put(TEMPLATE, templateName);
        }
        Parser parser = injector.getInstance(Key.get(Parser.class, Names.named(templateLoader.templateParser())));
        Class<?> parserClazz = parsers.get(templateLoader.templateParser());
        if (AbstractTemplateParser.class.isAssignableFrom(parserClazz)) {
            // Loads the template and initializes the parser
            Template template;
            try {
                template = templateLoader.load(templateName);
                ((AbstractTemplateParser) parser).setTemplate(template);
            // Catch all possible fails when fail to load a template
            } catch (Exception e) {
                throw SeedException.wrap(e, IoErrorCode.ERROR_LOADING_TEMPLATE).put(TEMPLATE, templateName);
            }
        }
        return parser;
    } else {
        try {
            return injector.getInstance(Key.get(Parser.class, Names.named(templateName)));
        } catch (Exception e) {
            throw SeedException.wrap(e, IoErrorCode.NO_TEMPLATE_FOUND_EXCEPTION).put(TEMPLATE, templateName);
        }
    }
}