com.google.inject.matcher.Matchers Java Examples

The following examples show how to use com.google.inject.matcher.Matchers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: hivemq-community-edition   Author: hivemq   File: LifecycleModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {

    final boolean newRegistry = lifecycleRegistry.compareAndSet(null, new LifecycleRegistry());
    bind(LifecycleRegistry.class).toInstance(lifecycleRegistry.get());

    if (newRegistry) {
        bind(LifecycleShutdownRegistration.class).asEagerSingleton();
    }

    bindListener(Matchers.any(), new TypeListener() {
        @Override
        public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) {
            executePostConstruct(encounter, type.getRawType(), lifecycleRegistry.get());
        }
    });
}
 
Example #2
Source Project: attic-aurora   Author: apache   File: GuiceUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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: %s", 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;
          }
        }
      });
}
 
Example #3
Source Project: ja-micro   Author: Sixt   File: TestHandlerInterception.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source Project: ProjectAres   Author: OvercastNetwork   File: ContextualProviderModule.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@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();
                }
            }
        }
    });
}
 
Example #5
Source Project: titus-control-plane   Author: Netflix   File: ContainerEventBusModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    bind(ContainerEventBus.class).to(DefaultContainerEventBus.class);

    // Activation lifecycle
    ActivationProvisionListener activationProvisionListener = new ActivationProvisionListener();
    bind(ActivationLifecycle.class).toInstance(activationProvisionListener);
    bindListener(Matchers.any(), activationProvisionListener);

    // Proxies
    bindInterceptor(
            Matchers.annotatedWith(ProxyConfiguration.class),
            Matchers.any(),
            new ProxyMethodInterceptor(getProvider(ActivationLifecycle.class), getProvider(TitusRuntime.class))
    );
}
 
Example #6
Source Project: conductor   Author: Netflix   File: MetadataServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
    metadataDAO = Mockito.mock(MetadataDAO.class);
    eventHandlerDAO = Mockito.mock(EventHandlerDAO.class);
    eventQueues = Mockito.mock(EventQueues.class);
    configuration = Mockito.mock(Configuration.class);
    when(configuration.isOwnerEmailMandatory()).thenReturn(true);

    Injector injector =
            Guice.createInjector(
                    new AbstractModule() {
                        @Override
                        protected void configure() {

                            bind(MetadataDAO.class).toInstance(metadataDAO);
                            bind(EventHandlerDAO.class).toInstance(eventHandlerDAO);
                            bind(EventQueues.class).toInstance(eventQueues);
                            bind(Configuration.class).toInstance(configuration);

                            install(new ValidationModule());
                            bindInterceptor(
                                    Matchers.any(), Matchers.annotatedWith(Service.class), new ServiceInterceptor(getProvider(Validator.class)));
                        }
                    });
    metadataService = injector.getInstance(MetadataServiceImpl.class);
}
 
Example #7
Source Project: conductor   Author: Netflix   File: TaskServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
    executionService = Mockito.mock(ExecutionService.class);
    queueDAO = Mockito.mock(QueueDAO.class);
    Injector injector =
            Guice.createInjector(
                    new AbstractModule() {
                        @Override
                        protected void configure() {

                            bind(ExecutionService.class).toInstance(executionService);
                            bind(QueueDAO.class).toInstance(queueDAO);

                            install(new ValidationModule());
                            bindInterceptor(Matchers.any(), Matchers.annotatedWith(Service.class), new ServiceInterceptor(getProvider(Validator.class)));
                        }
                    });
    taskService = injector.getInstance(TaskServiceImpl.class);
}
 
Example #8
Source Project: conductor   Author: Netflix   File: EventServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
    metadataService = Mockito.mock(MetadataService.class);
    eventProcessor = Mockito.mock(SimpleEventProcessor.class);
    eventQueues = Mockito.mock(EventQueues.class);

    Injector injector =
            Guice.createInjector(
                    new AbstractModule() {
                        @Override
                        protected void configure() {

                            bind(MetadataService.class).toInstance(metadataService);
                            bind(EventProcessor.class).toInstance(eventProcessor);
                            bind(EventQueues.class).toInstance(eventQueues);

                            install(new ValidationModule());
                            bindInterceptor(Matchers.any(), Matchers.annotatedWith(Service.class), new ServiceInterceptor(getProvider(Validator.class)));
                        }
                    });
    eventService = injector.getInstance(EventServiceImpl.class);
}
 
