下面列出了怎么用com.google.inject.matcher.Matchers的API类实例代码及写法,或者点击链接到github查看源代码。
@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());
}
});
}
/**
* 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;
}
}
});
}
@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(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))
);
}
@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);
}
@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);
}
@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);
}
@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);
}
/**
* 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);
}
@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() {
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);
}
}
});
}
});
}
@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);
}
}
});
}
/**
* 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);
}
}
});
}
@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());
}
@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() {});
}
/**
* 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);
}
@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);
}
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);
}
@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));
}
@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);
}
}
@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);
}
@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);
}
});
}
});
}
@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();
}
@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);
}
@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);
}
@Override
protected void configure() {
bindInterceptor(Matchers.subclassesOf(TestEndpoint.class), Matchers.any(),
new TestInterceptor());
bindInterceptor(Matchers.subclassesOf(Endpoint0.class), Matchers.any(),
new TestInterceptor());
}
@Override
protected void configure() {
bindInterceptor(Matchers.any(),
Matchers.annotatedWith(MessageSentLoggable.class),
new MessageLogger()
);
}
@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();
}
}
});
}
}