/** Compares two annotated types and returns true if they are the same */ public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) { if (!t1.getJavaClass().equals(t2.getJavaClass())) { return false; } if (!compareAnnotated(t1, t2)) { return false; } if (t1.getFields().size() != t2.getFields().size()) { return false; } Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>(); for (AnnotatedField<?> f : t2.getFields()) { fields.put(f.getJavaMember(), f); } for (AnnotatedField<?> f : t1.getFields()) { if (fields.containsKey(f.getJavaMember())) { if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) { return false; } } else { return false; } } if (t1.getMethods().size() != t2.getMethods().size()) { return false; } Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>(); for (AnnotatedMethod<?> f : t2.getMethods()) { methods.put(f.getJavaMember(), f); } for (AnnotatedMethod<?> f : t1.getMethods()) { if (methods.containsKey(f.getJavaMember())) { if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) { return false; } } else { return false; } } if (t1.getConstructors().size() != t2.getConstructors().size()) { return false; } Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>(); for (AnnotatedConstructor<?> f : t2.getConstructors()) { constructors.put(f.getJavaMember(), f); } for (AnnotatedConstructor<?> f : t1.getConstructors()) { if (constructors.containsKey(f.getJavaMember())) { if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) { return false; } } else { return false; } } return true; }
private void replaceAnnotatedType(AnnotatedType<X> type) { if (!this.originalAnnotatedType.getJavaClass().equals(type.getJavaClass())) { throw BootstrapLogger.LOG.annotatedTypeJavaClassMismatch( this.annotatedType.getJavaClass(), type.getJavaClass()); } AnnotatedTypeValidator.validateAnnotatedType(type); this.annotatedType = type; }
public void registerAvailableMBeans(@Observes final AfterDeploymentValidation event) { MBeanManager manager = Beans.getReference(MBeanManager.class); JMXConfig configuration = Beans.getReference(JMXConfig.class); for (AnnotatedType<?> type : types) { final Class<?> clazz = type.getJavaClass(); DynamicMBeanProxy beanProxy = new DynamicMBeanProxy(clazz, this.mbeanContext); StringBuffer name = new StringBuffer() .append( configuration.getMbeanDomain() != null ? configuration.getMbeanDomain() : clazz.getPackage().getName()) .append(":name=") .append( configuration.getMbeanDomain() != null ? configuration.getMbeanDomain() : clazz.getSimpleName()); if (manager.findMBeanInstance(name.toString()) == null) { ObjectInstance instance = MBeanHelper.register(beanProxy, name.toString()); manager.storeRegisteredMBean(instance); } } }
private void introspectInjectClass( AnnotatedType<X> type, ArrayList<ConfigProgram> injectProgramList) { InjectManager cdiManager = getBeanManager(); for (Annotation ann : type.getAnnotations()) { Class<? extends Annotation> annType = ann.annotationType(); InjectionPointHandler handler = cdiManager.getInjectionPointHandler(annType); if (handler != null) { injectProgramList.add(new ClassHandlerProgram(ann, handler)); } } // ioc/123i for (Class<?> parentClass = type.getJavaClass().getSuperclass(); parentClass != null; parentClass = parentClass.getSuperclass()) { for (Annotation ann : parentClass.getAnnotations()) { Class<? extends Annotation> annType = ann.annotationType(); InjectionPointHandler handler = cdiManager.getInjectionPointHandler(annType); if (handler != null) { injectProgramList.add(new ClassHandlerProgram(ann, handler)); } } } }
private <X> boolean validateGenericProducer( Annotation genericConfiguration, Bean<?> bean, AnnotatedMember<X> member) { Class<?> configType = genericConfiguration.annotationType().getAnnotation(GenericType.class).value(); boolean valid = false; for (Type type : bean.getTypes()) { if (type instanceof Class<?>) { Class<?> clazz = (Class<?>) type; if (configType.isAssignableFrom(clazz)) { valid = true; break; } } } if (!valid) { AnnotatedType<X> declaringType = member.getDeclaringType(); errors.add( "Generic producer method is not of correct type. Producer: " + declaringType.getJavaClass().getName() + "." + member.getJavaMember().getName() + ". Expected producer to be of type " + configType + " but was actually " + member.getBaseType()); } return valid; }
@Override public ConfigProgram introspectType(AnnotatedType<?> type) { for (Class<?> parentClass = type.getJavaClass().getSuperclass(); parentClass != null; parentClass = parentClass.getSuperclass()) { Resources resources = parentClass.getAnnotation(Resources.class); if (resources != null) { for (Resource resource : resources.value()) { introspectClass(getClass().getName(), resource); } } Resource resource = parentClass.getAnnotation(Resource.class); if (resource != null) introspectClass(getClass().getName(), resource); } Resources resources = type.getAnnotation(Resources.class); if (resources != null) { for (Resource resource : resources.value()) { introspectClass(getClass().getName(), resource); } } Resource resource = type.getAnnotation(Resource.class); if (resource != null) introspectClass(getClass().getName(), resource); return new NullProgram(); }
@Override public void run() { if (System.currentTimeMillis() > expiryTime) { scheduledExecutorService.shutdown(); throw new RuntimeException( "failed to discover beans: " + managedTypes.getServiceEndpoints()); } if (registered.isEmpty()) { scheduledExecutorService.shutdown(); log.info("all services registered successfully"); return; } for (final AnnotatedType<?> type : managedTypes.getServiceEndpoints()) { if (!registered.contains(type) || beanManager.getBeans(type.getJavaClass()).size() == 0) { continue; } final MessageCallback callback = (MessageCallback) CDIServerUtil.lookupBean(beanManager, type.getJavaClass()); registered.remove(type); // Discriminate on @Command final Map<String, Method> commandPoints = new HashMap<String, Method>(); for (final AnnotatedMethod method : type.getMethods()) { if (method.isAnnotationPresent(Command.class)) { final Command command = method.getAnnotation(Command.class); for (String cmdName : command.value()) { if (cmdName.equals("")) cmdName = method.getJavaMember().getName(); commandPoints.put(cmdName, method.getJavaMember()); } } } final String subjectName = CDIServerUtil.resolveServiceName(type.getJavaClass()); if (commandPoints.isEmpty()) { bus.subscribe(subjectName, callback); } else { bus.subscribeLocal( subjectName, new CommandBindingsCallback(commandPoints, callback, bus)); } } }
/** * Generates a unique signature for an annotated type. Members without annotations are omitted to * reduce the length of the signature * * @param <X> * @param annotatedType * @return */ public static <X> String createTypeId(AnnotatedType<X> annotatedType) { return createTypeId( annotatedType.getJavaClass(), annotatedType.getAnnotations(), annotatedType.getMethods(), annotatedType.getFields(), annotatedType.getConstructors()); }
/** * Read the {@link AnnotatedType}, creating a bean from the class and it's annotations. * * <p> * * <p>By default the bean lifecycle will wrap the result of calling {@link * BeanManager#createInjectionTarget(AnnotatedType)}. * * <p> * * <p>{@link BeanBuilder} does <em>not</em> support reading members of the class to create * producers or observer methods. * * @param type the type to read */ public BeanBuilder<T> readFromType(AnnotatedType<T> type) { this.beanClass = type.getJavaClass(); InjectionTarget<T> injectionTarget; if (!type.getJavaClass().isInterface()) { injectionTarget = beanManager.createInjectionTarget(type); } else { injectionTarget = new DummyInjectionTarget<T>(); } this.beanLifecycle = new DelegatingContextualLifecycle<T>(injectionTarget); this.injectionPoints = injectionTarget.getInjectionPoints(); this.qualifiers = new HashSet<Annotation>(); this.stereotypes = new HashSet<Class<? extends Annotation>>(); this.types = new HashSet<Type>(); for (Annotation annotation : type.getAnnotations()) { if (beanManager.isQualifier(annotation.annotationType())) { this.qualifiers.add(annotation); } else if (beanManager.isScope(annotation.annotationType())) { this.scope = annotation.annotationType(); } else if (beanManager.isStereotype(annotation.annotationType())) { this.stereotypes.add(annotation.annotationType()); } if (annotation instanceof Named) { this.name = ((Named) annotation).value(); } if (annotation instanceof Alternative) { this.alternative = true; } } if (this.scope == null) { this.scope = Dependent.class; } for (Class<?> c = type.getJavaClass(); c != Object.class && c != null; c = c.getSuperclass()) { this.types.add(c); } for (Class<?> i : type.getJavaClass().getInterfaces()) { this.types.add(i); } if (qualifiers.isEmpty()) { qualifiers.add(new DefaultLiteral()); } qualifiers.add(new AnyLiteral()); this.id = ImmutableBeanWrapper.class.getName() + ":" + Annotateds.createTypeId(type); return this; }
private <T> Set<AnnotatedCallable<? super T>> determineConstrainedCallables( AnnotatedType<T> type) { Set<AnnotatedCallable<? super T>> callables = newHashSet(); BeanDescriptor beanDescriptor = validator.getConstraintsForClass(type.getJavaClass()); determineConstrainedConstructors(type, beanDescriptor, callables); determineConstrainedMethods(type, beanDescriptor, callables); return callables; }
@Test public void testWatchAlternatives_disabledAlternativeClass() throws Exception { // prepare, global alternative when(at.isAnnotationPresent(Priority.class)).thenReturn(true); when(at.getJavaClass()).thenReturn(DisabledAlternativeClass.class); // act subject.watchAlternatives(pat); // assert, vetoed verify(pat).veto(); }
@Test public void testWatchAlternatives_unstereotypedField_veto() throws Exception { // prepare, global alternative when(at.isAnnotationPresent(Priority.class)).thenReturn(true); when(at.isAnnotationPresent(TestStereotype.class)).thenReturn(false); when(at.getJavaClass()).thenReturn(UnstereotypedField.class); // act subject.watchAlternatives(pat); // assert, vetoed verify(pat).veto(); }
@Test public void testWatchAlternatives_stereotypedClass_enable() throws Exception { // prepare, global alternative when(at.isAnnotationPresent(Priority.class)).thenReturn(true); when(at.isAnnotationPresent(TestStereotype.class)).thenReturn(true); when(at.getJavaClass()).thenReturn(StereotypedClass.class); // act subject.watchAlternatives(pat); // assert, not vetoed verify(pat, times(0)).veto(); }
public static <X> UnbackedAnnotatedType<X> additionalAnnotatedType( String contextId, AnnotatedType<X> source, String bdaId, String suffix, SharedObjectCache cache) { return new UnbackedAnnotatedType<X>( source, AnnotatedTypeIdentifier.of( contextId, bdaId, source.getJavaClass().getName(), suffix, false), cache); }
@Test public void testWatchAlternatives_stereotypedField_enable() throws Exception { // prepare, global alternative when(at.isAnnotationPresent(Priority.class)).thenReturn(true); final Set<Annotated> annotated = asAnnotatedSet(StereotypedField.class.getDeclaredFields()); when(at.getFields()).thenReturn(annotated); when(at.getJavaClass()).thenReturn(StereotypedField.class); // act subject.watchAlternatives(pat); // assert, not vetoed verify(pat, times(0)).veto(); }
@Override public ConfigProgram introspectType(AnnotatedType<?> type) { PersistenceContext pContext = type.getAnnotation(PersistenceContext.class); String location = type.getJavaClass().getName() + ": "; String jndiName = null; if (!"".equals(pContext.name())) jndiName = pContext.name(); Bean<?> bean = bindEntityManager(location, pContext); BeanValueGenerator gen = new BeanValueGenerator(location, bean); if (jndiName != null) bindJndi(jndiName, gen, null); return new NullProgram(); }
private <T> void determineConstrainedMethods( AnnotatedType<T> type, BeanDescriptor beanDescriptor, Set<AnnotatedCallable<? super T>> callables) { List<Method> overriddenAndImplementedMethods = InheritedMethodsHelper.getAllMethods(type.getJavaClass()); for (AnnotatedMethod<? super T> annotatedMethod : type.getMethods()) { Method method = annotatedMethod.getJavaMember(); boolean isGetter = ReflectionHelper.isGetterMethod(method); // obtain @ValidateOnExecution from the top-most method in the hierarchy Method methodForExecutableTypeRetrieval = replaceWithOverriddenOrInterfaceMethod(method, overriddenAndImplementedMethods); EnumSet<ExecutableType> classLevelExecutableTypes = executableTypesDefinedOnType(methodForExecutableTypeRetrieval.getDeclaringClass()); EnumSet<ExecutableType> memberLevelExecutableType = executableTypesDefinedOnMethod(methodForExecutableTypeRetrieval, isGetter); ExecutableType currentExecutableType = isGetter ? ExecutableType.GETTER_METHODS : ExecutableType.NON_GETTER_METHODS; // validation is enabled per default, so explicit configuration can just veto whether // validation occurs if (veto(classLevelExecutableTypes, memberLevelExecutableType, currentExecutableType)) { continue; } boolean needsValidation; if (isGetter) { needsValidation = isGetterConstrained(method, beanDescriptor); } else { needsValidation = isNonGetterConstrained(method, beanDescriptor); } if (needsValidation) { callables.add(annotatedMethod); } } }
private <T> void determineConstrainedConstructors( AnnotatedType<T> type, BeanDescriptor beanDescriptor, Set<AnnotatedCallable<? super T>> callables) { Class<?> clazz = type.getJavaClass(); EnumSet<ExecutableType> classLevelExecutableTypes = executableTypesDefinedOnType(clazz); for (AnnotatedConstructor<T> annotatedConstructor : type.getConstructors()) { Constructor<?> constructor = annotatedConstructor.getJavaMember(); EnumSet<ExecutableType> memberLevelExecutableType = executableTypesDefinedOnConstructor(constructor); if (veto(classLevelExecutableTypes, memberLevelExecutableType, ExecutableType.CONSTRUCTORS)) { continue; } if (beanDescriptor.getConstraintsForConstructor(constructor.getParameterTypes()) != null) { callables.add(annotatedConstructor); } } }
private UnbackedAnnotatedType( AnnotatedType<X> source, AnnotatedTypeIdentifier identifier, SharedObjectCache cache) { super(source.getBaseType(), source.getTypeClosure(), source.getAnnotations()); this.javaClass = source.getJavaClass(); ImmutableSet.Builder<AnnotatedConstructor<X>> constructors = ImmutableSet.builder(); for (AnnotatedConstructor<X> constructor : source.getConstructors()) { constructors.add(UnbackedAnnotatedConstructor.of(constructor, this, cache)); } this.constructors = constructors.build(); ImmutableSet.Builder<AnnotatedMethod<? super X>> methods = ImmutableSet.builder(); for (AnnotatedMethod<? super X> originalMethod : source.getMethods()) { methods.add(UnbackedAnnotatedMethod.of(originalMethod, this, cache)); } this.methods = methods.build(); ImmutableSet.Builder<AnnotatedField<? super X>> fields = ImmutableSet.builder(); for (AnnotatedField<? super X> originalField : source.getFields()) { fields.add(UnbackedAnnotatedField.of(originalField, this, cache)); } this.fields = fields.build(); this.identifier = identifier; }
<T> void processAnnotatedType(@Observes ProcessAnnotatedType<T> pat) { AnnotatedType<T> annotatedType = pat.getAnnotatedType(); Class<T> type = annotatedType.getJavaClass(); // Determine if bean should be processed boolean veto = !context.filter.filter(type); if (!veto) { for (AbstractBean boundBean : context.injector.boundBeans) { Class<?> beanType = boundBean.getBeanClass(); if (beanType.isAssignableFrom(type)) { veto = true; break; } } } // if (veto) { pat.veto(); } }
/** Introspects the constructor */ private void introspectConstructor(AnnotatedType<X> beanType) { if (_beanCtor != null) return; // XXX: may need to modify BeanFactory if (beanType.getJavaClass().isInterface()) return; try { /* Class cl = getInstanceClass(); if (cl == null) cl = getTargetClass(); */ AnnotatedConstructor<X> best = null; AnnotatedConstructor<X> second = null; for (AnnotatedConstructor<X> ctor : beanType.getConstructors()) { if (_newArgs != null && ctor.getParameters().size() != _newArgs.length) { continue; } else if (best == null) { best = ctor; } else if (ctor.isAnnotationPresent(Inject.class)) { if (best != null && best.isAnnotationPresent(Inject.class)) throw new ConfigException( L.l( "'{0}' can't have two constructors marked by @Inject or by a @Qualifier, because the Java Injection BeanManager can't tell which one to use.", beanType.getJavaClass().getName())); best = ctor; second = null; } else if (best.isAnnotationPresent(Inject.class)) { } else if (ctor.getParameters().size() == 0) { best = ctor; } else if (best.getParameters().size() == 0) { } else if (ctor.getParameters().size() == 1 && ctor.getParameters().get(0).equals(String.class)) { second = best; best = ctor; } } if (best == null) { // ioc/0q00 best = new AnnotatedConstructorImpl( beanType, beanType.getJavaClass().getConstructor(new Class[0])); } if (best == null) { throw new ConfigException( L.l( "{0}: no constructor found while introspecting bean for Java Injection", beanType.getJavaClass().getName())); } if (second == null) { } else if (beanType.getJavaClass().getName().startsWith("java.lang") && best.getParameters().size() == 1 && best.getParameters().get(0).equals(String.class)) { log.fine( L.l( "{0}: WebBean does not have a unique constructor, choosing String-arg constructor", beanType.getJavaClass().getName())); } else throw new ConfigException( L.l( "{0}: Bean does not have a unique constructor. One constructor must be marked with @Inject or have a qualifier annotation.", beanType.getJavaClass().getName())); _beanCtor = best; _javaCtor = _beanCtor.getJavaMember(); _javaCtor.setAccessible(true); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw ConfigException.create(e); } }
<X> void replaceInjectOnGenericBeans(@Observes ProcessAnnotatedType<X> event) { AnnotatedType<X> type = event.getAnnotatedType(); if (type.isAnnotationPresent(GenericConfiguration.class)) { final Class<? extends Annotation> genericConfigurationType = type.getAnnotation(GenericConfiguration.class).value(); // validate that the configuration type is annotated correctly if (!genericConfigurationType.isAnnotationPresent(GenericType.class)) { errors.add( "Bean " + type.getJavaClass().getName() + " specifies generic annotation " + type.getAnnotation(GenericConfiguration.class) + " however " + genericConfigurationType + " is not annotated @GenericConfiguration."); } else { Class<?> configType = genericConfigurationType.getAnnotation(GenericType.class).value(); if (configType.isAnnotationPresent(GenericConfiguration.class)) { errors.add( "Generic configuration type " + genericConfigurationType + " specifies a value() of " + configType + " however " + configType + " is a generic bean. Generic configuration types may not be generic beans"); } } final AnnotatedTypeBuilder<X> builder = new AnnotatedTypeBuilder<X>().readFromType(type); builder.addToClass(genericBeanQualifier); builder.redefine( Inject.class, new AnnotationRedefiner<Inject>() { public void redefine(RedefinitionContext<Inject> ctx) { if (ctx.getAnnotatedElement() instanceof Field) { if (ctx.getAnnotatedElement().isAnnotationPresent(Generic.class)) { // This is a Generic bean injection point ctx.getAnnotationBuilder() .remove(Inject.class) .add(InjectGenericLiteral.INSTANCE); } } } }); builder.redefine( Produces.class, new AnnotationRedefiner<Produces>() { public void redefine(RedefinitionContext<Produces> ctx) { // Add the marker qualifier ctx.getAnnotationBuilder() .add(GenericMarkerLiteral.INSTANCE) .add(genericBeanQualifier); } }); builder.redefine( Disposes.class, new AnnotationRedefiner<Disposes>() { public void redefine(RedefinitionContext<Disposes> ctx) { // Add the marker qualifier ctx.getAnnotationBuilder() .add(GenericMarkerLiteral.INSTANCE) .add(genericBeanQualifier); } }); builder.redefine( Generic.class, new AnnotationRedefiner<Generic>() { public void redefine(RedefinitionContext<Generic> ctx) { // if it is a parameter annotation if (!(ctx.getAnnotatedElement() instanceof AccessibleObject)) { // stick an InjectGeneric as a marker. ctx.getAnnotationBuilder().remove(Generic.class).add(InjectGenericLiteral.INSTANCE); if (ctx.getRawType().isAnnotationPresent(GenericConfiguration.class)) { ctx.getAnnotationBuilder().add(genericBeanQualifier); } } } }); event.setAnnotatedType(builder.create()); } }
/** * Register managed beans as Errai services * * @param event - * @param <T> - */ @SuppressWarnings("UnusedDeclaration") public <T> void observeResources(@Observes final ProcessAnnotatedType<T> event) { final AnnotatedType<T> type = event.getAnnotatedType(); for (final Annotation a : type.getJavaClass().getAnnotations()) { if (a.annotationType().isAnnotationPresent(Qualifier.class)) { beanQualifiers.put(a.annotationType().getName(), a); } } // services if (type.isAnnotationPresent(Service.class)) { log.debug("discovered Errai annotation on type: " + type); boolean isRpc = false; final Class<T> javaClass = type.getJavaClass(); for (final Class<?> intf : javaClass.getInterfaces()) { isRpc = intf.isAnnotationPresent(Remote.class); if (isRpc) { if (!managedTypes.getRemoteInterfaces().contains(intf)) { managedTypes.addRemoteInterface(intf); } } } if (!isRpc) { managedTypes.addServiceEndpoint(type); } } else { for (final AnnotatedMethod method : type.getMethods()) { if (method.isAnnotationPresent(Service.class)) { managedTypes.addServiceMethod(type, method); } } } // veto on client side implementations that contain CDI annotations // (i.e. @Observes) Otherwise Weld might try to invoke on them if (vetoClasses.contains(type.getJavaClass().getName()) || (type.getJavaClass().getPackage().getName().contains("client") && !type.getJavaClass().isInterface())) { event.veto(); } /** We must scan for Event consumer injection points to build the tables */ final Class clazz = type.getJavaClass(); for (final Field f : clazz.getDeclaredFields()) { if (f.isAnnotationPresent(Inject.class) && f.isAnnotationPresent(ObserverModel.class)) { processEventInjector(f.getType(), f.getGenericType(), f.getAnnotations()); } } for (final Method m : clazz.getDeclaredMethods()) { if (m.isAnnotationPresent(Inject.class) && m.isAnnotationPresent(ObserverModel.class)) { final Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) { final Class<?> parmType = parameterTypes[i]; processEventInjector( parmType, m.getGenericParameterTypes()[i], m.getParameterAnnotations()[i]); } } } for (final Constructor c : clazz.getDeclaredConstructors()) { if (c.isAnnotationPresent(Inject.class) && c.isAnnotationPresent(ObserverModel.class)) { final Class<?>[] parameterTypes = c.getParameterTypes(); for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) { final Class<?> parmType = parameterTypes[i]; processEventInjector( parmType, c.getGenericParameterTypes()[i], c.getParameterAnnotations()[i]); } } } }