Example #9
Source Project: EDDI   Author: labsai   File: BackupServiceModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    registerConfigFiles(this.configFiles);
    bind(IRestExportService.class).to(RestExportService.class).in(Scopes.SINGLETON);
    bind(IRestImportService.class).to(RestImportService.class).in(Scopes.SINGLETON);
    bind(IRestGitBackupService.class).to(RestGitBackupService.class).in(Scopes.SINGLETON);

    // AutoGit Injection - all methods that are annotated with @ConfigurationUpdate and start with
    // update or delete trigger a new commit/push
    bindInterceptor(Matchers.any(), new AbstractMatcher<>() {
        @Override
        public boolean matches(Method method) {
            return method.isAnnotationPresent(IResourceStore.ConfigurationUpdate.class) && !method.isSynthetic();
        }

    }, new GitConfigurationUpdateService(getProvider(IRestGitBackupService.class),
                                         getProvider(IBotStore.class),
                                         getProvider(IDeploymentStore.class),
                                         getProvider(IPackageStore.class),
                                         getProvider(IJsonSerialization.class)));
    bind(IZipArchive.class).to(ZipArchive.class).in(Scopes.SINGLETON);
}
 
Example #10
Source Project: flux   Author: flipkart-incubator   File: ShardModule.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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(ClientElbDAO.class).to(ClientElbDAOImpl.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("fluxSessionFactoriesContext")));
    final TransactionInterceptor transactionInterceptor = new TransactionInterceptor(provider);
    // Weird way of getting a package but java.lang.Package.getName(<String>) was no working for some reason.
    // todo [yogesh] dig deeper and fix this ^
    bindInterceptor(Matchers.not(Matchers.inPackage(MessageDao.class.getPackage())),
            Matchers.annotatedWith(Transactional.class), transactionInterceptor);
    bindInterceptor(Matchers.not(Matchers.inPackage(ScheduledMessage.class.getPackage())),
            Matchers.annotatedWith(Transactional.class), transactionInterceptor);
}
 
Example #11
Source Project: examples-javafx-repos1   Author: bekwam   File: OldScoresModule.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #12
Source Project: examples-javafx-repos1   Author: bekwam   File: OldScoresModule.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #13
Source Project: che   Author: eclipse   File: DestroyModule.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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);
                  }
                }
              });
        }
      });
}
 
Example #14
Source Project: dropwizard-guicier   Author: HubSpot   File: DropwizardModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void configure(final Binder binder) {
  binder.bindListener(Matchers.any(), new ProvisionListener() {
    @Override
    public <T> void onProvision(ProvisionInvocation<T> provision) {
      Object obj = provision.provision();

      if (obj instanceof Managed) {
        handle((Managed) obj);
      }

      if (obj instanceof Task) {
        handle((Task) obj);
      }

      if (obj instanceof HealthCheck) {
        handle((HealthCheck) obj);
      }

      if (obj instanceof ServerLifecycleListener) {
        handle((ServerLifecycleListener) obj);
      }
    }
  });
}
 
Example #15
Source Project: attic-aurora   Author: apache   File: GuiceUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
          }
        }
      });
}
 
Example #16
Source Project: termsuite-core   Author: termsuite   File: IndexedCorpusModule.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #17
Source Project: dropwizard-guicey   Author: xvik   File: CasesModule.java    License: MIT License 6 votes vote down vote up
@Override
protected void configure() {
    bindListener(new AbstractMatcher<TypeLiteral<?>>() {
        @Override
        public boolean matches(TypeLiteral<?> typeLiteral) {
            return false;
        }
    }, new CustomTypeListener());

    bindListener(new AbstractMatcher<Object>() {
        @Override
        public boolean matches(Object o) {
            return false;
        }
    }, new CustomProvisionListener());

    bindInterceptor(Matchers.subclassesOf(AopedService.class), Matchers.any(),
            new CustomAop());

    bind(AopedService.class);
    bind(BindService.class).to(OverriddenService.class);
    bind(BindService2.class).toInstance(new BindService2() {});
}
 
