@Test @NoPostConstructFor(String.class) public void handles_annotation() throws NoSuchMethodException { final Method method = getClass().getMethod("handles_annotation"); final NoPostConstructExtension extension = new ExtensionFactory().create(method); assertNotNull(extension); when(annotatedType.getJavaClass()).thenReturn(String.class); extension.processAnnotatedType(processAnnotatedType); ArgumentCaptor<AnnotatedType> captor = ArgumentCaptor.forClass(AnnotatedType.class); verify(processAnnotatedType).setAnnotatedType(captor.capture()); final AnnotatedType newType = captor.getValue(); assertNotNull(newType.getAnnotation(NoPostConstructIntercepted.class)); }
@Test public void testInjectionTarget() { BeanManager beanManager = current().getBeanManager(); // CDI uses an AnnotatedType object to read the annotations of a class AnnotatedType<String> type = beanManager.createAnnotatedType(String.class); // The extension uses an InjectionTarget to delegate instantiation, // dependency injection // and lifecycle callbacks to the CDI container InjectionTarget<String> it = beanManager.createInjectionTarget(type); // each instance needs its own CDI CreationalContext CreationalContext<String> ctx = beanManager.createCreationalContext(null); // instantiate the framework component and inject its dependencies String instance = it.produce(ctx); // call the constructor it.inject(instance, ctx); // call initializer methods and perform field // injection it.postConstruct(instance); // call the @PostConstruct method // destroy the framework component instance and clean up dependent // objects assertNotNull("the String instance is injected now", instance); assertTrue("the String instance is injected now but it's empty", instance.isEmpty()); it.preDestroy(instance); // call the @PreDestroy method it.dispose(instance); // it is now safe to discard the instance ctx.release(); // clean up dependent objects }
@SuppressWarnings("unchecked") private <X, A extends AnnotatedMember<? super X>> A getAnnotatedMember(Class<X> javaClass, String memberName, BeanManager beanManager) { AnnotatedType<X> type = beanManager.createAnnotatedType(javaClass); for (AnnotatedField<? super X> field : type.getFields()) { if (field.getJavaMember().getName().equals(memberName)) { return (A) field; } } for (AnnotatedMethod<? super X> method : type.getMethods()) { if (method.getJavaMember().getName().equals(memberName)) { return (A) method; } } throw new IllegalArgumentException("Member " + memberName + " not found on " + javaClass); }
static String getConfigKey(InjectionPoint ip, ConfigProperty configProperty) { String key = configProperty.name(); if (!key.trim().isEmpty()) { return key; } if (ip.getAnnotated() instanceof AnnotatedMember) { AnnotatedMember member = (AnnotatedMember) ip.getAnnotated(); AnnotatedType declaringType = member.getDeclaringType(); if (declaringType != null) { String[] parts = declaringType.getJavaClass().getCanonicalName().split("\\."); StringBuilder sb = new StringBuilder(parts[0]); for (int i = 1; i < parts.length; i++) { sb.append(".").append(parts[i]); } sb.append(".").append(member.getJavaMember().getName()); return sb.toString(); } } throw new IllegalStateException("Could not find default name for @ConfigProperty InjectionPoint " + ip); }
public <T> AnnotatedType<T> getReplacement(AnnotatedType<T> originalType) { boolean modified = false; Set<AnnotatedMethod<? super T>> methods = new LinkedHashSet<>(); for (AnnotatedMethod<? super T> originalMethod : originalType.getMethods()) { AnnotatedMethod<? super T> replacement = getReplacement(originalType, originalMethod); if (replacement != null) { methods.add(replacement); modified = true; } else { methods.add(originalMethod); } } if (modified) { return new AnnotatedTypeWrapper<T>(originalType, methods); } return null; }
private <T> AnnotatedMethod<? super T> getReplacement(AnnotatedType<T> type, AnnotatedMethod<? super T> method) { boolean isResourceMethod = method.getAnnotation(GET.class) != null || method.getAnnotation(POST.class) != null || method.getAnnotation(PUT.class) != null || method.getAnnotation(HEAD.class) != null || method.getAnnotation(DELETE.class) != null; boolean hasControllerAnnotation = method.getAnnotation(Controller.class) != null || type.getAnnotation(Controller.class) != null; if (isResourceMethod && hasControllerAnnotation) { log.log(Level.FINE, "Found controller method: {0}#{1}", new Object[]{ type.getJavaClass().getName(), method.getJavaMember().getName() }); return new AnnotatedMethodWrapper<>( method, Collections.singleton(() -> ValidationInterceptorBinding.class) ); } return null; }
private boolean isRouteHandler(AnnotatedType<?> annotatedType) { if (!Reflections.isTopLevelOrStaticNestedClass(annotatedType.getJavaClass())) { LOGGER.warn("Ignoring {0} - class annotated with @WebRoute must be top-level or static nested class", annotatedType.getJavaClass()); return false; } Set<Type> types = new HierarchyDiscovery(annotatedType.getBaseType()).getTypeClosure(); for (Type type : types) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (parameterizedType.getRawType().equals(Handler.class)) { Type[] arguments = parameterizedType.getActualTypeArguments(); if (arguments.length == 1 && arguments[0].equals(RoutingContext.class)) { return true; } } } } LOGGER.warn("Ignoring {0} - class annotated with @WebRoute must implement io.vertx.core.Handler<RoutingContext>", annotatedType.getJavaClass()); return false; }
<T> void findJobs( @Observes @WithAnnotations({Cron.class}) ProcessAnnotatedType<T> pat, BeanManager beanManager ) { // Ensure we are named otherwise job won't fire as we can't locate it AnnotatedType<?> type = pat.getAnnotatedType(); Class<?> clazz = type.getJavaClass(); CDIUtils.addTypeAnnotation( pat, Named.class, () -> new NamedImpl( "Schedule_" + (id++) ) ); if( type.isAnnotationPresent( Cron.class ) ) { if( Job.class.isAssignableFrom( clazz ) ) { jobClasses.add( clazz ); } else { throw new UnsupportedOperationException( "@Cron on type must implement Job" ); } } else { for( AnnotatedMethod<?> meth: type.getMethods() ) { if( meth.isAnnotationPresent( Cron.class ) ) { jobClasses.add( clazz ); } } } }
/** * Ensure we have an annotation present * <p> * @param <T> * @param pat * @param clazz * @param s * <p> * @return */ public static <T> AnnotatedType<T> addTypeAnnotation( ProcessAnnotatedType<T> pat, Class<? extends Annotation> clazz, Supplier<Annotation> s ) { AnnotatedType<T> t = pat.getAnnotatedType(); if( !t.isAnnotationPresent( clazz ) ) { MutableAnnotatedType<T> mat; if( t instanceof MutableAnnotatedType ) { mat = (MutableAnnotatedType<T>) t; } else { mat = new MutableAnnotatedType<>( t ); pat.setAnnotatedType( mat ); } mat.add( s.get() ); return mat; } return t; }
/** * Instantiates <em>unmanaged instances</em> of HealthCheckProcedure and * handle manually their CDI creation lifecycle. * Add them to the {@link Monitor}. */ private void afterDeploymentValidation(@Observes final AfterDeploymentValidation abd, BeanManager beanManager) { try { for (AnnotatedType delegate : delegates) { Unmanaged<HealthCheck> unmanagedHealthCheck = new Unmanaged<HealthCheck>(beanManager, delegate.getJavaClass()); Unmanaged.UnmanagedInstance<HealthCheck> healthCheckInstance = unmanagedHealthCheck.newInstance(); HealthCheck healthCheck = healthCheckInstance.produce().inject().postConstruct().get(); healthChecks.add(healthCheck); healthCheckInstances.add(healthCheckInstance); monitor.registerHealthBean(healthCheck); log.info(">> Added health bean impl " + healthCheck); } // we don't need the references anymore delegates.clear(); } catch (Exception e) { throw new RuntimeException("Failed to register health bean", e); } }
/** * Get the property key to use. * In case the {@link ConfigProperty#name()} is empty we will try to determine the key name from the InjectionPoint. */ public static String getConfigKey(InjectionPoint ip, ConfigProperty configProperty) { String key = configProperty.name(); if (key.length() > 0) { return key; } if (ip.getAnnotated() instanceof AnnotatedMember) { AnnotatedMember member = (AnnotatedMember) ip.getAnnotated(); AnnotatedType declaringType = member.getDeclaringType(); if (declaringType != null) { String[] parts = declaringType.getJavaClass().getName().split("."); String cn = parts[parts.length-1]; parts[parts.length-1] = Character.toLowerCase(cn.charAt(0)) + (cn.length() > 1 ? cn.substring(1) : ""); StringBuilder sb = new StringBuilder(parts[0]); for (int i = 1; i < parts.length; i++) { sb.append(".").append(parts[i]); } // now add the field name sb.append(".").append(member.getJavaMember().getName()); return sb.toString(); } } throw new IllegalStateException("Could not find default name for @ConfigProperty InjectionPoint " + ip); }
static boolean hasAnnotation(AnnotatedType<?> type, Class<? extends Annotation> annotation) { if (type.isAnnotationPresent(annotation)) { return true; } for (AnnotatedMethod<?> method : type.getMethods()) { if (method.isAnnotationPresent(annotation)) { return true; } } for (AnnotatedConstructor<?> constructor : type.getConstructors()) { if (constructor.isAnnotationPresent(annotation)) { return true; } } for (AnnotatedField<?> field : type.getFields()) { if (field.isAnnotationPresent(annotation)) { return true; } } return false; }
/** * Activates the alternatives declared with {@code @Beans} globally for the * application. * <p/> * For every types and every methods of every types declared with * {@link Beans#alternatives()}, the {@code Priority} annotation is added * so that the corresponding alternatives are selected globally for the * entire application. * * @see Beans */ private <T> void alternatives(@Observes @WithAnnotations(Alternative.class) ProcessAnnotatedType<T> pat) { AnnotatedType<T> type = pat.getAnnotatedType(); if (!Arrays.asList(beans.alternatives()).contains(type.getJavaClass())) { // Only select globally the alternatives that are declared with @Beans return; } Set<AnnotatedMethod<? super T>> methods = new HashSet<>(); for (AnnotatedMethod<? super T> method : type.getMethods()) { if (method.isAnnotationPresent(Alternative.class) && !method.isAnnotationPresent(Priority.class)) { methods.add(new AnnotatedMethodDecorator<>(method, PriorityLiteral.of(APPLICATION))); } } if (type.isAnnotationPresent(Alternative.class) && !type.isAnnotationPresent(Priority.class)) { pat.setAnnotatedType(new AnnotatedTypeDecorator<>(type, PriorityLiteral.of(APPLICATION), methods)); } else if (!methods.isEmpty()) { pat.setAnnotatedType(new AnnotatedTypeDecorator<>(type, methods)); } }
private static Map<QualifierType, Set<Annotation>> extractQualifiers(final BeanManager bm, final AnnotatedType<?> annotated) { Map<QualifierType, Set<Annotation>> qualifiers = new HashMap<>(); AggregateConfiguration aggregateConfiguration = CdiUtils.findAnnotation(bm, annotated.getAnnotations(), AggregateConfiguration.class); if (aggregateConfiguration != null) { qualifiers.putAll( extractQualifiers(bm, aggregateConfiguration, annotated.getJavaClass())); } else { Set<Annotation> defaultQualifiers = CdiUtils.qualifiers(bm, annotated); for (QualifierType type : QualifierType.values()) { qualifiers.put(type, defaultQualifiers); } } return normalizeQualifiers(qualifiers); }
/** * Prepares the injection process of properties from a property file. * * @param pit * The actual target of process injection * @param <T> * the generic type of the injection target */ public <T> void initializePropertyLoading(@Observes final ProcessInjectionTarget<T> pit) throws IOException { AnnotatedType<T> at = pit.getAnnotatedType(); if (!at.isAnnotationPresent(PropertyFile.class)) { return; } try { PropertyFile propertyFile = at.getAnnotation(PropertyFile.class); Properties properties = loadProperties(propertyFile, pit.getAnnotatedType().getJavaClass()); Map<Field, Object> fieldValues = assignPropertiesToFields(at.getFields(), properties); InjectionTarget<T> wrapped = new PropertyInjectionTarget<T>(fieldValues, pit, pit.getInjectionTarget()); pit.setInjectionTarget(wrapped); } catch (Exception e) { pit.addDefinitionError(e); } }
@SuppressWarnings({"unchecked", "rawtypes"}) public static BeanManager beanManager(final CompletableFuture<Registry> injector) { return Reflection.newProxy(BeanManager.class, (proxy, method, args) -> { final String name = method.getName(); switch (name) { case "createAnnotatedType": return createAnnotatedType((Class) args[0]); case "createInjectionTarget": return createInjectionTarget(injector, ((AnnotatedType) args[0]).getJavaClass()); case "createCreationalContext": return createCreationalContext(); case "toString": return injector.toString(); default: throw new UnsupportedOperationException(method.toString()); } }); }
private static <T> T newInstance(final OpenEjbConfig config, final Class<T> clazz) throws Exception { final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb( Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE); if (webBeansContext == null) { return clazz.newInstance(); } final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl(); if (!beanManager.isInUse()) { return clazz.newInstance(); } final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz); final InjectionTarget<T> it = beanManager.createInjectionTarget(annotatedType); final CreationalContext<T> context = beanManager.createCreationalContext(null); final T instance = it.produce(context); it.inject(instance, context); it.postConstruct(instance); config.releasables.add(new Releasable<T>(context, it, instance)); return instance; }
private ConstructorInjectionBean<Object> getConstructorInjectionBean(final Class beanClass, final WebBeansContext webBeansContext) { if (webBeansContext == null) { return null; } ConstructorInjectionBean<Object> beanDefinition = constructorInjectionBeanCache.get(beanClass); if (beanDefinition == null) { synchronized (this) { beanDefinition = constructorInjectionBeanCache.get(beanClass); if (beanDefinition == null) { final AnnotatedType annotatedType = webBeansContext.getAnnotatedElementFactory().newAnnotatedType(beanClass); if (isWeb(beanClass)) { beanDefinition = new ConstructorInjectionBean<>(webBeansContext, beanClass, annotatedType, false); } else { beanDefinition = new ConstructorInjectionBean<>(webBeansContext, beanClass, annotatedType); } constructorInjectionBeanCache.put(beanClass, beanDefinition); } } } return beanDefinition; }
/** * Manually inject dependencies. Inspired by https://developer.jboss.org/thread/196807 * * @param clazz * @param injectionObject * @throws NamingException */ public static <T> T programmaticInjection(Class<T> clazz, T injectionObject) throws NamingException { InitialContext initialContext = new InitialContext(); Object lookup = initialContext.lookup("java:comp/BeanManager"); BeanManager beanManager = (BeanManager) lookup; AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz); InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget(annotatedType); CreationalContext<T> creationalContext = beanManager.createCreationalContext(null); injectionTarget.inject(injectionObject, creationalContext); injectionTarget.postConstruct(injectionObject); //call the @PostConstruct method creationalContext.release(); return injectionObject; }
@Before public final void setUp() throws Exception { System.out.printf("AbstractCdiContainerTest#setUp() containerRefCount=%d, cdiContainer=%s\n", containerRefCount.get(), cdiContainer ); if ( cdiContainer != null ) { containerRefCount.incrementAndGet(); final ContextControl ctxCtrl = BeanProvider.getContextualReference(ContextControl.class); //stop the RequestContext to dispose of the @RequestScoped EntityManager ctxCtrl.stopContext(RequestScoped.class); //immediately restart the context again ctxCtrl.startContext(RequestScoped.class); // perform injection into the very own test class final BeanManager beanManager = cdiContainer.getBeanManager(); final CreationalContext creationalContext = beanManager.createCreationalContext(null); final AnnotatedType annotatedType = beanManager.createAnnotatedType(this.getClass()); final InjectionTarget injectionTarget = beanManager.createInjectionTarget(annotatedType); injectionTarget.inject(this, creationalContext); } }
protected <T> Bean<T> createBean(Class<T> beanClass, BeanManager beanManager) { Class<? extends InvocationHandler> invocationHandlerClass = Converter.class.isAssignableFrom(beanClass) ? ConverterInvocationHandler.class : ValidatorInvocationHandler.class; AnnotatedType<T> annotatedType = new AnnotatedTypeBuilder<T>().readFromType(beanClass).create(); DeltaSpikeProxyContextualLifecycle lifecycle = new DeltaSpikeProxyContextualLifecycle(beanClass, invocationHandlerClass, ConverterAndValidatorProxyFactory.getInstance(), beanManager); BeanBuilder<T> beanBuilder = new BeanBuilder<T>(beanManager) .readFromType(annotatedType) .passivationCapable(true) .beanLifecycle(lifecycle); return beanBuilder.create(); }
Jsf2BeanWrapper(AnnotatedType wrapped, Class<? extends Annotation> cdiScopeAnnotation, Class<? extends Annotation> jsf2ScopeAnnotation) { this.wrapped = wrapped; Set<Annotation> originalAnnotationSet = wrapped.getAnnotations(); this.annotations = new HashMap<Class<? extends Annotation>, Annotation>(originalAnnotationSet.size()); for (Annotation originalAnnotation : originalAnnotationSet) { if (!originalAnnotation.annotationType().equals(jsf2ScopeAnnotation)) { this.annotations.put(originalAnnotation.annotationType(), originalAnnotation); } } this.annotations.put(cdiScopeAnnotation, AnnotationInstanceProvider.of(cdiScopeAnnotation)); this.annotationSet = new HashSet<Annotation>(this.annotations.size()); this.annotationSet.addAll(this.annotations.values()); }
public DeltaSpikeProxyContextualLifecycle(Class<T> targetClass, Class<H> delegateInvocationHandlerClass, DeltaSpikeProxyFactory proxyFactory, BeanManager beanManager) { this.targetClass = targetClass; this.delegateInvocationHandlerClass = delegateInvocationHandlerClass; this.proxyClass = proxyFactory.getProxyClass(beanManager, targetClass); this.delegateMethods = proxyFactory.getDelegateMethods(targetClass); this.beanManager = beanManager; if (!targetClass.isInterface()) { AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(this.targetClass); this.injectionTarget = beanManager.createInjectionTarget(annotatedType); } }
/** * Performs dependency injection on an instance. Useful for instances which aren't managed by CDI. * <p/> * <b>Attention:</b><br/> * The resulting instance isn't managed by CDI; only fields annotated with @Inject get initialized. * * @param instance current instance * @param <T> current type * * @return instance with injected fields (if possible - or null if the given instance is null) */ @SuppressWarnings("unchecked") public static <T> T injectFields(T instance) { if (instance == null) { return null; } BeanManager beanManager = getBeanManager(); CreationalContext<T> creationalContext = beanManager.createCreationalContext(null); AnnotatedType<T> annotatedType = beanManager.createAnnotatedType((Class<T>) instance.getClass()); InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget(annotatedType); injectionTarget.inject(instance, creationalContext); return instance; }
@Test public void modifyAnnotationsOnConstructorParameter() throws NoSuchMethodException { final AnnotatedTypeBuilder<Cat> builder = new AnnotatedTypeBuilder<Cat>(); builder.readFromType(Cat.class, true); builder.removeFromConstructorParameter(Cat.class.getConstructor(String.class, String.class), 1, Default.class); builder.addToConstructorParameter(Cat.class.getConstructor(String.class, String.class), 1, new AnyLiteral()); final AnnotatedType<Cat> catAnnotatedType = builder.create(); Set<AnnotatedConstructor<Cat>> catCtors = catAnnotatedType.getConstructors(); assertThat(catCtors.size(), is(2)); for (AnnotatedConstructor<Cat> ctor : catCtors) { if (ctor.getParameters().size() == 2) { List<AnnotatedParameter<Cat>> ctorParams = ctor.getParameters(); assertThat(ctorParams.get(1).getAnnotations().size(), is(1)); assertThat((AnyLiteral) ctorParams.get(1).getAnnotations().toArray()[0], is(new AnyLiteral())); } } }
@SuppressWarnings("UnusedDeclaration") protected void detectInterfaces(@Observes ProcessAnnotatedType processAnnotatedType) { if (!isActivated) { return; } AnnotatedType<?> type = processAnnotatedType.getAnnotatedType(); if (type.isAnnotationPresent(MessageBundle.class)) { if (validateMessageBundle(type.getJavaClass())) { messageBundleTypes.add(type); } } }
@SuppressWarnings("UnusedDeclaration") protected void installMessageBundleProducerBeans(@Observes AfterBeanDiscovery abd, BeanManager beanManager) { if (!deploymentErrors.isEmpty()) { abd.addDefinitionError(new IllegalArgumentException("The following MessageBundle problems where found: " + Arrays.toString(deploymentErrors.toArray()))); return; } MessageBundleExtension parentExtension = ParentExtensionStorage.getParentExtension(this); if (parentExtension != null) { messageBundleTypes.addAll(parentExtension.messageBundleTypes); } for (AnnotatedType<?> type : messageBundleTypes) { abd.addBean(createMessageBundleBean(type, beanManager)); } }
private <T> Bean<T> createMessageBundleBean(AnnotatedType<T> annotatedType, BeanManager beanManager) { BeanBuilder<T> beanBuilder = new BeanBuilder<T>(beanManager).readFromType(annotatedType); beanBuilder.beanLifecycle(new MessageBundleLifecycle<T>(beanManager)); beanBuilder.types(annotatedType.getJavaClass(), Object.class, Serializable.class); beanBuilder.addQualifier(new DefaultLiteral()); beanBuilder.passivationCapable(true); beanBuilder.scope(ApplicationScoped.class); // needs to be a normalscope due to a bug in older Weld versions beanBuilder.id("MessageBundleBean#" + annotatedType.getJavaClass().getName()); return beanBuilder.create(); }
GlobalInterceptorWrapper(AnnotatedType wrapped, Annotation priorityAnnotation) { this.wrapped = wrapped; Set<Annotation> originalAnnotationSet = wrapped.getAnnotations(); this.annotations = new HashMap<Class<? extends Annotation>, Annotation>(originalAnnotationSet.size()); for (Annotation originalAnnotation : originalAnnotationSet) { this.annotations.put(originalAnnotation.annotationType(), originalAnnotation); } this.annotations.put(priorityAnnotation.annotationType(), priorityAnnotation); this.annotationSet = new HashSet<Annotation>(this.annotations.size()); this.annotationSet.addAll(this.annotations.values()); }
protected ExecutorService getOrCreatePool(final InvocationContext ic) { final Method method = ic.getMethod(); ExecutorService executorService = configByMethod.get(method); if (executorService == null) { final AnnotatedType<?> annotatedType = beanManager.createAnnotatedType(method.getDeclaringClass()); final AnnotatedMethod<?> annotatedMethod = AnnotatedMethods.findMethod(annotatedType, method); final Futureable methodConfig = annotatedMethod.getAnnotation(Futureable.class); final ExecutorService instance = manager.find( (methodConfig == null ? annotatedType.getAnnotation(Futureable.class) : methodConfig).value()); configByMethod.putIfAbsent(method, instance); executorService = instance; } return executorService; }
public static AnnotatedMethod<?> findMethod(final AnnotatedType<?> type, final Method method) { AnnotatedMethod<?> annotatedMethod = null; for (final AnnotatedMethod<?> am : type.getMethods()) { if (am.getJavaMember().equals(method)) { annotatedMethod = am; break; } } if (annotatedMethod == null) { throw new IllegalStateException("No annotated method for " + method); } return annotatedMethod; }
public FilteringAnnotatedTypeWrapper( final AnnotatedType<T> delegate, final Predicate<Class<? extends Annotation>> filter ) { this.delegate = delegate; this.filter = filter; }
public PersistenceAnnotatedType(BeanManager manager, AnnotatedType<T> delegate) { super(delegate); this.manager = manager; this.fields = new HashSet<>(); for (AnnotatedField<? super T> field : delegate.getFields()) { if (field.isAnnotationPresent(PersistenceContext.class)) { field = decorateContext(field); } else if (field.isAnnotationPresent(PersistenceUnit.class)) { field = decorateUnit(field); } this.fields.add(field); } }
<X> void processBean(@Observes ProcessManagedBean<X> event) { AnnotatedType<X> annotatedType = event.getAnnotatedBeanClass(); Transactional classTx = annotatedType.getAnnotation(Transactional.class); for (AnnotatedMethod<? super X> am : annotatedType.getMethods()) { Transactional methodTx = am.getAnnotation(Transactional.class); if (classTx != null || methodTx != null) { Method method = am.getJavaMember(); Transactional attrType = mergeTransactionAttributes(classTx, methodTx); transactionAttributes.put(method, attrType); } } }
/** * Discover all classes that implements HealthCheckProcedure */ public void observeResources(@Observes @WithAnnotations({Health.class}) ProcessAnnotatedType<? extends HealthCheck> event) { AnnotatedType<? extends HealthCheck> annotatedType = event.getAnnotatedType(); Class<? extends HealthCheck> javaClass = annotatedType.getJavaClass(); MicroProfileHealthLogger.ROOT_LOGGER.debugf("Discovered health check procedure %s", javaClass); delegates.add(annotatedType); }
/** * Instantiates <em>unmanaged instances</em> of HealthCheckProcedure and * handle manually their CDI creation lifecycle. * Add them to the {@link HealthMonitor}. */ private void afterDeploymentValidation(@Observes final AfterDeploymentValidation avd, BeanManager bm) { for (AnnotatedType delegate : delegates) { try { Unmanaged<HealthCheck> unmanagedHealthCheck = new Unmanaged<HealthCheck>(bm, delegate.getJavaClass()); UnmanagedInstance<HealthCheck> healthCheckInstance = unmanagedHealthCheck.newInstance(); HealthCheck healthCheck = healthCheckInstance.produce().inject().postConstruct().get(); healthChecks.add(healthCheck); healthCheckInstances.add(healthCheckInstance); healthMonitor.addHealthCheck(healthCheck); } catch (Exception e) { throw new RuntimeException("Failed to register health bean", e); } } }
/** * Searches methods in the underlying class annotated with @Failsafe annotation for not returning Optional<T>. * * @param annotatedType Class annotated with @Failsafe annotation * @param <X> Generic type of AnnotatedType * @return Potentially empty list of public methods not returning Optional<T>. */ private <X> List<AnnotatedMethod<? super X>> findGuardedMethodsWithBadReturnType(AnnotatedType<X> annotatedType) { return annotatedType.getMethods() .stream() .filter(method -> method.isAnnotationPresent(Failsafe.class) || method.isAnnotationPresent(Semisafe.class)) .filter(annotatedMethod -> !annotatedMethod.getJavaMember().getReturnType().equals(Optional.class)) .collect(Collectors.toList()); }
public void process(Set<AnnotatedType<?>> discoveredTypes) { for(AnnotatedType<?> at : discoveredTypes) { for(AnnotatedMethod<?> am : at.getMethods()) { boolean hasObserver = am.getParameters().stream().anyMatch(ap -> ap.getAnnotation(ObservesReactor.class) != null); if(hasObserver) { AnnotatedParameter<?> observerType = am.getParameters().stream().filter(ap -> ap.isAnnotationPresent(ObservesReactor.class)).findFirst().orElseThrow(() -> new RuntimeException("No observer found")); Class<?> returnType = null; Type genericReturnType = am.getJavaMember().getGenericReturnType(); boolean returnsPublisher = false; if(genericReturnType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType)genericReturnType; if(Publisher.class.isAssignableFrom((Class<?>) type.getRawType())) { returnsPublisher = true; returnType = (Class<?>) type.getActualTypeArguments()[0]; } else { throw new RuntimeException("Method "+am+" should either return a concrete type or an instance of "+Publisher.class.getName()); } } else { returnType = (Class)genericReturnType; } Class<?> eventType = observerType.getJavaParameter().getType(); Set<Annotation> annotations = new LinkedHashSet<>(asList(observerType.getJavaParameter().getAnnotations())); methods.add(new ReactorMethod(at,am,returnType,eventType,annotations,returnsPublisher)); } } } }
ReactorMethod(AnnotatedType<?> annotatedType, AnnotatedMethod<?> annotatedMethod, Class<T> returnType, Class<?> eventType, Set<Annotation> eventQualifiers, boolean returnsPublisher) { this.annotatedType = annotatedType; this.annotatedMethod = annotatedMethod; this.returnType = returnType; this.eventType = eventType; this.eventQualifiers = findQualifiers(eventQualifiers); this.returnsPublisher = returnsPublisher; try { this.targetMethod = locateMethod(); } catch (NoSuchMethodException e) { throw new RuntimeException("Unable to locate method",e); } }
public void registerRoutes(Router router) { for (AnnotatedType<? extends Handler<RoutingContext>> annotatedType : handlerTypes) { processHandlerType(annotatedType, router); } for (RouteObserver routeObserver : routeObservers) { routeObserver.process(router); } }