@Test public void testMethodId() throws SecurityException, NoSuchMethodException { TestAnnotatedTypeBuilder<Chair> builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class); builder.addToMethod(Chair.class.getMethod("sit"), new ProducesLiteral()); AnnotatedType<Chair> chair3 = builder.create(); Iterator<AnnotatedMethod<? super Chair>> it = chair3.getMethods().iterator(); AnnotatedMethod<? super Chair> method = it.next(); while (!method.getJavaMember().getName().equals("sit")) method = it.next(); String id = AnnotatedTypes.createCallableId(method); Assert.assertEquals( "org.jboss.weld.tests.unit.util.Chair.sit[@javax.enterprise.inject.Produces()]()", id, "wrong id for method :" + id); builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class); chair3 = builder.create(); it = chair3.getMethods().iterator(); method = it.next(); while (!method.getJavaMember().getName().equals("sit")) method = it.next(); id = AnnotatedTypes.createCallableId(method); Assert.assertEquals( "org.jboss.weld.tests.unit.util.Chair.sit()", id, "wrong id for method :" + id); builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class); builder.addToMethod(Chair.class.getMethod("sit"), new ComfyChairLiteral()); chair3 = builder.create(); it = chair3.getMethods().iterator(); method = it.next(); while (!method.getJavaMember().getName().equals("sit")) method = it.next(); id = AnnotatedTypes.createCallableId(method); Assert.assertEquals( "org.jboss.weld.tests.unit.util.Chair.sit[@org.jboss.weld.tests.unit.util.ComfyChair(softness=1)]()", id, "wrong id for method :" + id); }
private void introspectDestroy(ArrayList<ConfigProgram> destroyList, AnnotatedType<?> type) throws ConfigException { if (type == null || type.equals(Object.class)) return; if (type.isAnnotationPresent(Interceptor.class)) { return; } for (AnnotatedMethod<?> method : type.getMethods()) { if (method.isAnnotationPresent(PreDestroy.class)) { Method javaMethod = method.getJavaMember(); Class<?>[] types = javaMethod.getParameterTypes(); if (types.length == 0) { } else if (types.length == 1 && types[0].equals(InvocationContext.class)) { // XXX: continue; } else throw new ConfigException( location(javaMethod) + L.l("@PreDestroy is requires zero arguments")); PreDestroyInject destroyProgram = new PreDestroyInject(javaMethod); if (!destroyList.contains(destroyProgram)) destroyList.add(destroyProgram); } } }
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)); } } } }
@Test public void testFieldId() throws SecurityException, NoSuchFieldException { TestAnnotatedTypeBuilder<Chair> builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class); builder.addToField(Chair.class.getField("legs"), new ProducesLiteral()); AnnotatedType<Chair> chair3 = builder.create(); AnnotatedField<? super Chair> field = chair3.getFields().iterator().next(); String id = AnnotatedTypes.createFieldId(field); Assert.assertEquals( "org.jboss.weld.tests.unit.util.Chair.legs[@javax.enterprise.inject.Produces()]", id, "wrong id for field :" + id); builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class); chair3 = builder.create(); field = chair3.getFields().iterator().next(); id = AnnotatedTypes.createFieldId(field); Assert.assertEquals( "org.jboss.weld.tests.unit.util.Chair.legs", id, "wrong id for field :" + id); builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class); builder.addToField(Chair.class.getField("legs"), new ComfyChairLiteral()); chair3 = builder.create(); field = chair3.getFields().iterator().next(); id = AnnotatedTypes.createFieldId(field); Assert.assertEquals( "org.jboss.weld.tests.unit.util.Chair.legs[@org.jboss.weld.tests.unit.util.ComfyChair(softness=1)]", id, "wrong id for field :" + id); }
protected <Z extends Annotation> Z getAnnotation( Class<Z> annotationType, AnnotatedMethod<?> apiMethod, AnnotatedType<?> apiClass, AnnotatedMethod<?> implementationMethod, AnnotatedType<?> implementationClass) { Z annotation = null; if (apiMethod != null) { annotation = apiMethod.getAnnotation(annotationType); } if (annotation == null && apiClass != null) { annotation = apiClass.getAnnotation(annotationType); } if ((annotation == null) && (implementationMethod != null)) { annotation = implementationMethod.getAnnotation(annotationType); } if ((annotation == null) && (implementationClass != null)) { annotation = implementationClass.getAnnotation(annotationType); } return annotation; }
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); } } }
@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(); }
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; }
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; }
/** * 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()); }
private void validateWsEndpointAnnotatedType(AnnotatedType<TranslatorEndpoint> annotatedType) { assertEquals(annotatedType.getBaseType(), TranslatorEndpoint.class); // translate() assertEquals(annotatedType.getMethods().size(), 1); Set<Type> typeClosure = annotatedType.getTypeClosure(); // Translator, TranslatorEndpoint, Object assertTrue( typeSetMatches(typeClosure, Translator.class, TranslatorEndpoint.class, Object.class)); }
private RequestMappingInfo findMethodRequestMapping(FacesContext context, Bean<?> bean) { RequestMappingInfo result = null; Class clazz = bean.getBeanClass(); AnnotatedType annotatedType = beanManager.createAnnotatedType(clazz); Set<AnnotatedMethod> annotatedMethodSet = annotatedType.getMethods(); for (AnnotatedMethod method : annotatedMethodSet) { if (method.isAnnotationPresent(RequestMapping.class)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); String[] mappings = requestMapping.value(); String mapping = null; for (String current : mappings) { String pathInfo = context.getExternalContext().getRequestPathInfo(); if (pathInfo.equals(current)) { result = new RequestMappingInfo(); result.setBean(bean); result.setMethod(method.getJavaMember()); result.setRequestMapping(mapping); result.setMappingType(RequestMappingInfo.MappingType.EXACT); break; } else if (current.endsWith("*")) { current = current.substring(0, current.length() - 1); if (pathInfo.startsWith(current)) { if (result == null) { result = new RequestMappingInfo(); result.setBean(bean); result.setMethod(method.getJavaMember()); result.setRequestMapping(current); result.setMappingType(RequestMappingInfo.MappingType.PREFIX); } else if (current.length() > result.getLength()) { result.setBean(bean); result.setMethod(method.getJavaMember()); result.setRequestMapping(current); result.setMappingType(RequestMappingInfo.MappingType.PREFIX); } } } else if (current.startsWith("*")) { current = current.substring(1); if (pathInfo.endsWith(current)) { result = new RequestMappingInfo(); result.setBean(bean); result.setMethod(method.getJavaMember()); result.setRequestMapping(current); result.setMappingType(RequestMappingInfo.MappingType.EXTENSION); break; } } } } if (result != null && (result.getMappingType().equals(RequestMappingInfo.MappingType.EXACT) || (result.getMappingType().equals(RequestMappingInfo.MappingType.EXTENSION)))) { break; } } return result; }
@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(); }
<T, X> void registerGenericBeanObserverMethod(@Observes ProcessObserverMethod<T, X> event) { AnnotatedType<X> declaringType = event.getAnnotatedMethod().getDeclaringType(); if (declaringType.isAnnotationPresent(GenericConfiguration.class)) { AnnotatedMethod<X> method = event.getAnnotatedMethod(); Class<? extends Annotation> genericConfigurationType = declaringType.getAnnotation(GenericConfiguration.class).value(); genericBeanObserverMethods.put( genericConfigurationType, new ObserverMethodHolder<X, T>(method, event.getObserverMethod())); } }
@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(); }
@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(); }
protected <Z extends Annotation> Z getAnnotation( Class<Z> annotationType, AnnotatedType<?> apiClass, AnnotatedType<?> implClass) { Z annotation = null; if (apiClass != null) annotation = apiClass.getAnnotation(annotationType); if ((annotation == null) && (implClass != null)) { annotation = implClass.getAnnotation(annotationType); } return annotation; }
<X> void processType(@Observes ProcessAnnotatedType<X> event) { AnnotatedType<X> original = event.getAnnotatedType(); if (original.isAnnotationPresent(ManagedBean.class) && !original.isAnnotationPresent(Named.class)) { AnnotatedType<X> modified = new AnnotatedTypeBuilder<X>() .readFromType(event.getAnnotatedType(), true) .addToClass(new NamedLiteral(original.getAnnotation(ManagedBean.class).value())) .create(); event.setAnnotatedType(modified); } }
@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(); }
<X> void registerGenericBean(@Observes ProcessManagedBean<X> event) { AnnotatedType<X> type = event.getAnnotatedBeanClass(); if (type.isAnnotationPresent(GenericConfiguration.class)) { Class<? extends Annotation> genericType = type.getAnnotation(GenericConfiguration.class).value(); genericBeans.put( genericType, new BeanHolder<X>(event.getAnnotatedBeanClass(), event.getBean())); for (AnnotatedMethod<? super X> m : event.getAnnotatedBeanClass().getMethods()) { if (m.isAnnotationPresent(Unwraps.class)) { unwrapsMethods.put(genericType, m); } } } }
<X, T> void registerGenericBeanProducerMethod(@Observes ProcessProducerMethod<X, T> event) { AnnotatedType<X> declaringType = event.getAnnotatedProducerMethod().getDeclaringType(); Annotation genericConfiguration = getGenericConfiguration(event.getAnnotated()); if (declaringType.isAnnotationPresent(GenericConfiguration.class)) { genericBeanProducerMethods.put( declaringType.getAnnotation(GenericConfiguration.class).value(), getProducerMethodHolder(event)); } else if (genericConfiguration != null) { if (validateGenericProducer( genericConfiguration, event.getBean(), event.getAnnotatedProducerMethod())) { genericProducerBeans.put(event.getAnnotatedProducerMethod(), event.getBean()); } } }
@Test @SpecAssertion(section = PAT, id = "ba") public void testGetAnnotatedType() { AnnotatedType<Dog> annotatedType = ProcessAnnotatedTypeObserver.getDogAnnotatedType(); assertEquals(annotatedType.getBaseType(), Dog.class); Set<AnnotatedMethod<? super Dog>> annotatedMethods = annotatedType.getMethods(); assertEquals(annotatedMethods.size(), 3); for (AnnotatedMethod<? super Dog> annotatedMethod : annotatedMethods) { Set<String> validMethodNames = new HashSet<String>(Arrays.asList("bite", "live", "drinkMilk")); if (!validMethodNames.contains(annotatedMethod.getJavaMember().getName())) { fail("Invalid method name found" + annotatedMethod.getJavaMember().getName()); } } }
private void introspectInjectField( AnnotatedType<X> type, ArrayList<ConfigProgram> injectProgramList) { for (AnnotatedField<?> field : type.getFields()) { if (field.getAnnotations().size() == 0) continue; if (field.isAnnotationPresent(Inject.class)) { // boolean isOptional = isQualifierOptional(field); InjectionPoint ij = new InjectionPointImpl(getBeanManager(), this, field); _injectionPointSet.add(ij); if (field.isAnnotationPresent(Delegate.class)) { // ioc/0i60 /* if (! type.isAnnotationPresent(javax.decorator.Decorator.class)) { throw new IllegalStateException(L.l("'{0}' may not inject with @Delegate because it is not a @Decorator", type.getJavaClass())); } */ } else { injectProgramList.add(new FieldInjectProgram(field.getJavaMember(), ij)); } } else { InjectionPointHandler handler = getBeanManager().getInjectionPointHandler(field); if (handler != null) { ConfigProgram program = new FieldHandlerProgram(field, handler); injectProgramList.add(program); } } } }
private void introspectInjectMethod( AnnotatedType<X> type, ArrayList<ConfigProgram> injectProgramList) { for (AnnotatedMethod method : type.getMethods()) { if (method.getAnnotations().size() == 0) continue; if (method.isAnnotationPresent(Inject.class)) { // boolean isOptional = isQualifierOptional(field); List<AnnotatedParameter<?>> params = method.getParameters(); InjectionPoint[] args = new InjectionPoint[params.size()]; for (int i = 0; i < args.length; i++) { InjectionPoint ij = new InjectionPointImpl(getBeanManager(), this, params.get(i)); _injectionPointSet.add(ij); args[i] = ij; } injectProgramList.add(new MethodInjectProgram(method.getJavaMember(), args)); } else { InjectionPointHandler handler = getBeanManager().getInjectionPointHandler(method); if (handler != null) { ConfigProgram program = new MethodHandlerProgram(method, handler); injectProgramList.add(program); } } } }
@SuppressWarnings("unchecked") private <X, A extends AnnotatedMember<? super X>> A getAnnotatedMember( Class<X> javaClass, String memberName) { AnnotatedType<X> type = getCurrentManager().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); }
@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)); } } }
<X, T> void registerGenericBeanProducerField(@Observes ProcessProducerField<X, T> event) { AnnotatedType<X> declaringType = event.getAnnotatedProducerField().getDeclaringType(); Annotation genericConfiguration = getGenericConfiguration(event.getAnnotated()); if (declaringType.isAnnotationPresent(GenericConfiguration.class)) { AnnotatedField<X> field = event.getAnnotatedProducerField(); Class<? extends Annotation> genericConfigurationType = declaringType.getAnnotation(GenericConfiguration.class).value(); genericBeanProducerFields.put( genericConfigurationType, new FieldHolder<X, T>(field, event.getBean())); } else if (genericConfiguration != null) { if (validateGenericProducer( genericConfiguration, event.getBean(), event.getAnnotatedProducerField())) { genericProducerBeans.put(event.getAnnotatedProducerField(), event.getBean()); } } }
@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(); }
@Test public void testWatchAlternatives_noGlobalAlternative() throws Exception { // prepare, no global alternative when(at.isAnnotationPresent(Priority.class)).thenReturn(false); // act subject.watchAlternatives(pat); // assert, not vetoed verify(pat, times(0)).veto(); }
/** * 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; }