private Consumer<Object> createInvocableSetter(Method method, DependencyResolver resolver) { // gather qualifiers on setter List<Annotation> qualifiers = Arrays.asList(method.getAnnotations()).stream() .filter(a -> a.annotationType().getAnnotation(Qualifier.class) != null) .collect(Collectors.toList()); // determine property/setter type List<Type> parameterTypes = Arrays.asList(method.getGenericParameterTypes()); if (parameterTypes.isEmpty() || parameterTypes.size() > 1) throw new RuntimeException("method [" + method.getName() + "], annotated " + "with @Inject does NOT take exactly 1 parameter; it takes " + parameterTypes.size()); Type propertyType = parameterTypes.get(0); return instance -> setterInvocation(method, resolver, instance, propertyType, qualifiers); }
/** * Create the InjectSignature for a specific Method parameter. */ private InjectSignature createInjectSignature(Method method, int parameterIndex) { Class<?> parameterClass = method.getParameterTypes()[parameterIndex]; Annotation[] annotations = method.getParameterAnnotations()[parameterIndex]; Nullability nullability = Nullability.create(annotations); Class<?> targetType = (parameterClass == Provider.class) ? (Class<?>) ((ParameterizedType) method.getGenericParameterTypes()[parameterIndex]).getActualTypeArguments()[0] : parameterClass; Annotation qualifierAnnotation = Annotations.findAnnotationAnnotatedWith(Qualifier.class, annotations); String qualifier = qualifierAnnotation != null ? qualifierCache.getQualifier(qualifierAnnotation) : null; return new InjectSignature(targetType, nullability, qualifier); }
/** * Collect the ObjectGraphNode instances for a specific module. */ private static void collectObjectGraphNodes(ReflectionCache reflectionCache, List<ObjectGraphNode> objectGraphNodes, Object module) { for (Method method : module.getClass().getDeclaredMethods()) { // find a matching method if (!method.isAnnotationPresent(Provides.class)) { continue; } if (!Modifier.isPublic(method.getModifiers())) { throw new SporkRuntimeException("Module method is not public: " + method.toString()); } // getQualifier key Nullability nullability = Nullability.create(method); Annotation qualifierAnnotation = Annotations.findAnnotationAnnotatedWith(Qualifier.class, method); String qualifier = qualifierAnnotation != null ? reflectionCache.getQualifier(qualifierAnnotation) : null; InjectSignature injectSignature = new InjectSignature(method.getReturnType(), nullability, qualifier); objectGraphNodes.add(new ObjectGraphNode(injectSignature, module, method)); } }
@Test public void testAutowiredFieldDoesNotResolveWithBaseQualifierAndNonDefaultValueAndMultipleMatchingCandidates() { GenericApplicationContext context = new GenericApplicationContext(); ConstructorArgumentValues cavs1 = new ConstructorArgumentValues(); cavs1.addGenericArgumentValue("the real juergen"); RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null); person1.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen")); ConstructorArgumentValues cavs2 = new ConstructorArgumentValues(); cavs2.addGenericArgumentValue("juergen imposter"); RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null); person2.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen")); context.registerBeanDefinition("juergen1", person1); context.registerBeanDefinition("juergen2", person2); context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); try { context.refresh(); fail("expected BeanCreationException"); } catch (BeanCreationException e) { assertTrue(e instanceof UnsatisfiedDependencyException); assertEquals("autowired", e.getBeanName()); } }
private boolean isProduces(Method m) { Annotation []anns = m.getAnnotations(); if (anns == null) { return false; } for (Annotation ann : anns) { if (ann.annotationType().isAnnotationPresent(Qualifier.class)) { return true; } } return false; }
private void qualify(final Bind<?> bind) { if(Objects.isNull(bind.to())){ return; } if (bind.to().isAnnotationPresent(Named.class)) { bind.name(bind.to().getAnnotation(Named.class).value()); return; } Arrays.asList(bind.to().getAnnotations()).stream().forEach(a -> { // With qualifier qualify with module name if (a.annotationType().isAnnotationPresent(Qualifier.class)) { bind.name(a.annotationType().getSimpleName()); } }); }
public String getQualifier(AnnotatedElement field) { String name = StringUtils.EMPTY; if (field.isAnnotationPresent(Named.class)) { name = field.getAnnotation(Named.class).value(); } else { for (Annotation a : field.getAnnotations()) { if (a.annotationType().isAnnotationPresent(Qualifier.class)) { name = a.annotationType().getSimpleName(); } } } return name; }
private static boolean isPartOfPU(ClassNode classNode, Class<? extends Annotation> qualifier, ClassLoader classLoader) { boolean anyQualifierFound = false; boolean requiredPUAnnotationFound = false; for (AnnotationNode annotation : classNode.visibleAnnotations) { Class<?> annotationClass = AsmUtil.loadClass(Type.getType(annotation.desc), classLoader); anyQualifierFound |= annotationClass.isAnnotationPresent(Qualifier.class); requiredPUAnnotationFound |= AnyUnit.class.equals(annotationClass); if (qualifier == null) { requiredPUAnnotationFound |= NullUnit.class.equals(annotationClass); } else { requiredPUAnnotationFound |= qualifier.equals(annotationClass); } } return requiredPUAnnotationFound || (qualifier == null && !anyQualifierFound); }
/** * Unregister component where methods annotated by {@link Provides} will be registered as * injection providers. * * @param providerHolder The object with methods marked by {@link Provides} to provide injectable * instances * @return this instance * * @throws ProviderMissingException Thrown when the any provider in the provider holder with * the given type and qualifier cannot be found under this component */ public Component unregister(Object providerHolder) throws ProviderMissingException { Method[] methods = providerHolder.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Provides.class)) { Class<?> returnType = method.getReturnType(); if (returnType != void.class) { Annotation qualifier = null; Annotation[] annotations = method.getAnnotations(); for (Annotation a : annotations) { if (a.annotationType().isAnnotationPresent(Qualifier.class)) { qualifier = a; break; } } unregister(returnType, qualifier); } } } return this; }
private void registerProvides(final Object providerHolder, final Method method) throws ProvideException, ProviderConflictException { Class<?> returnType = method.getReturnType(); if (returnType == void.class) { throw new ProvideException(String.format("Provides method %s must not return void.", method.getName())); } else { Annotation[] annotations = method.getAnnotations(); Annotation qualifier = null; for (Annotation a : annotations) { Class<? extends Annotation> annotationType = a.annotationType(); if (annotationType.isAnnotationPresent(Qualifier.class)) { if (qualifier != null) { throw new ProvideException("Only one Qualifier is supported for Provide method. " + String.format("Found multiple qualifier %s and %s for method %s", qualifier.getClass().getName(), a.getClass().getName(), method.getName())); } qualifier = a; } } Provider provider = new MethodProvider(returnType, qualifier, scopeCache, providerHolder, method); register(provider); } }
/** * Returns list of all annotations given <code>element</code> has. * * @param element Element. */ public List<AnnotationSpec> getQualifiers(Element element) { List<AnnotationSpec> list = new ArrayList<>(); for (AnnotationMirror a : element.getAnnotationMirrors()) { if (a.getAnnotationType().asElement().getAnnotation(Qualifier.class) == null) { continue; // ignore non-Qualifier annotations } ClassName annotationClassName = (ClassName) ClassName.get(a.getAnnotationType()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(annotationClassName); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : a.getElementValues().entrySet()) { String format = (entry.getValue().getValue() instanceof String) ? "$S" : "$L"; annotation.addMember(entry.getKey().getSimpleName().toString(), format, entry.getValue().getValue()); } list.add(annotation.build()); } return list; }
public DocumentedAnnotations(Element element) { List<AnnotationMirror> allAnnotations = new ArrayList<AnnotationMirror>(); allAnnotations.addAll(annotationsOf(element, Qualifier.class)); allAnnotations.addAll(annotationsOf(element, Scope.class)); if (allAnnotations.isEmpty()) { this.description = Optional.absent(); return; } StringBuilder result = new StringBuilder(); for (AnnotationMirror annotation : allAnnotations) { if (result.length() > 0) { result.append(" "); } result.append(annotation.toString()); } this.description = Optional.of(result.toString()); }
protected Object getDependency(Class<?> type, Type genericType, Annotation[] annotations) { List<Annotation> qualifiers = Arrays.stream(annotations) .filter(a -> a.annotationType().isAnnotationPresent(Qualifier.class)) .collect(Collectors.toList()); Annotation qualifier = null; if (qualifiers.isEmpty() == false) { if (qualifiers.size() > 1) { throw new IllegalArgumentException(); } qualifier = qualifiers.get(0); } Object dependency; if (type == Provider.class) { ParameterizedType pt = (ParameterizedType) genericType; Class<?> type2 = (Class<?>) pt.getActualTypeArguments()[0]; dependency = container.getProvider(type2, qualifier); } else { dependency = container.getInstance(type, qualifier); } return dependency; }
protected List<Annotation> harvestQualifiers(Class<?> klass) { List<Annotation> list = new ArrayList<>(); Annotation[] annotations = klass.getAnnotations(); for (Annotation annotation : annotations) { if (AnnotationUtils.isAnnotatedWith(annotation, Qualifier.class)) { // special case @BindTo is only used during tests if (BindTo.class.isAssignableFrom(annotation.getClass())) { continue; } // special case for @Named if (Named.class.isAssignableFrom(annotation.getClass())) { Named named = (Named) annotation; if (isBlank(named.value())) { list.add(named(getPropertyName(klass))); continue; } } list.add(annotation); } } return list; }
@Nonnull protected List<Annotation> harvestQualifiers(@Nonnull Class<?> clazz) { List<Annotation> list = new ArrayList<>(); Annotation[] annotations = clazz.getAnnotations(); for (Annotation annotation : annotations) { if (AnnotationUtils.isAnnotatedWith(annotation, Qualifier.class)) { if (BindTo.class.isAssignableFrom(annotation.getClass())) { continue; } // special case for @Named if (Named.class.isAssignableFrom(annotation.getClass())) { Named named = (Named) annotation; if (isBlank(named.value())) { list.add(named(getPropertyName(clazz))); continue; } } list.add(annotation); } } return list; }
@Nonnull protected List<Annotation> harvestQualifiers(@Nonnull Field field) { List<Annotation> list = new ArrayList<>(); Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (AnnotationUtils.isAnnotatedWith(annotation, Qualifier.class)) { if (BindTo.class.isAssignableFrom(annotation.getClass())) { continue; } // special case for @Named if (Named.class.isAssignableFrom(annotation.getClass())) { Named named = (Named) annotation; if (isBlank(named.value())) { list.add(named(getPropertyName(field.getName()))); continue; } } list.add(annotation); } } return list; }
/** * Obtain a parameter array to call a method with injections or a constructor with injections. * * @param dependencies map of dependencies for beans - pass null if you don't want to record needed dependencies * @param beanName name of the bean * @param types types array for the call * @param genericTypes generic type array for the call * @param annotations annotations of the parameters * @return array suitable as parameter for invoke or newInstance calls * @throws Exception */ private Object[] getParameters(Properties beanProperties, Map<String, Set<Object>> dependencies, String beanName, Class<? extends Object>[] types, Type[] genericTypes, Annotation[][] annotations) throws Exception { beanProperties = beanProperties==null ? new Properties() : beanProperties; Object[] parameters = new Object[types.length]; for (int i = 0; i<types.length; i++) { String name = null; Collection<Annotation> qualifiers = new HashSet<>(); for (Annotation a : annotations[i]) { if (a instanceof Named) { name = ((Named) a).value(); } // if boolean q = false; for (Class<?> ii : a.getClass().getInterfaces()) { LOG.info("getParameters() {}: {}", ii, ii.getAnnotation(Qualifier.class)); q = q||(ii.getAnnotation(Qualifier.class)!=null); } // for if (q) { qualifiers.add(a); } // if } // for // TODO: Deal with scopes. parameters[i] = getValue(beanProperties, dependencies, beanName, types[i], genericTypes[i], name, qualifiers); } // for return parameters; }
private QualifierInfo findQualifierAnnotation( final Element elem ) { Element pe = elem; do { pe = pe.getEnclosingElement(); } while ( pe != null && pe.getKind() != ElementKind.CLASS ); final List<? extends AnnotationMirror> ams = pe.getAnnotationMirrors(); for ( final AnnotationMirror am : ams ) { final Element annoElem = am.getAnnotationType() .asElement(); final Qualifier qualifier = annoElem.getAnnotation( Qualifier.class ); if ( qualifier != null ) { return new QualifierInfo( annoElem ); } } return EMPTY_QUALIFIER; }
private void processAnnotation(final Annotation annotation) { final Class<? extends Annotation> annType = annotation.annotationType(); if (annType == Context.class) { setStrategy(Strategy.CONTEXT); } else if (annType == CookieParam.class) { processCookieParamAnnotation((CookieParam) annotation); } else if (annType == FormParam.class) { processFormParamAnnotation((FormParam) annotation); } else if (annType == HeaderParam.class) { processHeaderParamAnnotation((HeaderParam) annotation); } else if (annType == Named.class) { processNamedAnnotation((Named) annotation); } else if (annType == PathParam.class) { processPathParamAnnotation((PathParam) annotation); } else if (annType == OptionalClasses.PERSISTENCE_CONTEXT) { processPersistenceContextAnnotation((PersistenceContext) annotation); } else if (annType == QueryParam.class) { processQueryParamAnnotation((QueryParam) annotation); } else if (annType == DefaultValue.class) { defaultValue = (DefaultValue) annotation; } else if (annType.isAnnotationPresent(Qualifier.class)) { processQualifierAnnotation(annType); } }
static Set<Annotation> findQualifiers(Set<Annotation> annotations) { Set<Annotation> results = new LinkedHashSet<>(); for(Annotation annotation : annotations) { Class<? extends Annotation> annotationClass = annotation.getClass(); if(annotation instanceof Default) { continue; } else if(annotationClass.getAnnotation(Qualifier.class) != null) { results.add(annotation); } else if(annotationClass.getAnnotation(Stereotype.class) != null) { Set<Annotation> parentAnnotations = new LinkedHashSet<>(asList(annotationClass.getAnnotations())); results.addAll(findQualifiers(parentAnnotations)); } } return results; }
private InjectSignature createInjectSignature(Field field, Class<?> targetType) { Annotation qualifierAnnotation = Annotations.findAnnotationAnnotatedWith(Qualifier.class, field); Nullability nullability = Nullability.create(field); String qualifier = qualifierAnnotation != null ? qualifierCache.getQualifier(qualifierAnnotation) : null; return new InjectSignature(targetType, nullability, qualifier); }
public <A extends Annotation> Binding<T> withName(Class<A> annotationClassWithQualifierAnnotation) { if (!annotationClassWithQualifierAnnotation.isAnnotationPresent(Qualifier.class)) { throw new IllegalArgumentException( String.format("Only qualifier annotation annotations can be used to define a binding name. Add @Qualifier to %s", annotationClassWithQualifierAnnotation)); } this.name = annotationClassWithQualifierAnnotation.getName(); return this; }
boolean isQualifier(Annotation ann) { Class<?> annType = ann.annotationType(); if (annType.isAnnotationPresent(Qualifier.class)) { return true; } return _qualifierSet.contains(annType); }
private boolean isProduces(Annotation []anns) { if (anns == null) { return false; } for (Annotation ann : anns) { if (ann.annotationType().isAnnotationPresent(Qualifier.class)) { return true; } } return false; }
@Override public JsonDriver locate(Annotation[] fieldAnnotations, Optional<String> name) { final BeanManager bm = CDI.current().getBeanManager(); final Annotation[] qualifiers = Arrays.stream(fieldAnnotations).filter(a -> searchAnnotation(a, Qualifier.class).isPresent()).toArray(n -> new Annotation[n]); JsonDriverNotFound.failIf(qualifiers.length > 0 && name.isPresent(), "found both @Qualifiers and @WithDriver.value()"); final Set<Bean<?>> beans = name.map(n -> bm.getBeans(n)).orElseGet(() -> bm.getBeans(JsonDriver.class, qualifiers)); JsonDriverNotFound.failIf(beans.isEmpty(), "no JsonDriver found in BeanManager"); JsonDriverNotFound.failIf(beans.size() > 1, "more than one JsonDriver found in BeanManager, use @JsonType.WithDriver to disambiguate"); final Bean<?> bean = beans.iterator().next(); final CreationalContext<?> ctx = bm.createCreationalContext(bean); return (JsonDriver) bm.getReference(bean, JsonDriver.class, ctx); }
private Set<Annotation> getCdiQualifiers(Annotation[] annotattions) { Set<Annotation> qualifiers = Sets.newHashSet(); for (Annotation annotation : annotattions) { if (annotation.annotationType().isAnnotationPresent(Qualifier.class)) { qualifiers.add(annotation); } } if (qualifiers.isEmpty()) { qualifiers.add(DefaultLiteral.INSTANCE); } return qualifiers; }
/** * @param x the object from which all qualifier annotations shall be searched out. * @return a set of all qualifiers the object's class is annotated with. */ public static Set<Annotation> getCdiQualifiers(AccessibleObject x) { Set<Annotation> qualifiers = Sets.newHashSet(); for (Annotation annotation : x.getAnnotations()) { if (annotation.annotationType().isAnnotationPresent(Qualifier.class)) { qualifiers.add(annotation); } } if (qualifiers.isEmpty()) { qualifiers.add(DefaultLiteral.INSTANCE); } return qualifiers; }
private boolean isQualifier(Class<? extends Annotation> annotationType) { Annotation[] annotations = annotationType.getAnnotations(); for (Annotation annotation : annotations) { if (annotation.annotationType().equals(Qualifier.class)) { return true; } } return false; }
/** * Returns qualifier annotation for the given method, null if none. */ @Nullable public static DeclaredType getQualifierAnnotation(Element element) { for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { DeclaredType annotationType = annotationMirror.getAnnotationType(); if (annotationType.asElement().getAnnotation(Qualifier.class) != null) { return annotationType; } } return null; }
@Test public void testTaggedAnnotation() throws Exception { Constructor<LeatherSmoother.Host> constructor = LeatherSmoother.Host.class.getConstructor(LeatherSmoother.class); Annotation[] annotations = constructor.getParameterAnnotations()[0]; Type paramType = constructor.getGenericParameterTypes()[0]; BeanSpec spec = BeanSpec.of(paramType, annotations, Genie.create()); eq(1, spec.taggedAnnotations(Qualifier.class).length); eq(0, spec.taggedAnnotations(InjectTag.class).length); eq(0, spec.taggedAnnotations(Retention.class).length); eq(0, spec.taggedAnnotations(Target.class).length); eq(0, spec.taggedAnnotations(Inherited.class).length); eq(0, spec.taggedAnnotations(Documented.class).length); }
protected void addQualifierExtractors(StandardInjectorConfiguration config) { config.requiredQualifierExtractors.add(annotatedElement -> Arrays.stream(annotatedElement.getAnnotations()) .filter(a -> a.annotationType().isAnnotationPresent(Qualifier.class))); config.availableQualifierExtractors.add(annotated -> Arrays.stream(annotated.getAnnotations()) .filter(a -> a.annotationType().isAnnotationPresent(Qualifier.class))); }
private AnnotationMirror findQualifier(Element element) { List<AnnotationMirror> annotationMirrors = ExtractorUtil.findAnnotatedAnnotation(element, Qualifier.class); if (annotationMirrors.isEmpty()) { return null; } if (annotationMirrors.size() > 1) { errors.getParent().addInvalid(element, "Cannot have several qualifiers (@Qualifier)."); return null; } return annotationMirrors.get(0); }
private static Annotation findFirstQualifierInAnnotations(Annotation[] annotations) { if (annotations != null) { for (Annotation a : annotations) { if (a.annotationType().isAnnotationPresent(Qualifier.class)) { return a; } } } return null; }
/** * This method builds a list of all qualifier annotations source-code declaration that annotates the passed element. * @param element {@link TypeElement} which will be scanned for qualifier annotations. * @return A list of the annotations source-code declarations. */ public static List<String> getAllQualifiersDeclarationFromType(TypeElement element) { List<String> qualifiers = new ArrayList<>(); for (final AnnotationMirror am : element.getAnnotationMirrors()) { final TypeElement annotationElement = (TypeElement) am.getAnnotationType().asElement(); if (annotationElement.getAnnotation(Qualifier.class) != null) { qualifiers.add(am.toString()); } } return qualifiers; }
@SuppressWarnings("unused") static BeanType createBeanType(Field f) { Collection<Class<?>> genericTypes = filterGenericTypes(f); Named stringQualifier = f.getAnnotation(Named.class); Collection<Annotation> qualifierAnnotations = new ArrayList<>(); if (stringQualifier == null) { for (Annotation annotation : f.getAnnotations()) { if (annotation.annotationType().isAnnotationPresent(Qualifier.class)) { qualifierAnnotations.add(annotation); } } } return new BeanType(f.getType(), genericTypes, stringQualifier == null ? null : stringQualifier.value(), qualifierAnnotations); }
private Set<Annotation> getQualifiers(final Class<?> type) { Set<Annotation> qualifiers = Stream.of(type.getAnnotations()) .filter(a -> a.annotationType().isAnnotationPresent(Qualifier.class)) .collect(Collectors.toSet()); if (qualifiers.isEmpty()) { qualifiers.add(DefaultAnnotationLiteral.INSTANCE); } qualifiers.add(AnyAnnotationLiteral.INSTANCE); return ImmutableSet.copyOf(qualifiers); }
/** * Optionally returns the qualifier annotation of a class. */ public static Optional<Annotation> getQualifier(AnnotatedElement annotatedElement) { AnnotatedElement cleanedAnnotatedElement; if (annotatedElement instanceof Class<?>) { cleanedAnnotatedElement = ProxyUtils.cleanProxy((Class<?>) annotatedElement); } else { cleanedAnnotatedElement = annotatedElement; } return Annotations.on(cleanedAnnotatedElement) .findAll() .filter(AnnotationPredicates.annotationAnnotatedWith(Qualifier.class, false)) .findFirst(); }
@Nonnull @Override public LinkedBindingBuilder<T> withClassifier(@Nonnull Class<? extends Annotation> annotationType) { requireNonNull(annotationType, "Argument 'annotationType' cannot be null"); AnnotationUtils.requireAnnotation(annotationType, Qualifier.class); this.classifierType = annotationType; return this; }