/** * Get display name of specified element from name parameter of {@link Editable} annotation. * If the annotation is not defined or name parameter is not available in the annotation, the * element name itself will be transferred to non-camel case and returned. * * @param element * annotated element to get name from * @return * display name of the element */ public static String getName(AnnotatedElement element) { Editable editable = element.getAnnotation(Editable.class); if (editable != null && editable.name().trim().length() != 0) return editable.name(); else if (element instanceof Class) return WordUtils.uncamel(((Class<?>)element).getSimpleName()); else if (element instanceof Field) return WordUtils.uncamel(WordUtils.capitalize(((Field)element).getName())); else if (element instanceof Method) return StringUtils.substringAfter(WordUtils.uncamel(((Method)element).getName()), " "); else if (element instanceof Package) return ((Package)element).getName(); else throw new GeneralException("Invalid element type: " + element.getClass().getName()); }
private static <M extends Member & AnnotatedElement> void addInjectorsForMembers( TypeLiteral<?> typeLiteral, Factory<M> factory, boolean statics, Collection<InjectionPoint> injectionPoints, Errors errors) { for (M member : factory.getMembers(getRawType(typeLiteral.getType()))) { if (isStatic(member) != statics) { continue; } Inject inject = member.getAnnotation(Inject.class); if (inject == null) { continue; } try { injectionPoints.add(factory.create(typeLiteral, member, errors)); } catch (ConfigurationException ignorable) { if (!inject.optional()) { errors.merge(ignorable.getErrorMessages()); } } } }
private static String getNameFromMemberAnnotation(final AnnotatedElement field) { final String result; if (field.isAnnotationPresent(Attribute.class)) { result = Utils.name(field.getAnnotation(Attribute.class).name(), field); } else if (field.isAnnotationPresent(Element.class)) { result = Utils.name(field.getAnnotation(Element.class).name(), field); } else if (field.isAnnotationPresent(ElementList.class)) { result = Utils.name(field.getAnnotation(ElementList.class).name(), field); } else if (field.isAnnotationPresent(ElementMap.class)) { result = Utils.name(field.getAnnotation(ElementMap.class).name(), field); } else if (field.isAnnotationPresent(Text.class)) { result = "**text**"; } else { result = null; } return result; }
/** * Find all the tester annotations declared on a tester class or method. * @param classOrMethod a class or method whose tester annotations to find * @return an iterable sequence of tester annotations on the class */ public static Iterable<Annotation> getTesterAnnotations(AnnotatedElement classOrMethod) { synchronized (annotationCache) { List<Annotation> annotations = annotationCache.get(classOrMethod); if (annotations == null) { annotations = new ArrayList<Annotation>(); for (Annotation a : classOrMethod.getDeclaredAnnotations()) { if (a.annotationType().isAnnotationPresent(TesterAnnotation.class)) { annotations.add(a); } } annotations = Collections.unmodifiableList(annotations); annotationCache.put(classOrMethod, annotations); } return annotations; } }
private SourceId getSourceId(AnnotatedElement element) { SourceId sourceId = null; Optional<Annotation> sourceAnnotation = Stream.of(element.getAnnotations()) .filter(a -> a.annotationType().isAnnotationPresent(RegisteredSourceIdProducer.class)).findFirst(); if (sourceAnnotation.isPresent()) { RegisteredSourceIdProducer sourceIdProviderAnnotation = sourceAnnotation.get().annotationType() .getAnnotation(RegisteredSourceIdProducer.class); try { SourceIdProducer sourceIdProducer = sourceIdProviderAnnotation.value().newInstance(); sourceId = sourceIdProducer.get(element, sourceAnnotation.get()); } catch (Exception e) { throw new QueryProxyException("Problem with sourceId aquiring: can't find suitable constructor " + e, e); } } return sourceId; }
private Map<String, String> getReferenceColumnNamesMapForReferenceAttribute(SingularAttribute<?, ?> attribute, ManagedType<?> targetEntity) { List<String> idAttributeNames = targetEntity.getSingularAttributes().stream() .filter(this::isIdAttribute) .map(this::getSingularAttributeColumnName) .collect(Collectors.toList()); JoinColumns joinColumnsAnnotation = ((AnnotatedElement) attribute.getJavaMember()).getAnnotation(JoinColumns.class); JoinColumn joinColumnAnnotation = ((AnnotatedElement) attribute.getJavaMember()).getAnnotation(JoinColumn.class); JoinColumn[] joinColumns = joinColumnsAnnotation != null ? joinColumnsAnnotation.value() : joinColumnAnnotation != null ? new JoinColumn[]{joinColumnAnnotation} : null; Map<String, String> referenceColumnNamesMap; if (joinColumns != null) { referenceColumnNamesMap = Arrays.stream(joinColumns) .collect(Collectors.toMap(JoinColumn::name, joinColumn -> joinColumn.referencedColumnName().length() > 0 ? joinColumn.referencedColumnName() : idAttributeNames.get(0))); } else { referenceColumnNamesMap = idAttributeNames.stream() .collect(Collectors.toMap(idAttributeName -> attribute.getName().toUpperCase() + "_" + idAttributeName, idAttributeName -> idAttributeName)); } return referenceColumnNamesMap; }
public EjbRefElement(Member member, PropertyDescriptor pd) { super(member, pd); AnnotatedElement ae = (AnnotatedElement) member; EJB resource = ae.getAnnotation(EJB.class); String resourceBeanName = resource.beanName(); String resourceName = resource.name(); this.isDefaultName = !StringUtils.hasLength(resourceName); if (this.isDefaultName) { resourceName = this.member.getName(); if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) { resourceName = Introspector.decapitalize(resourceName.substring(3)); } } Class<?> resourceType = resource.beanInterface(); if (resourceType != null && !Object.class.equals(resourceType)) { checkResourceType(resourceType); } else { // No resource type specified... check field/method. resourceType = getResourceType(); } this.beanName = resourceBeanName; this.name = resourceName; this.lookupType = resourceType; this.mappedName = resource.mappedName(); }
/** * Utility method for calling an arbitrary method in an annotation. * * @param element the element that was annotated, either a class or method * @param annotation the class of the annotation we're interested in * @param methodName the name of the method in the annotation we wish * to call. * @param defaultValue the value to return if the annotation doesn't * exist, or we couldn't invoke the method for some reason. * @return the result of calling the annotation method, or the default. */ protected static Object getAnnotationValue( AnnotatedElement element, Class<? extends Annotation> annotation, String methodName, Object defaultValue) { Object ret = defaultValue; try { Method m = annotation.getMethod(methodName); Annotation a = element.getAnnotation(annotation); ret = m.invoke(a); } catch (NoSuchMethodException e) { assert false; } catch (IllegalAccessException e) { assert false; } catch (InvocationTargetException e) { assert false; } catch (NullPointerException e) { assert false; } return ret; }
/** * Find the annotations of given <code>annotationType</code> on given element and stores them in given * <code>accumulator</code>. * @param accumulator Accumulator * @param element Annotated element * @param annotationType Annotation type to lookup * @param repeatableContainerType Optional repeteable annotation type */ private static <A extends Annotation> void findAnnotations(List<A> accumulator, AnnotatedElement element, Class<A> annotationType, Class<? extends Annotation> repeatableContainerType) { // direct lookup A[] as = element.getAnnotationsByType(annotationType); if (as.length > 0) { for (A a : as) { accumulator.add(a); } } // check meta-annotations Annotation[] all = element.getAnnotations(); if (all.length > 0) { for (Annotation annotation : all) { if (!isInJavaLangAnnotationPackage(annotation) && !annotation.annotationType().equals(annotationType) && (repeatableContainerType == null || !annotation.annotationType().equals(repeatableContainerType))) { findAnnotations(accumulator, annotation.annotationType(), annotationType, repeatableContainerType); } } } }
public Annotations(AnnotatedElement... elements) { for (AnnotatedElement element : elements) { for (Annotation annotation : element.getAnnotations()) { annotations.put(annotation.annotationType(), annotation); } } }
public static AnnotatedElement getAnnotatedElement(Class<?> beanClass, String propertyName, Class<?> propertyClass) { Field field = getFieldOrNull(beanClass, propertyName); Method method = getGetterOrNull(beanClass, propertyName, propertyClass); if (field == null || field.getAnnotations().length == 0) { return (method != null && method.getAnnotations().length > 0) ? method : method; } else if (method == null || method.getAnnotations().length == 0) { return field; } else { //return new Annotations(field, method); return null; } }
private Tracked resolveAnnotation(InvocationContext context) { Function<AnnotatedElement, Tracked> extractor = c -> c.getAnnotation(Tracked.class); Method method = context.getMethod(); Tracked tracked = extractor.apply(method); return tracked != null ? tracked : extractor.apply(method.getDeclaringClass()); }
/** * Get all the annotations of given <code>annotationType</code> present in given <code>element</code>, including any * meta-annotation and supporting repeatable annotations. * @param <A> Annotation type * @param element Annotated element to inspect (not null) * @param annotationType Annotation type to lookup * @return List of detected annotation of given <code>annotationType</code>, an empty List if none found */ public static <A extends Annotation> List<A> getAnnotations(AnnotatedElement element, Class<A> annotationType) { ObjectUtils.argumentNotNull(element, "AnnotatedElement must be not null"); ObjectUtils.argumentNotNull(annotationType, "Annotation type must be not null"); Class<? extends Annotation> repeatableContainerType = null; if (annotationType.isAnnotationPresent(Repeatable.class)) { repeatableContainerType = annotationType.getAnnotation(Repeatable.class).value(); } List<A> annotations = new LinkedList<>(); findAnnotations(annotations, element, annotationType, repeatableContainerType); return annotations; }
@Override Object createFor(AnnotatedElement annotatedElement, Class<?> targetType, Fairy fairy) { IntegerWith config = findAnnotation(annotatedElement, IntegerWith.class).orElse(null); int min = minValue(config); int max = maxValue(config); BaseProducer producer = fairy.baseProducer(); return producer.randomBetween(min, max); }
private List<QueryConverter> getConverters(AnnotatedElement element) { List<QueryConverter> annotatedConverters = new ArrayList<>(2); List<Annotation> converterAnnotations = Stream.of(element.getAnnotations()) .filter(a -> a.annotationType().isAnnotationPresent(Converter.class) || converters.containsKey(a.annotationType())) .collect(Collectors.toList()); if (!converterAnnotations.isEmpty()) { for (Annotation converterAnnotation : converterAnnotations) { QueryConverterFactory factory; if (converters.containsKey(converterAnnotation.annotationType())) { factory = converters.get(converterAnnotation.annotationType()); } else { Converter converter = converterAnnotation.annotationType().getAnnotation(Converter.class); Class<? extends QueryConverterFactory> converterFactoryClass = converter.value(); if (Converter.DEFAULT.class.isAssignableFrom(converterFactoryClass)) { throw new QueryProxyException("Factory is not registered for annotation " + converterAnnotation.annotationType().getName() + "! " + "Set static converter using @Converter annotation value or use Queries.Builder.converter() method to register factory instance!"); } try { factory = converterFactoryClass.newInstance(); } catch (Exception e) { throw new QueryProxyException( "Problem instantiating query converter factory class with no argument constructor " + e, e); } } annotatedConverters.add(factory.get(converterAnnotation)); } } return annotatedConverters; }
public TypeAnnotation(TypeAnnotationTargetInfo targetInfo, LocationInfo loc, Annotation annotation, AnnotatedElement baseDeclaration) { this.targetInfo = targetInfo; this.loc = loc; this.annotation = annotation; this.baseDeclaration = baseDeclaration; }
private static void checkAnnotations(AnnotatedElement el, AnnotatableWrapper aw) throws Exception { for (Annotation ann : el.getAnnotations()) { Annotation wrapper = aw.getAnnotation(ann.annotationType()); assertNotNull(ann.annotationType().getName(), wrapper); checkAnnotation(ann, wrapper); } }
private boolean ignoreThrowable(Exception exception, AnnotatedElement... annotatedElements) { if(exception != null) { for(AnnotatedElement element : annotatedElements) { if(element == null) { continue; } IgnoreRemoteExceptions annotation = element.getAnnotation(IgnoreRemoteExceptions.class); if(annotation != null) { return !Arrays.asList(annotation.exceptTypes()).contains(exception.getClass()); } } } return false; }
private static <M extends Member & AnnotatedElement> void addInjectionPoints(TypeLiteral<?> type, Factory<M> factory, boolean statics, Collection<InjectionPoint> injectionPoints, Errors errors) { if (type.getType() == Object.class) { return; } // Add injectors for superclass first. TypeLiteral<?> superType = type.getSupertype(type.getRawType().getSuperclass()); addInjectionPoints(superType, factory, statics, injectionPoints, errors); // Add injectors for all members next addInjectorsForMembers(type, factory, statics, injectionPoints, errors); }
private List<Label> getLabels(final AnnotatedElement annotatedElement) { return Stream.of( getAnnotations(annotatedElement, Epic.class).map(ResultsUtils::createLabel), getAnnotations(annotatedElement, Feature.class).map(ResultsUtils::createLabel), getAnnotations(annotatedElement, Story.class).map(ResultsUtils::createLabel), getAnnotations(annotatedElement, Severity.class).map(ResultsUtils::createLabel), getAnnotations(annotatedElement, Owner.class).map(ResultsUtils::createLabel) ).reduce(Stream::concat).orElseGet(Stream::empty).collect(Collectors.toList()); }
private List<Link> getLinks(final AnnotatedElement annotatedElement) { return Stream.of( getAnnotations(annotatedElement, io.qameta.allure.Link.class).map(ResultsUtils::createLink), getAnnotations(annotatedElement, io.qameta.allure.Issue.class).map(ResultsUtils::createLink), getAnnotations(annotatedElement, io.qameta.allure.TmsLink.class).map(ResultsUtils::createLink)) .reduce(Stream::concat).orElseGet(Stream::empty).collect(Collectors.toList()); }
private <T extends Annotation> Stream<T> getAnnotations(final AnnotatedElement annotatedElement, final Class<T> annotationClass) { final T annotation = annotatedElement.getAnnotation(annotationClass); return Stream.concat( extractRepeatable(annotatedElement, annotationClass).stream(), Objects.isNull(annotation) ? Stream.empty() : Stream.of(annotation) ); }
private static <T extends Annotation> List<Label> getLabels(final AnnotatedElement element, final Class<T> annotation, final Function<T, List<Label>> extractor) { return element.isAnnotationPresent(annotation) ? extractor.apply(element.getAnnotation(annotation)) : Collections.emptyList(); }
public static <T extends Annotation> List<Link> getLinks(final Method method, final Class<T> annotation, final Function<T, List<Link>> extractor) { final List<Link> labels = new ArrayList<>(); labels.addAll(getLinks((AnnotatedElement) method, annotation, extractor)); labels.addAll(getLinks(method.getDeclaringClass(), annotation, extractor)); return labels; }
private Object resolve(AnnotatedElement annotatedElement, Class<?> targetType) { for (ObjectProvider provider : providers) { if (provider.supports(targetType)) { return provider.createFor(annotatedElement, targetType); } } throw new IllegalArgumentException("no provider found for type " + targetType); }
@Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) { AnnotatedElement element = extensionContext.getElement().orElseThrow(AssertionError::new); Disabled disabled = findAnnotation(element, Disabled.class).orElseThrow(AssertionError::new); String name = disabled.value(); String reason = name + "=" + System.getProperty(name); boolean result = Boolean.getBoolean(name); if (disabled.not()) { result = !result; } if (result) { return ConditionEvaluationResult.disabled(reason); } return ConditionEvaluationResult.enabled(reason); }
/** * The default implementation performs a simple search for a declared annotation matching the search type. * Spring provides a more sophisticated annotation search utility that matches on meta-annotations as well. * * @param annotatedElement The element to search. * @param annotationType The annotation type class. * @param <A> Annotation type to search for. * @return */ @SuppressWarnings("unchecked") default <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement, Class<A> annotationType) { Annotation[] anns = annotatedElement.getDeclaredAnnotations(); for (Annotation ann : anns) { if (ann.annotationType() == annotationType) { return (A) ann; } } return null; }
Set<Timed> findTimedAnnotations(AnnotatedElement element) { Timed t = annotationFinder.findAnnotation(element, Timed.class); if (t != null) return Collections.singleton(t); TimedSet ts = annotationFinder.findAnnotation(element, TimedSet.class); if (ts != null) { return Arrays.stream(ts.value()).collect(Collectors.toSet()); } return Collections.emptySet(); }
public static Set<Timed> findTimedAnnotations(AnnotatedElement element) { Timed t = AnnotationUtils.findAnnotation(element, Timed.class); if (t != null) return Collections.singleton(t); TimedSet ts = AnnotationUtils.findAnnotation(element, TimedSet.class); if (ts != null) { return Arrays.stream(ts.value()).collect(Collectors.toSet()); } return Collections.emptySet(); }
/** * Construct the set of requirements specified by annotations * directly on a tester class or method. * @param classOrMethod a tester class or a test method thereof * @return all the constraints implicitly or explicitly required by * annotations on the class or method. * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ public static TesterRequirements buildDeclaredTesterRequirements(AnnotatedElement classOrMethod) throws ConflictingRequirementsException { TesterRequirements requirements = new TesterRequirements(); Iterable<Annotation> testerAnnotations = getTesterAnnotations(classOrMethod); for (Annotation testerAnnotation : testerAnnotations) { TesterRequirements moreRequirements = buildTesterRequirements(testerAnnotation); incorporateRequirements(requirements, moreRequirements, testerAnnotation); } return requirements; }
private static String serializedName(Member member) { if(member instanceof AnnotatedElement) { SerializedName nameAnnot = ((AnnotatedElement) member).getAnnotation(SerializedName.class); if(nameAnnot != null) return nameAnnot.value(); } return member.getName(); }
public static boolean isAction(AnnotatedElement element) { if (element.getAnnotation(Action.class) != null) { return true; } for (Annotation anno : element.getAnnotations()) { if (AnnotationUtil.isActionAnnotation(anno)) { return true; } } return false; }
private static String getTableName(Class javaType) { javax.persistence.Table tableAnnotation = ((AnnotatedElement) javaType).getAnnotation(javax.persistence.Table.class); javax.persistence.Entity entityAnnotation = ((AnnotatedElement) javaType).getAnnotation(javax.persistence.Entity.class); boolean tableNameSet = tableAnnotation != null && tableAnnotation.name().length() > 0; boolean entityNameSet = entityAnnotation != null && entityAnnotation.name().length() > 0; return tableNameSet ? tableAnnotation.name().toUpperCase() : entityNameSet ? entityAnnotation.name().toUpperCase() : javaType.getSimpleName().toUpperCase(); }
public static ValidElement by(AnnotatedElement annotatedElement) { Valid annotation = annotatedElement.getAnnotation(Valid.class); if (annotation == null) { return NULL_VALID; } return new ValidElement(annotation); }
private void readAnnotations(AnnotatedElement element) { if (element.isAnnotationPresent(BindItem.class)) { BindItem bindItem = element.getAnnotation(BindItem.class); putViewType(bindItem.layout(), bindItem.holder()); } else { throw new IllegalStateException("items should be annotated with BindItem"); } }
/** * Finds a parameter annotation. * * @param element * annotated element. * @return a pair with annotation type on the left and value on the right. */ public static Optional<Pair<Class<? extends Annotation>, String>> parameterAnnotation(final AnnotatedElement element) { final PathParam pathParam = element.getAnnotation(PathParam.class); if (pathParam != null) { return Optional.of(Pair.of(PathParam.class, StringHelper.camelize(pathParam.value()))); } final QueryParam queryParam = element.getAnnotation(QueryParam.class); if (queryParam != null) { return Optional.of(Pair.of(QueryParam.class, StringHelper.camelize(queryParam.value()))); } return Optional.empty(); }
private static Set<Class<? extends Module>> getModuleTypes(AnnotatedElement element) { return findRepeatableAnnotations(element, IncludeModule.class) .stream() .map(IncludeModule::value) .flatMap(Stream::of) .collect(toSet()); }
Optional<ConditionEvaluationResult> evaluateElement( List<String> currentDisplayName, AnnotatedElement element) { List<Disable> disabledTests = findRepeatableAnnotations(element, Disable.class); return disabledTests .stream() .filter( disabledTest -> Arrays.asList(disabledTest.value()).equals(currentDisplayName)) .map(disabledTest -> ConditionEvaluationResult.disabled(disabledTest.reason())) .findFirst(); }
/** * Checks if given <code>element</code> has the {@link Authenticate} annotation and if so registers the required * authentication filters. * @param context Feature context * @param element Annotated element * @return <code>true</code> if the {@link Authenticate} annotation was found and the authentication filters were * registered, <code>false</code> otherwise */ private static boolean registerAuthenticationFilters(FeatureContext context, AnnotatedElement element) { if (element.isAnnotationPresent(Authenticate.class)) { // AuthContext setup for SecurityContext context.register(AuthContextFilter.class, Priorities.AUTHENTICATION - 10); // Authenticator context.register(new AuthenticationFilter(element.getAnnotation(Authenticate.class).schemes()), Priorities.AUTHENTICATION); return true; } return false; }