@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); }
/** 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 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; }
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; }
@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 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); } } } }
@Override public ConfigProgram introspectMethod(AnnotatedMethod<?> method) { PersistenceContext pContext = method.getAnnotation(PersistenceContext.class); Method javaMethod = method.getJavaMember(); String location = getLocation(javaMethod); Class<?> param = javaMethod.getParameterTypes()[0]; if (!param.isAssignableFrom(EntityManager.class)) { throw new ConfigException( L.l( "{0}: @PersistenceContext method must be assignable from EntityManager.", getLocation(javaMethod))); } BeanValueGenerator gen; /* if (PersistenceContextType.EXTENDED.equals(type)) return generateExtendedContext(field, pContext); else */ gen = generateTransactionContext(location, pContext); return new MethodGeneratorProgram(javaMethod, gen); }
/** Send the event notification. */ public void notify(T event) { Object instance = getInstance(); if (instance == null) return; Method method = _method.getJavaMember(); try { method.invoke(instance, getEventArguments(event)); } catch (IllegalArgumentException e) { String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": "); throw new InjectionException(loc + e.getMessage(), e.getCause()); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": "); throw new InjectionException(loc + e.getMessage(), e.getCause()); } catch (Exception e) { String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": "); throw new InjectionException(loc + e.getMessage(), e.getCause()); } }
public boolean isInjectionPoint() { for (Class<?> paramType : _producesMethod.getJavaMember().getParameterTypes()) { if (InjectionPoint.class.equals(paramType)) return true; } return false; }
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); } } }
@Override protected String getDefaultName() { String methodName = _producesMethod.getJavaMember().getName(); if (methodName.startsWith("get") && methodName.length() > 3) { return (Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4)); } else return methodName; }
@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)); } } }
@Override public ConfigProgram introspectMethod(AnnotatedMethod<?> method) { Resource resource = method.getAnnotation(Resource.class); Method javaMethod = method.getJavaMember(); String loc = getLocation(method.getJavaMember()); String jndiName = (javaMethod.getDeclaringClass().getName() + "/" + javaMethod.getName()); Class<?> bindType = javaMethod.getParameterTypes()[0]; ValueGenerator gen = generateContext(loc, bindType, jndiName, resource); bindJndi(javaMethod, gen); return new MethodGeneratorProgram(method.getJavaMember(), gen); }
private void subscribeServices(final BeanManager beanManager, final MessageBus bus) { for (final Map.Entry<AnnotatedType, List<AnnotatedMethod>> entry : managedTypes.getServiceMethods().entrySet()) { final Class<?> type = entry.getKey().getJavaClass(); for (final AnnotatedMethod method : entry.getValue()) { final Service svc = method.getAnnotation(Service.class); final String svcName = svc.value().equals("") ? method.getJavaMember().getName() : svc.value(); final Method callMethod = method.getJavaMember(); bus.subscribe( svcName, new MessageCallback() { @Override public void callback(final Message message) { final Object targetBean = CDIServerUtil.lookupBean(beanManager, type); try { callMethod.invoke(targetBean, message); } catch (Exception e) { ErrorHelper.sendClientError(bus, message, "Error dispatching service", e); } } }); } } /** * Due to the lack of contract in CDI guaranteeing when beans will be available, we use an * executor to search for the beans every 100ms until it finds them. Or, after a 25 seconds, * blow up if they don't become available. */ final ScheduledExecutorService startupScheduler = Executors.newScheduledThreadPool(1); startupScheduler.scheduleAtFixedRate( new StartupCallback(beanManager, bus, startupScheduler, 25), 0, 100, TimeUnit.MILLISECONDS); for (final Class<?> remoteInterfaceType : managedTypes.getRemoteInterfaces()) { createRPCScaffolding(remoteInterfaceType, bus, beanManager); } }
ObserverMethodImpl( InjectManager beanManager, Bean<X> bean, AnnotatedMethod<X> method, Type type, Set<Annotation> qualifiers) { _beanManager = beanManager; _bean = bean; _method = method; _method.getJavaMember().setAccessible(true); _type = type; _qualifiers = qualifiers; introspect(); }
@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); }
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); } } }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append("["); Method method = _producesMethod.getJavaMember(); sb.append(getTargetSimpleName()); sb.append(", "); sb.append(method.getDeclaringClass().getSimpleName()); sb.append("."); sb.append(method.getName()); sb.append("()"); sb.append(", {"); boolean isFirst = true; for (Annotation ann : getQualifiers()) { if (!isFirst) sb.append(", "); sb.append(ann); isFirst = false; } sb.append("}"); if (getName() != null) { sb.append(", name="); sb.append(getName()); } sb.append("]"); return sb.toString(); }
public static void introspectInit(ArrayList<ConfigProgram> initList, AnnotatedType<?> type) throws ConfigException { for (AnnotatedMethod<?> annMethod : type.getMethods()) { Method method = annMethod.getJavaMember(); if (!annMethod.isAnnotationPresent(PostConstruct.class)) { // && ! isAnnotationPresent(annList, Inject.class)) { continue; } if (method.getParameterTypes().length == 1 && InvocationContext.class.equals(method.getParameterTypes()[0])) continue; if (method.isAnnotationPresent(PostConstruct.class) && method.getParameterTypes().length != 0) { throw new ConfigException( location(method) + L.l("{0}: @PostConstruct is requires zero arguments")); } PostConstructProgram initProgram = new PostConstructProgram(method); if (!initList.contains(initProgram)) initList.add(initProgram); } }
private ProducesMethodBean( InjectManager manager, Bean<X> producerBean, AnnotatedMethod<? super X> producesMethod, Arg<?>[] producesArgs, AnnotatedMethod<? super X> disposesMethod, Arg<?>[] disposesArgs) { super(manager, producesMethod.getBaseType(), producesMethod); _producerBean = producerBean; _producesMethod = producesMethod; _producesArgs = producesArgs; if (producesMethod == null) throw new NullPointerException(); if (producesArgs == null) throw new NullPointerException(); producesMethod.getJavaMember().setAccessible(true); if (disposesMethod != null) { _disposesProducer = new DisposesProducer<T, X>( manager, producerBean, disposesMethod, disposesArgs); for (AnnotatedParameter<? super X> param : disposesMethod.getParameters()) { if (param.isAnnotationPresent(Disposes.class)) _disposedParam = param; } } introspectInjectionPoints(); _methodProducer = new MethodProducer(); _producer = _methodProducer; Method javaMethod = producesMethod.getJavaMember(); int modifiers = javaMethod.getModifiers(); if (producesMethod.isAnnotationPresent(Specializes.class)) { if (Modifier.isStatic(modifiers)) { throw new ConfigException( L.l( "{0}.{1} is an invalid @Specializes @Producer because the method is static.", javaMethod.getDeclaringClass().getName(), javaMethod.getName())); } Method parentMethod = getSpecializedMethod(javaMethod); if (parentMethod == null) { throw new ConfigException( L.l( "{0}.{1} is an invalid @Specializes @Producer because it does not directly specialize a parent method", javaMethod.getDeclaringClass().getName(), javaMethod.getName())); } if (producesMethod.getJavaMember().isAnnotationPresent(Named.class) && parentMethod.isAnnotationPresent(Named.class)) { throw new ConfigException( L.l( "{0}.{1} is an invalid @Specializes @Producer because both it and its parent defines @Named", javaMethod.getDeclaringClass().getName(), javaMethod.getName())); } for (Annotation ann : parentMethod.getAnnotations()) { if (ann.annotationType().isAnnotationPresent(Qualifier.class)) { // ioc/07a5 if (producesMethod instanceof AnnotatedElementImpl) { ((AnnotatedElementImpl) producesMethod).addAnnotation(ann); } } } } }
void registerSecuredMethods() { for (AnnotatedMethod<?> method : securedMethods) { registerSecuredMethod(method.getDeclaringType().getJavaClass(), method.getJavaMember()); } }
/** Returns the JavaMethod for this aspect. */ protected Method getJavaMethod() { return _method.getJavaMember(); }