@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); }
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; }
<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 ); } } } }
private static CamelContextNameStrategy nameStrategy(Annotated annotated) { if (annotated.isAnnotationPresent(ContextName.class)) { return new ExplicitCamelContextNameStrategy(annotated.getAnnotation(ContextName.class).value()); } else if (annotated.isAnnotationPresent(Named.class)) { // TODO: support stereotype with empty @Named annotation String name = annotated.getAnnotation(Named.class).value(); if (name.isEmpty()) { if (annotated instanceof AnnotatedField) { name = ((AnnotatedField) annotated).getJavaMember().getName(); } else if (annotated instanceof AnnotatedMethod) { name = ((AnnotatedMethod) annotated).getJavaMember().getName(); if (name.startsWith("get")) { name = decapitalize(name.substring(3)); } } else { name = decapitalize(getRawType(annotated.getBaseType()).getSimpleName()); } } return new ExplicitCamelContextNameStrategy(name); } else { // Use a specific naming strategy for Camel CDI as the default one increments the suffix for each CDI proxy created return new CdiCamelContextNameStrategy(); } }
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 CamelContextNameStrategy nameStrategy(Annotated annotated) { if (annotated.isAnnotationPresent(ContextName.class)) { return new ExplicitCamelContextNameStrategy(annotated.getAnnotation(ContextName.class).value()); } else if (annotated.isAnnotationPresent(Named.class)) { // TODO: support stereotype with empty @Named annotation String name = annotated.getAnnotation(Named.class).value(); if (name.isEmpty()) { if (annotated instanceof AnnotatedField) { name = ((AnnotatedField) annotated).getJavaMember().getName(); } else if (annotated instanceof AnnotatedMethod) { name = ((AnnotatedMethod) annotated).getJavaMember().getName(); if (name.startsWith("get")) name = decapitalize(name.substring(3)); } else { name = decapitalize(getRawType(annotated.getBaseType()).getSimpleName()); } } return new ExplicitCamelContextNameStrategy(name); } else { // Use a specific naming strategy for Camel CDI as the default one increments the suffix for each CDI proxy created return new CdiCamelContextNameStrategy(); } }
public int compare(AnnotatedMethod<? super T> arg0, AnnotatedMethod<? super T> arg1) { int result = callableComparator.compare(arg0, arg1); if (result != 0) { return result; } for (int i = 0; i < arg0.getJavaMember().getParameterTypes().length; ++i) { Class<?> p0 = arg0.getJavaMember().getParameterTypes()[i]; Class<?> p1 = arg1.getJavaMember().getParameterTypes()[i]; result = p0.getName().compareTo(p1.getName()); if (result != 0) { return result; } } return 0; }
/** * Determines if the given method is a handler by looking for the {@link Handles} annotation on a parameter. * * @param method method to search * @return true if {@link Handles} is found, false otherwise */ public static boolean isHandler(final AnnotatedMethod<?> method) { if (method == null) { throw new IllegalArgumentException("Method must not be null"); } for (AnnotatedParameter<?> param : method.getParameters()) { if (param.isAnnotationPresent(Handles.class) || param.isAnnotationPresent(BeforeHandles.class)) { return true; } } return false; }
public static AnnotatedParameter<?> findHandlerParameter(final AnnotatedMethod<?> method) { if (!isHandler(method)) { throw new IllegalArgumentException("Method is not a valid handler"); } AnnotatedParameter<?> returnParam = null; for (AnnotatedParameter<?> param : method.getParameters()) { if (param.isAnnotationPresent(Handles.class) || param.isAnnotationPresent(BeforeHandles.class)) { returnParam = param; break; } } return returnParam; }
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; }
@Override public ReadWriteLock newLock(final AnnotatedMethod<?> method, final boolean fair) { final String name = method.getJavaMember().getDeclaringClass().getName(); ReadWriteLock lock = locks.get(name); if (lock == null) { lock = new ReentrantReadWriteLock(fair); final ReadWriteLock existing = locks.putIfAbsent(name, lock); if (existing != null) { lock = existing; } } return lock; }
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; }
@Override public Semaphore newSemaphore(final AnnotatedMethod<?> method, final String name, final boolean fair, final int permits) { Semaphore semaphore = semaphores.get(name); if (semaphore == null) { semaphore = new Semaphore(permits, fair); final Semaphore existing = semaphores.putIfAbsent(name, semaphore); if (existing != null) { semaphore = existing; } } return semaphore; }
<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); } } }
/** * 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()); }
/** * Logs names of methods and their declaring classes without proper return type * * @param badMethods List of bad methods to print * @param <X> Generic type of AnnotatedType */ private <X> void logBadMethods(List<AnnotatedMethod<? super X>> badMethods) { badMethods.forEach(method -> { final String error = String.format("A guarded method %s does not return Optional<T>.", method.getJavaMember().toString()); logger.log(Level.INFO, error); }); }
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); } }
private boolean hasEventParameter(AnnotatedMethod<?> annotatedMethod) { for (AnnotatedParameter<?> param : annotatedMethod.getParameters()) { if (param.isAnnotationPresent(Observes.class)) { return true; } } return false; }
/** * For each method in a type that has a specific annotation pass the class and method to a consumer * * @param <T> * @param pat * @param annotationType * @param c */ public static <T> void forEachMethod( ProcessAnnotatedType<T> pat, Class<? extends Annotation> annotationType, BiConsumer<Class<?>, ? super AnnotatedMethod<? extends Object>> c ) { AnnotatedType<?> type = pat.getAnnotatedType(); Class<?> clazz = type.getJavaClass(); type.getMethods() .stream(). filter( meth -> meth.isAnnotationPresent( annotationType ) ). forEach( m -> c.accept( clazz, m ) ); }
@Override public Set<AnnotatedMethod<? super X>> getMethods() { Set<AnnotatedMethod<? super X>> methods = new HashSet<>(decoratedType.getMethods()); for (AnnotatedMethod<? super X> method : decoratedMethods) { methods.remove(method); methods.add(method); } return Collections.unmodifiableSet(methods); }
private static <T extends Annotation> void declareAsInterceptorBinding(Class<T> annotation, BeanManager manager, BeforeBeanDiscovery bbd) { AnnotatedType<T> annotated = manager.createAnnotatedType(annotation); Set<AnnotatedMethod<? super T>> methods = new HashSet<>(); for (AnnotatedMethod<? super T> method : annotated.getMethods()) { methods.add(new AnnotatedMethodDecorator<>(method, NON_BINDING)); } bbd.addInterceptorBinding(new AnnotatedTypeDecorator<>(annotated, INTERCEPTOR_BINDING, methods)); }
private static boolean hasInjectionPointMetadata(AnnotatedMember<?> member) { if (!(member instanceof AnnotatedMethod)) { return false; } AnnotatedMethod<?> method = (AnnotatedMethod<?>) member; for (AnnotatedParameter<?> parameter : method.getParameters()) { if (parameter.getBaseType().equals(InjectionPoint.class)) { return true; } } return false; }
public static FaultToleranceOperation of(AnnotatedMethod<?> annotatedMethod) { return new FaultToleranceOperation(annotatedMethod.getJavaMember(), isAnnotated(Asynchronous.class, annotatedMethod), getConfig(Bulkhead.class, annotatedMethod, BulkheadConfig::new), getConfig(CircuitBreaker.class, annotatedMethod, CircuitBreakerConfig::new), getConfig(Fallback.class, annotatedMethod, FallbackConfig::new), getConfig(Retry.class, annotatedMethod, RetryConfig::new), getConfig(Timeout.class, annotatedMethod, TimeoutConfig::new)); }
private static <A extends Annotation, C extends GenericConfig<A>> C getConfig(Class<A> annotationType, AnnotatedMethod<?> annotatedMethod, Function<AnnotatedMethod<?>, C> function) { if (isAnnotated(annotationType, annotatedMethod)) { return function.apply(annotatedMethod); } return null; }
private GenericConfig(Method method, AnnotatedMethod<?> annotatedMethod, X annotation, ElementType annotationSource) { this.method = method; this.annotatedMethod = annotatedMethod; this.annotation = annotation; this.annotationSource = annotationSource; this.values = getConfig().getOptionalValue(CONFIG_PARAMS_CACHE_KEY, Boolean.class).orElse(true) ? new ConcurrentHashMap<>() : null; }
/** * Observe all enabled managed beans and identify/validate FT operations. This allows us to: * <ul> * <li>Skip validation of types which are not recognized as beans (e.g. are vetoed)</li> * <li>Take the final values of AnnotatedTypes</li> * <li>Support annotations added via portable extensions</li> * </ul> * * @param event */ void collectFaultToleranceOperations(@Observes ProcessManagedBean<?> event) { AnnotatedType<?> annotatedType = event.getAnnotatedBeanClass(); for (AnnotatedMethod<?> annotatedMethod : annotatedType.getMethods()) { FaultToleranceOperation operation = FaultToleranceOperation.of(annotatedMethod); if (operation.isLegitimate() && operation.validate()) { LOGGER.debugf("Found %s", operation); faultToleranceOperations.put(annotatedMethod.getJavaMember().toGenericString(), operation); } } }
AnnotatedTypeDelegate(AnnotatedType<T> delegate, Set<AnnotatedMethod<? super T>> methods) { super(delegate); this.delegate = delegate; this.methods = new HashSet<>(delegate.getMethods()); this.methods.removeAll(methods); this.methods.addAll(methods); }
public <X> void processInjectedPersistenceResources(@Observes ProcessAnnotatedType<X> event) { for (AnnotatedMethod<? super X> method : event.getAnnotatedType().getMethods()) handleAnnotatedMember(method); for (AnnotatedField<? super X> field : event.getAnnotatedType().getFields()) handleAnnotatedMember(field); }
/** * Adds the {@link Inject} annotation to the fields and setters of the annotated type if required. * * @param <X> * the type of the annotated type * @param annotatedType * the annotated type whose fields and setters the inject annotation should be added to * @param builder * the builder that should be used to add the annotation. * @see #shouldInjectionAnnotationBeAddedToMember(AnnotatedMember) */ public static <X> void addInjectAnnotation(final AnnotatedType<X> annotatedType, AnnotatedTypeBuilder<X> builder) { for (AnnotatedField<? super X> field : annotatedType.getFields()) { if (shouldInjectionAnnotationBeAddedToMember(field)) { builder.addToField(field, AnnotationInstances.INJECT); } } for (AnnotatedMethod<? super X> method : annotatedType.getMethods()) { if (shouldInjectionAnnotationBeAddedToMember(method)) { builder.addToMethod(method, AnnotationInstances.INJECT); } } }
public <X> void processAnnotatedType(@Observes ProcessAnnotatedType<X> pat) { // Wrap this to override the annotations of the class final AnnotatedType<X> at = pat.getAnnotatedType(); final AnnotatedTypeConfigurator<X> cat = pat.configureAnnotatedType(); // Collect Secure annotation from the type List<Secure> typeSecureAnnotations = new ArrayList<Secure>(); for (Annotation annotation : pat.getAnnotatedType().getAnnotations()) { collectAnnotations(Secure.class, annotation, typeSecureAnnotations); } // Collect the Secure annotations from the methods for (AnnotatedMethodConfigurator<? super X> methodConfiguration : cat.methods()) { AnnotatedMethod<?> method = methodConfiguration.getAnnotated(); final List<Secure> methodAnnotations = new ArrayList<Secure>(typeSecureAnnotations); collectAnnotations(Secure.class, method, methodAnnotations); // Store in the map if we find Secure annotations if (methodAnnotations.size() > 0) { InterceptSecure is = new InterceptSecureImpl(methodAnnotations.toArray(new Secure[methodAnnotations.size()])); // Add InterceptSecure annotation methodConfiguration.add(is); interceptSecureForMethods.put(method.getJavaMember(), is); } } }
private Bean<?> camelProducerBean(BeanManager manager, AnnotatedMethod<? super CdiCamelFactory> am, Set<Annotation> qualifiers) { return manager.createBean( new BeanAlternative<>(manager.createBeanAttributes(am), qualifiers), CdiCamelFactory.class, manager.getProducerFactory(am, (Bean<CdiCamelFactory>) manager.resolve(manager.getBeans(CdiCamelFactory.class)))); }
/** * @see {@link com.byteslounge.cdi.resolver.bean.AbstractResolverBean#validate(AnnotatedMethod)} */ @Override void validate(AnnotatedMethod<?> resolverMethod) { ValidationUtils.validateResolverMethod(Arrays.asList( new LocaleResolverMethodParametersVerifier(resolverMethod), new DependentResolverMethodParametersVerifier(resolverMethod))); }
/** * @see {@link com.byteslounge.cdi.resolver.bean.ResolverBean#process(AnnotatedType)} */ @Override public void process(AnnotatedType<?> at) { for (AnnotatedMethod<?> method : at.getMethods()) { if (method.isAnnotationPresent(typeToSearch)) { if (method.getJavaMember().getDeclaringClass().equals(defaulResolverClass)) { resolverMethod = method; if (logger.isDebugEnabled()) { logger.debug("Found default " + resolverDescription + "resolver method: " + MessageUtils.getMethodDefinition(method)); } } else { if (providedResolverMethod != null) { String errorMessage = "Found multiple provided " + resolverDescription + " resolver methods: " + MessageUtils.getMethodDefinition(providedResolverMethod) + ", " + MessageUtils.getMethodDefinition(method); logger.error(errorMessage); throw new ExtensionInitializationException(errorMessage); } providedResolverMethod = method; if (logger.isDebugEnabled()) { logger.debug("Found provided " + resolverDescription + "resolver method: " + MessageUtils.getMethodDefinition(providedResolverMethod)); } } } } }
/** * Observes {@link ProcessManagedBean} event. * * @param event {@link ProcessManagedBean} event. */ <X> void processBean( @Observes ProcessManagedBean<X> event) { boolean sessionBean = event instanceof ProcessSessionBean<?>; AnnotatedType<X> annotatedType = event.getAnnotatedBeanClass(); boolean hasClassInterceptor = annotatedType .isAnnotationPresent(Transactional.class); if (hasClassInterceptor && sessionBean) { event.addDefinitionError(new RuntimeException( "@Transactional is forbidden for session bean " + event.getBean())); } else { TransactionAttribute classAttr = annotatedType .getAnnotation(TransactionAttribute.class); for (AnnotatedMethod<? super X> am : annotatedType.getMethods()) { boolean hasMethodInterceptor = am .isAnnotationPresent(Transactional.class); if (hasMethodInterceptor && sessionBean) { event.addDefinitionError(new RuntimeException( "@Transactional is forbidden for session bean method " + am)); } else if (hasClassInterceptor || hasMethodInterceptor) { TransactionAttribute attr = am .getAnnotation(TransactionAttribute.class); Method method = am.getJavaMember(); TransactionAttributeType attrType = mergeTransactionAttributes(classAttr, attr); transactionAttributes.put(method, attrType); } } } }
private static void validateObserverMethods(final CdiEjbBean<?> bean, final Map<ObserverMethod<?>, AnnotatedMethod<?>> methods) { final BeanContext beanContext = bean.getBeanContext(); if (beanContext.isLocalbean()) { return; } for (final Map.Entry<ObserverMethod<?>, AnnotatedMethod<?>> m : methods.entrySet()) { final Method method = m.getValue().getJavaMember(); if (!Modifier.isStatic(method.getModifiers()) && doResolveViewMethod(bean, method) == null) { throw new WebBeansConfigurationException("@Observes " + method + " neither in the ejb view of ejb " + bean.getBeanContext().getEjbName() + " nor static"); } } }