Example #18
Source Project: guice-persist-orient   Author: xvik   File: RepositoryModule.java    License: MIT License 6 votes vote down vote up
/**
 * Configures repository annotations interceptor.
 */
protected void configureAop() {
    final RepositoryMethodInterceptor proxy = new RepositoryMethodInterceptor();
    requestInjection(proxy);
    // repository specific method annotations (query, function, delegate, etc.)
    bindInterceptor(Matchers.any(), new AbstractMatcher<Method>() {
        @Override
        public boolean matches(final Method method) {
            // this will throw error if two or more annotations specified (fail fast)
            try {
                return ExtUtils.findMethodAnnotation(method) != null;
            } catch (Exception ex) {
                throw new MethodDefinitionException(String.format("Error declaration on method %s",
                        RepositoryUtils.methodToString(method)), ex);
            }
        }
    }, proxy);
}
 
Example #19
Source Project: attic-aurora   Author: apache   File: ServerInfoInterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #20
Source Project: seed   Author: seedstack   File: SecurityAopModule.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private void bindCrudInterceptor() {
    Multibinder<CrudActionResolver> crudActionResolverMultibinder = Multibinder.newSetBinder(binder(),
            CrudActionResolver.class);
    for (Class<? extends CrudActionResolver> crudActionResolverClass : crudActionResolverClasses) {
        crudActionResolverMultibinder.addBinding().to(crudActionResolverClass);
    }

    RequiresCrudPermissionsInterceptor requiresCrudPermissionsInterceptor = new
            RequiresCrudPermissionsInterceptor();
    requestInjection(requiresCrudPermissionsInterceptor);

    // Allows a single annotation at class level, or multiple annotations / one per method
    bindInterceptor(Matchers.annotatedWith(RequiresCrudPermissions.class), Matchers.any(),
            requiresCrudPermissionsInterceptor);
    bindInterceptor(Matchers.any(), Matchers.annotatedWith(RequiresCrudPermissions.class),
            requiresCrudPermissionsInterceptor);
}
 
Example #21
Source Project: seed   Author: seedstack   File: JndiModule.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    requestStaticInjection(JndiContext.class);

    // Bind default context
    Key<Context> defaultContextKey = Key.get(Context.class, Names.named("defaultContext"));
    bind(defaultContextKey).toInstance(this.defaultContext);
    bind(Context.class).to(defaultContextKey);

    // Bind additional contexts
    for (Map.Entry<String, Context> jndiContextToBeBound : jndiContextsToBeBound.entrySet()) {
        Key<Context> key = Key.get(Context.class, Names.named(jndiContextToBeBound.getKey()));
        bind(key).toInstance(jndiContextToBeBound.getValue());
    }

    bindListener(Matchers.any(), new ResourceTypeListener(this.defaultContext, this.jndiContextsToBeBound));
}
 
Example #22
Source Project: act-platform   Author: mnemonic-no   File: ServiceRequestScopeAspect.java    License: ISC License 5 votes vote down vote up
@Override
protected void configure() {
  bindInterceptor(Matchers.subclassesOf(Service.class), matchServiceMethod(), this);

  // Register service request scope in Guice.
  bindScope(ServiceRequestScope.class, scope);

  // Bind all contexts in service request scope. They must be explicitly seeded after the scope
  // has been entered, otherwise the UNSEEDED_KEY_PROVIDER will be called and throw an exception.
  for (Class ctx : contexts.keySet()) {
    bind(ctx).toProvider(UNSEEDED_KEY_PROVIDER).in(ServiceRequestScope.class);
  }
}
 
Example #23
Source Project: guice-validator   Author: xvik   File: ValidationModule.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected Matcher<? super Class<?>> getClassMatcher(final Class<? extends Annotation> annotation) {
    final Matcher<AnnotatedElement> res = Matchers.annotatedWith(annotation);
    return classMatcher == Matchers.any()
            // combine custom filter with annotation
            ? res : res.and((Matcher<? super AnnotatedElement>) classMatcher);
}
 
