@Test public void test_interceptor() throws ClassNotFoundException { Injector injector = Guice.createInjector((Module) binder -> binder.bindInterceptor( Matchers.identicalTo(TestedRpcHandler.class), Matchers.any(), new RpcHandlerMethodInterceptor() )); TestedRpcHandler methodHandler = injector.getInstance(TestedRpcHandler.class); methodHandler.handleRequest(RpcEnvelope.Request.newBuilder().build(), new OrangeContext()); SameGuiceModuleAssertionOnInterceptorInvokation sameGuiceModuleAssertionOnInterceptorInvokation = injector.getInstance(SameGuiceModuleAssertionOnInterceptorInvokation.class); sameGuiceModuleAssertionOnInterceptorInvokation.test_that_intercepted_rpc_handler_still_verified(); assertThat(ReflectionUtil.findSubClassParameterType(methodHandler, 0)). isEqualTo(RpcEnvelope.Request.class); assertThat(ReflectionUtil.findSubClassParameterType(methodHandler, 1)). isEqualTo(RpcEnvelope.Response.class); }
@Override protected void configure() { bindListener(Matchers.any(), new ProvisionListener() { @Override public <T> void onProvision(ProvisionInvocation<T> provision) { final ProvisionListener.ProvisionInvocation<?> prior = ContextualProvider.provisionInvocation.get(); ContextualProvider.provisionInvocation.set(provision); try { provision.provision(); } finally { if(prior != null) { ContextualProvider.provisionInvocation.set(prior); } else { ContextualProvider.provisionInvocation.remove(); } } } }); }
@Override protected void configure() { bind(MotTestReadService.class).to(MotTestReadServiceDatabase.class); bind(VehicleReadService.class).to(VehicleReadServiceDatabase.class); bind(TradeReadService.class).to(TradeReadServiceDatabase.class); bind(MotrReadService.class).to(MotrReadServiceDatabase.class); bind(TradeReadDao.class).to(TradeReadDaoJdbc.class); bind(MotTestReadDao.class).to(MotTestReadDaoJdbc.class); bind(VehicleReadDao.class).to(VehicleReadDaoJdbc.class); bind(ConnectionManager.class).in(Singleton.class); DbConnectionInterceptor dbConnectionInterceptor = new DbConnectionInterceptor(); requestInjection(dbConnectionInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(ProvideDbConnection.class), dbConnectionInterceptor); }
private void bindMethodInterceptorForStringTemplateClassLoaderWorkaround() { bindInterceptor(Matchers.subclassesOf(JDBIHistoryManager.class), Matchers.any(), new MethodInterceptor() { @Override public Object invoke(MethodInvocation invocation) throws Throwable { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); } try { return invocation.proceed(); } finally { Thread.currentThread().setContextClassLoader(cl); } } }); }
/** * Binds an interceptor that ensures the main ClassLoader is bound as the thread context * {@link ClassLoader} during JNI callbacks from mesos. Some libraries require a thread * context ClassLoader be set and this ensures those libraries work properly. * * @param binder The binder to use to register an interceptor with. * @param wrapInterface Interface whose methods should wrapped. */ public static void bindJNIContextClassLoader(Binder binder, Class<?> wrapInterface) { final ClassLoader mainClassLoader = GuiceUtils.class.getClassLoader(); binder.bindInterceptor( Matchers.subclassesOf(wrapInterface), interfaceMatcher(wrapInterface, false), new MethodInterceptor() { @Override public Object invoke(MethodInvocation invocation) throws Throwable { Thread currentThread = Thread.currentThread(); ClassLoader prior = currentThread.getContextClassLoader(); try { currentThread.setContextClassLoader(mainClassLoader); return invocation.proceed(); } finally { currentThread.setContextClassLoader(prior); } } }); }
/** * Binds an exception trap on all interface methods of all classes bound against an interface. * Individual methods may opt out of trapping by annotating with {@link AllowUnchecked}. * Only void methods are allowed, any non-void interface methods must explicitly opt out. * * @param binder The binder to register an interceptor with. * @param wrapInterface Interface whose methods should be wrapped. * @throws IllegalArgumentException If any of the non-whitelisted interface methods are non-void. */ public static void bindExceptionTrap(Binder binder, Class<?> wrapInterface) throws IllegalArgumentException { Set<Method> disallowed = ImmutableSet.copyOf(Iterables.filter( ImmutableList.copyOf(wrapInterface.getMethods()), Predicates.and(Predicates.not(IS_WHITELISTED), Predicates.not(VOID_METHOD)))); Preconditions.checkArgument(disallowed.isEmpty(), "Non-void methods must be explicitly whitelisted with @AllowUnchecked: " + disallowed); Matcher<Method> matcher = Matchers.not(WHITELIST_MATCHER).and(interfaceMatcher(wrapInterface, false)); binder.bindInterceptor(Matchers.subclassesOf(wrapInterface), matcher, new MethodInterceptor() { @Override public Object invoke(MethodInvocation invocation) throws Throwable { try { return invocation.proceed(); } catch (RuntimeException e) { LOG.warn("Trapped uncaught exception: " + e, e); return null; } } }); }
private void replayAndInitialize() { expect(statsProvider.makeCounter(SHIRO_AUTHORIZATION_FAILURES)) .andReturn(new AtomicLong()); expect(statsProvider.makeCounter(SHIRO_BAD_REQUESTS)) .andReturn(new AtomicLong()); control.replay(); decoratedThrift = Guice .createInjector(new AbstractModule() { @Override protected void configure() { bind(Subject.class).toInstance(subject); MockDecoratedThrift.bindForwardedMock(binder(), thrift); bindInterceptor( Matchers.subclassesOf(AnnotatedAuroraAdmin.class), HttpSecurityModule.AURORA_SCHEDULER_MANAGER_SERVICE, interceptor); bind(StatsProvider.class).toInstance(statsProvider); requestInjection(interceptor); } }).getInstance(AnnotatedAuroraAdmin.class); }
@Before public void setUp() { statsInterceptor = new ThriftStatsExporterInterceptor(); realThrift = createMock(AnnotatedAuroraAdmin.class); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { MockDecoratedThrift.bindForwardedMock(binder(), realThrift); AopModule.bindThriftDecorator( binder(), Matchers.annotatedWith(DecoratedThrift.class), statsInterceptor); } }); decoratedThrift = injector.getInstance(AnnotatedAuroraAdmin.class); }
@Before public void setUp() { interceptor = new ServerInfoInterceptor(); realThrift = createMock(AnnotatedAuroraAdmin.class); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { MockDecoratedThrift.bindForwardedMock(binder(), realThrift); bind(IServerInfo.class).toInstance(SERVER_INFO); AopModule.bindThriftDecorator( binder(), Matchers.annotatedWith(DecoratedThrift.class), interceptor); } }); decoratedThrift = injector.getInstance(AnnotatedAuroraAdmin.class); }
@Override protected void configure() { bind(ReportEntryLogger.class).to(ReportEntryLoggerImpl.class); bind(TestEventCollector.class).to(TestEventCollectorImpl.class); bind(ReportingHandler.ACTIVE_REPORTERS).toProvider(ReporterProvider.class).in(Singleton.class); SubreportInterceptor subreportInterceptor = new SubreportInterceptor(); requestInjection(subreportInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(Subreport.class), subreportInterceptor); Multibinder<WebDriverEventListener> webDriverListenerBinder = Multibinder.newSetBinder(binder(), WebDriverEventListener.class); webDriverListenerBinder.addBinding().to(WebDriverLogger.class); Multibinder<ProxyEventListener> proxyListenerBinder = Multibinder.newSetBinder(binder(), ProxyEventListener.class); proxyListenerBinder.addBinding().to(ProxyLogger.class); }
/** * @see com.google.inject.AbstractModule#configure() */ @Override protected void configure() { logger.info("NinjaQuartz Module initialising."); // disable Quartz' checking for updates System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true"); bind(SchedulerFactory.class).toProvider(QuartzSchedulerFactoryProvider.class).in(Singleton.class); NinjaQuartzScheduleHelper scheduleHelper = new NinjaQuartzScheduleHelper(); requestInjection(scheduleHelper); bindListener(Matchers.any(), new NinjaQuartzTypeListener(scheduleHelper)); bind(NinjaQuartzScheduleHelper.class).toInstance(scheduleHelper); bind(NinjaQuartzUtil.class).to(NinjaQuartzUtilImpl.class); logger.info("NinjaQuartz Module initialisation completed."); }
private void bindInterceptors() { Instrumentor instrumentor = new Instrumentor( metricRegistry, healthCheckRegistry, exceptionFilter ); bindInterceptor( Matchers.annotatedWith(Instrumented.class), Matchers.not(Matchers.annotatedWith(Instrumented.class)), // in case of both, defer to method annotation InstrumentingInterceptor.ofClasses(instrumentor) ); bindInterceptor( Matchers.any(), Matchers.annotatedWith(Instrumented.class), InstrumentingInterceptor.ofMethods(instrumentor) ); }
/** * Performs concrete bindings for interfaces * @see com.google.inject.AbstractModule#configure() */ @Override protected void configure() { //bind entity classes bind(AuditDAO.class).to(AuditDAOImpl.class).in(Singleton.class); bind(EventsDAO.class).to(EventsDAOImpl.class).in(Singleton.class); bind(StateMachinesDAO.class).to(StateMachinesDAOImpl.class).in(Singleton.class); bind(StatesDAO.class).to(StatesDAOImpl.class).in(Singleton.class); //bind Transactional Interceptor to intercept methods which are annotated with javax.transaction.Transactional Provider<SessionFactoryContext> provider = getProvider(Key.get(SessionFactoryContext.class, Names.named("fluxSessionFactoryContext"))); final TransactionInterceptor transactionInterceptor = new TransactionInterceptor(provider); bindInterceptor(Matchers.not(Matchers.inPackage(MessageDao.class.getPackage())), Matchers.annotatedWith(Transactional.class), transactionInterceptor); bindInterceptor(Matchers.not(Matchers.inPackage(EventSchedulerDao.class.getPackage())), Matchers.annotatedWith(Transactional.class), transactionInterceptor); }
@Override protected void configure() { bindInterceptor(Matchers.any(), new AbstractMatcher<Method>() { @Override public boolean matches(Method method) { return getAuthAnnotations(method.getAnnotations()).isPresent(); } }, new MethodInterceptor() { @Override public Object invoke(MethodInvocation ctx) throws Throwable { Optional<Auth> methodAnnotation = getAuthAnnotations(ctx.getMethod().getAnnotations()); boolean allowAnon = methodAnnotation.map(Auth::pass).orElse(true); if (!allowAnon) { throw new Exception("Access denied"); } return ctx.proceed(); } }); }
public void testCachedInScopePreventsProvisionNotify() { final Counter count1 = new Counter(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), count1); bind(Foo.class).in(Scopes.SINGLETON); } }); Foo foo = injector.getInstance(Foo.class); assertNotNull(foo); assertEquals(1, count1.count); // not notified the second time because nothing is provisioned // (it's cached in the scope) count1.count = 0; assertSame(foo, injector.getInstance(Foo.class)); assertEquals(1, count1.count); }
public void testNotifyEarlyListenersIfFailBeforeProvision() { final Counter count1 = new Counter(); final Counter count2 = new Counter(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), count1, new FailBeforeProvision(), count2); } }); try { injector.getInstance(Foo.class); fail(); } catch (SaltaException e) { if (!e.getMessage().contains("boo")) throw e; } }
public void testNotifyLaterListenersIfFailAfterProvision() { final Counter count1 = new Counter(); final Counter count2 = new Counter(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), count1, new FailAfterProvision(), count2); } }); try { injector.getInstance(Foo.class); fail(); } catch (SaltaException e) { if (!e.getMessage().contains("boo")) throw e; } }
public void testBindToInjectorWithListeningGivesSaneException() { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new Counter()); bind(Injector.class) .toProvider(Providers.<Injector> of(null)); } }); fail(); } catch (SaltaException ce) { assertContains(ce.getMessage(), "Binding to core guice framework type is not allowed: Injector."); } }
public void testProvisionIsNotifiedAfterContextsClear() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new ProvisionListener() { @Override public <T> void onProvision( ProvisionInvocation<T> provision) { Object provisioned = provision.provision(); if (provisioned instanceof X) { ((X) provisioned).init(); } else if (provisioned instanceof Y) { X.createY = false; ((Y) provisioned).init(); } } }); } }); X.createY = true; X x = injector.getInstance(X.class); assertNotSame(x, x.y.x); assertFalse("x.ID: " + x.ID + ", x.y.x.iD: " + x.y.x.ID, x.ID == x.y.x.ID); }
@Test public void testInjection() throws Exception { // given final int newFieldValue = 1; final String newFiledValueStr = String.valueOf(newFieldValue); final Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { final ModelParameterTypeListener modelParameterTypeListener = new ModelParameterTypeListener(ImmutableMap.of("field", newFiledValueStr)); bindListener(Matchers.any(), modelParameterTypeListener); } }); // when final TypeParameterOwner instance = injector.getInstance(TypeParameterOwner.class); // then assertThat(instance, new CustomTypeSafeMatcher<TypeParameterOwner>("got it's fields injected") { @Override protected boolean matchesSafely(TypeParameterOwner item) { return item.field == newFieldValue; } }); }
@Override protected void configure() { String mathRecenteredJSONFile = MATH_RECENTERED_JSON_FILE; String verbalRecenteredJSONFile = VERBAL_RECENTERED_JSON_FILE; String settingsFileName = SETTINGS_FILE_NAME; bind(BuilderFactory.class).to(JavaFXBuilderFactory.class); bind(String.class).annotatedWith(Names.named("mathRecenteredJSONFile")).toInstance(mathRecenteredJSONFile); bind(String.class).annotatedWith(Names.named("verbalRecenteredJSONFile")).toInstance(verbalRecenteredJSONFile); bind(String.class).annotatedWith(Names.named("settingsFileName")).toInstance(settingsFileName); bind(SettingsDAO.class).to(SettingsDAOImpl.class).asEagerSingleton(); bind(RecenteredDAO.class).to(RecenteredDAOImpl.class).asEagerSingleton(); bindInterceptor(Matchers.subclassesOf(ManagedDataSource.class), Matchers.any(), new ManagedDataSourceInterceptor()); }
@Override protected void configure() { final Destroyer destroyer = new Destroyer(errorHandler); bind(Destroyer.class).toInstance(destroyer); bindListener( Matchers.any(), new TypeListener() { @Override public <T> void hear(TypeLiteral<T> type, TypeEncounter<T> encounter) { encounter.register( new InjectionListener<T>() { @Override public void afterInjection(T injectee) { final Method[] methods = get(injectee.getClass(), annotationType); if (methods.length > 0) { // copy array when pass it outside final Method[] copy = new Method[methods.length]; System.arraycopy(methods, 0, copy, 0, methods.length); destroyer.add(injectee, copy); } } }); } }); }
/** * Binds the {@link ServiceProxiesAggregator} that MUST contain fields of types implementing {@link ServiceInterface} which are * the concrete proxy implementation to the services * * The {@link ServiceInterface} fields of {@link ServiceProxiesAggregator} implementing type are LAZY loaded by * {@link ServicesClientProxyLazyLoaderGuiceMethodInterceptor} which guesses what proxy implementation assign to the field: * <ul> * <li>If the {@link ServiceProxiesAggregator} extends {@link ServiceProxiesAggregatorForDefaultImpls}, the concrete {@link ServiceInterface}-implementing * proxy instance is taken from the client properties XML file, so some service impls might be accessed using a BEAN proxy while others might be accessed * using a REST proxy -depending on the properties file-</li> * <li>If the {@link ServiceInterface} field's BEAN implementation is available this one will be assigned to the field no matter what type the aggregator is</li> * </ul> * @param binder */ private void _bindServiceProxiesAggregators(final Binder binder) { // Inject all Map fields that matches the service interface types with the bean impl or proxy to be used // (this Map fields are injected by MapBinders created at ServicesForAppModulePrivateGuiceModule) binder.requestInjection(_serviceInterfaceTypesToImplOrProxyMappings); // Create a private binder to be used to inject the MethodInterceptor that will intercept all fine-grained // proxy accessor method calls at ServicesAggregatorClientProxy // The interceptor lazily loads the fine-grained proxy instances and makes the aggregator creation simpler PrivateBinder privateBinder = binder.newPrivateBinder(); privateBinder.bind(ServiceInterfaceTypesToImplOrProxyMappings.class) .toInstance(_serviceInterfaceTypesToImplOrProxyMappings); MethodInterceptor serviceProxyGetterInterceptor = new ServicesClientProxyLazyLoaderGuiceMethodInterceptor(_apiAppAndModule, _coreAppAndModules); privateBinder.requestInjection(serviceProxyGetterInterceptor); // the method interceptor is feeded with a map of service interfaces to bean impl or proxy created below // Bind the interceptor to ServiceProxiesAggregator type's fine-grained method calls binder.bindInterceptor(Matchers.subclassesOf(ServiceProxiesAggregator.class), Matchers.any(), serviceProxyGetterInterceptor); // Bind every services proxy aggregator implementation log.info("[ServiceProxyAggregator] > {}",_servicesProxiesAggregatorType); binder.bind(_servicesProxiesAggregatorType) .in(Singleton.class); }
@Override public void configure(Binder binder) { // Some debugging if (log.isTraceEnabled()) { binder.bindListener(Matchers.any(), new ProvisionListener() { @Override @SuppressWarnings("rawtypes") public void onProvision(final ProvisionInvocation provision) { log.trace(">> Guice provisioning: {}",provision.getBinding()); } }); } log.warn("[START] R01F Bootstraping ________________________________"); //binder.requireExplicitBindings(); // All the injected members MUST be defined at the guice modules binder.install(new XMLPropertiesGuiceModule()); // XMLProperties binder.install(new ConfigPropertiesGuiceModule()); // Configs binder.install(new I18NGuiceModule()); // I18N binder.install(new GUIDDispenserGuiceModule()); // GUIDDispenser binder.install(new MarsallerGuiceModule()); // Marshaller binder.install(new JSonMarshallerGuiceModule()); // Marshalling de JSON log.warn(" [END] R01F Bootstraping ________________________________"); }
@Override protected void configure() { bind(new TypeLiteral<Optional<TermHistory>>(){}).toInstance(history); bind(FilterResource.class).to(DefaultFilterResource.class); bind(Terminology.class).toInstance(corpus.getTerminology()); bind(IndexedCorpus.class).toInstance(corpus); bind(Lang.class).toInstance(corpus.getTerminology().getLang()); bind(OccurrenceStore.class).toInstance(corpus.getOccurrenceStore()); bind(TerminologyService.class).toInstance(new TerminologyService(corpus.getTerminology())); bind(PipelineService.class).in(Singleton.class); bind(IndexService.class).toInstance(new IndexService(corpus.getTerminology())); bind(GroovyService.class).in(Singleton.class); bind(PipelineStats.class).in(Singleton.class); bind(PipelineListener.class).toInstance(listener); bindListener(Matchers.any(), new Slf4JTypeListener()); }
@Test @SuppressWarnings("unchecked") public void testCustomConstructor() throws Exception { // original type constructor copied and constructor injection correctly handled Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindInterceptor(Matchers.any(), Matchers.annotatedWith(CustomAop.class), new CustomAopInterceptor()); } }).getInstance(CustomConstructorBean.class).hello(); Class<?> generated = DynamicClassGenerator.generate(CustomConstructorBean.class); assertEquals(1, generated.getConstructors().length); Constructor ctor = generated.getConstructors()[0]; assertTrue(ctor.isAnnotationPresent(Inject.class)); assertTrue(ctor.isAnnotationPresent(Ann.class)); assertEquals("ctor", ((Ann) ctor.getAnnotation(Ann.class)).value()); assertEquals(1, ctor.getExceptionTypes().length); assertEquals(1, ctor.getParameterAnnotations()[0].length); Annotation ann = ctor.getParameterAnnotations()[0][0]; assertTrue(ann instanceof Ann); assertEquals("param", ((Ann) ann).value()); }
@Override protected void configureServlets() { // add support for the @PostConstruct annotation for Guice-injected objects // if you choose to remove it, also modify GuiceJsfInjector.invokePostConstruct() bindListener(Matchers.any(), new PostConstructTypeListener(null)); doCustomBinds(); bindJaxrsResources(); // configure Jersey: use Jackson + CORS-filter Map<String, String> initParams = new HashMap<>(); if (isUseJackson()) initParams.put("com.sun.jersey.api.json.POJOMappingFeature", "true"); String reponseFilters = getResponseFilters(); if (reponseFilters != null) initParams.put("com.sun.jersey.spi.container.ContainerResponseFilters", reponseFilters); doCustomJerseyParameters(initParams); // route all requests through Guice serve(getServingUrl()).with(GuiceContainer.class, initParams); doCustomServing(); }
protected void configureSecurity() { final SecurityInterceptor securityInterceptor = new SecurityInterceptor(); requestInjection(securityInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(AssertRole.class), securityInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(AssertAuthorizedUser.class), securityInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(AssertRoles.class), securityInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(AssertUser.class), securityInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(AssertCurrentUser.class), securityInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(AssertOneOfRoles.class), securityInterceptor); bindInterceptor(Matchers.annotatedWith(AssertRoles.class), Matchers.any(), securityInterceptor); bindInterceptor(Matchers.annotatedWith(AssertRole.class), Matchers.any(), securityInterceptor); bindInterceptor(Matchers.annotatedWith(AssertUser.class), Matchers.any(), securityInterceptor); bindInterceptor(Matchers.annotatedWith(AssertAuthorizedUser.class), Matchers.any(), securityInterceptor); bindInterceptor(Matchers.annotatedWith(AssertCurrentUser.class), Matchers.any(), securityInterceptor); bindInterceptor(Matchers.annotatedWith(AssertOneOfRoles.class), Matchers.any(), securityInterceptor); }
public void testExceptionInListenerBeforeProvisioning() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new FailBeforeProvision()); } }); try { injector.getInstance(Foo.class); fail(); } catch(ProvisionException pe) { assertEquals(1, pe.getErrorMessages().size()); assertContains(pe.getMessage(), "1) Error notifying ProvisionListener " + FailBeforeProvision.class.getName() + " of " + Foo.class.getName(), "Reason: java.lang.RuntimeException: boo", "while locating " + Foo.class.getName()); assertEquals("boo", pe.getCause().getMessage()); } }
public void testStringIsConvertedOnlyOnce() { final TypeConverter converter = new TypeConverter() { boolean converted = false; public Object convert(String value, TypeLiteral<?> toType) { if (converted) { throw new AssertionFailedError("converted multiple times!"); } converted = true; return new Date(); } }; Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { convertToTypes(Matchers.only(TypeLiteral.get(Date.class)), converter); bindConstant().annotatedWith(NumericValue.class).to("unused"); } }); Date first = injector.getInstance(Key.get(Date.class, NumericValue.class)); Date second = injector.getInstance(Key.get(Date.class, NumericValue.class)); assertSame(first, second); }
@Test public void testPostProcessingByType() throws Exception { final PostProcessor postProcessor = new PostProcessor(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Bean1.class).asEagerSingleton(); bind(Bean2.class).asEagerSingleton(); bind(Bean3.class).asEagerSingleton(); bindListener(Matchers.any(), new GeneralTypeListener<AbstractBean>(AbstractBean.class, postProcessor)); } }); Assert.assertEquals(postProcessor.called, 2); Assert.assertEquals(injector.getInstance(Bean1.class).called, 1); Assert.assertEquals(injector.getInstance(Bean2.class).called, 1); }
public void testInterceptedDefaultMethod() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindInterceptor( Matchers.any(), Matchers.annotatedWith(InterceptMe.class), interceptor); bind(Foo.class).to(NonOverridingFoo.class); } }); Foo foo = injector.getInstance(Foo.class); assertEquals("Foo", foo.defaultMethod()); assertEquals(1, callCount.get()); assertEquals(1, interceptedCallCount.get()); }
public void testInterceptedDefaultMethod_calledByAnotherMethod() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindInterceptor( Matchers.any(), Matchers.annotatedWith(InterceptMe.class), interceptor); } }); NonOverridingFoo foo = injector.getInstance(NonOverridingFoo.class); assertEquals("NonOverriding-Foo", foo.methodCallingDefault()); assertEquals(1, callCount.get()); assertEquals(1, interceptedCallCount.get()); }
public void testInterceptedDefaultMethod_whenParentClassDefinesNonInterceptedMethod() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindInterceptor( Matchers.any(), Matchers.annotatedWith(InterceptMe.class), interceptor); bind(Foo.class).to(InheritingFoo.class); } }); // the concrete implementation that wins is not annotated Foo foo = injector.getInstance(Foo.class); assertEquals("BaseClass", foo.defaultMethod()); assertEquals(1, callCount.get()); assertEquals(0, interceptedCallCount.get()); }
public void testListenerCallsProvisionTwice() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new ProvisionTwice()); } }); try { injector.getInstance(Foo.class); fail(); } catch(ProvisionException pe) { assertEquals(1, pe.getErrorMessages().size()); assertContains(pe.getMessage(), "1) Error notifying ProvisionListener " + ProvisionTwice.class.getName() + " of " + Foo.class.getName(), "Reason: java.lang.IllegalStateException: Already provisioned in this listener.", "while locating " + Foo.class.getName()); assertEquals("Already provisioned in this listener.", pe.getCause().getMessage()); } }
public void testInterception_ofAllMethodsOnType() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindInterceptor(Matchers.subclassesOf(Baz.class), Matchers.any(), interceptor); bind(Baz.class).to(BazImpl.class); } }); Baz baz = injector.getInstance(Baz.class); assertEquals("Baz", baz.doSomething()); assertEquals("BazImpl", baz.doSomethingElse()); assertEquals(2, interceptedCallCount.get()); }
public void testInterception_ofAllMethodsOnType_interceptsInheritedDefaultMethod() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindInterceptor(Matchers.subclassesOf(BazImpl.class), Matchers.any(), interceptor); bind(Baz.class).to(BazImpl.class); } }); Baz baz = injector.getInstance(Baz.class); assertEquals("Baz", baz.doSomething()); assertEquals("BazImpl", baz.doSomethingElse()); assertEquals(2, interceptedCallCount.get()); }
public void testToConstructorAndMethodInterceptors() throws NoSuchMethodException { final Constructor<D> constructor = D.class.getConstructor(Stage.class); final AtomicInteger count = new AtomicInteger(); final MethodInterceptor countingInterceptor = new MethodInterceptor() { public Object invoke(MethodInvocation methodInvocation) throws Throwable { count.incrementAndGet(); return methodInvocation.proceed(); } }; Injector injector = Guice.createInjector(new AbstractModule() { protected void configure() { bind(Object.class).toConstructor(constructor); bindInterceptor(Matchers.any(), Matchers.any(), countingInterceptor); } }); D d = (D) injector.getInstance(Object.class); d.hashCode(); d.hashCode(); assertEquals(2, count.get()); }
public void testCustomTypeConversion() throws CreationException { final Date result = new Date(); Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { convertToTypes( Matchers.only(TypeLiteral.get(Date.class)), mockTypeConverter(result)); bindConstant().annotatedWith(NumericValue.class).to("Today"); bind(DateHolder.class); } }); assertSame(result, injector.getInstance(DateHolder.class).date); Binding<Date> binding = injector.getBinding(Key.get(Date.class, NumericValue.class)); assertTrue(binding instanceof ConvertedConstantBinding<?>); TypeConverterBinding converterBinding = ((ConvertedConstantBinding<?>) binding).getTypeConverterBinding(); assertEquals("CustomConverter", converterBinding.getTypeConverter().toString()); assertTrue(injector.getTypeConverterBindings().contains(converterBinding)); }