Example #24
Source Project: Scribengin   Author: DemandCube   File: MycilaJmxModuleExt.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void configure() {
  bindListener(ClassToTypeLiteralMatcherAdapter.adapt(Matchers.annotatedWith(JmxBean.class)), new TypeListener() {
    @Override
    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
      final Provider<JmxExporter> exporter = encounter.getProvider(JmxExporter.class);
      encounter.register(new InjectionListener<I>() {
        @Override
        public void afterInjection(I injectee) {
          exporter.get().register(injectee);
        }
      });
    }
  });
}
 
Example #25
Source Project: conductor   Author: Netflix   File: ServerModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    install(new CoreModule());
    install(new ValidationModule());
    install(new ArchaiusModule());
    install(new HealthModule());
    install(new JettyModule());
    install(new GRPCModule());

    bindInterceptor(Matchers.any(), Matchers.annotatedWith(Service.class), new ServiceInterceptor(getProvider(Validator.class)));
    bind(Configuration.class).to(SystemPropertiesDynomiteConfiguration.class);
    bind(ExecutorService.class).toProvider(ExecutorServiceProvider.class).in(Scopes.SINGLETON);
    bind(WorkflowSweeper.class).asEagerSingleton();
    bind(WorkflowMonitor.class).asEagerSingleton();
}
 
Example #26
Source Project: guice-validator   Author: xvik   File: CheckCustomMatcher.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    Injector injector = Guice.createInjector(new ValidationModule()
            .targetClasses(Matchers.not(Matchers.annotatedWith(SuppressValidation.class))));

    matchedService = injector.getInstance(MatchedService.class);
    exceptionalService = injector.getInstance(ExceptionalService.class);
}
 
Example #27
Source Project: bobcat   Author: Cognifide   File: TrafficModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
  Multibinder<ProxyEventListener> proxyListenerBinder
      = Multibinder.newSetBinder(binder(), ProxyEventListener.class);
  proxyListenerBinder.addBinding().to(TrafficLogProvider.class);

  RecordTrafficAspect recordTrafficAspect = new RecordTrafficAspect();
  requestInjection(recordTrafficAspect);
  bindInterceptor(Matchers.any(), Matchers.annotatedWith(RecordTraffic.class),
      recordTrafficAspect);
}
 
Example #28
Source Project: endpoints-java   Author: cloudendpoints   File: InterceptorModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
  bindInterceptor(Matchers.subclassesOf(TestEndpoint.class), Matchers.any(),
      new TestInterceptor());
  bindInterceptor(Matchers.subclassesOf(Endpoint0.class), Matchers.any(),
      new TestInterceptor());
}
 
Example #29
Source Project: tutorials   Author: eugenp   File: AOPModule.java    License: MIT License 5 votes vote down vote up
@Override
protected void configure() {
    bindInterceptor(Matchers.any(),
            Matchers.annotatedWith(MessageSentLoggable.class),
            new MessageLogger()
    );
}
 
Example #30
Source Project: emodb   Author: bazaarvoice   File: ParameterizedTimedListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <I> void hear(TypeLiteral<I> literal, TypeEncounter<I> encounter) {
    Class<? super I> type = literal.getRawType();
    for (Method method : type.getMethods()) {
        ParameterizedTimed annotation = method.getAnnotation(ParameterizedTimed.class);
        if (annotation == null) {
            continue;
        }

        String metricType = annotation.type();
        if(metricType == null || metricType.isEmpty()) {
            metricType = type.getSimpleName().replaceAll("\\$$", "");
        }
        String metricName = annotation.name();
        if(metricName == null || metricName.isEmpty()) {
            metricName = method.getName();
        }
        String metric = MetricRegistry.name(_group, metricType, metricName);
        final Timer timer = _metricRegistry.timer(metric);

        encounter.bindInterceptor(Matchers.only(method), new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                Timer.Context time = timer.time();
                try {
                    return invocation.proceed();
                } finally {
                    time.stop();
                }
            }
        });
    }
}