Java Code Examples for java.lang.reflect.AnnotatedType

The following examples show how to use java.lang.reflect.AnnotatedType. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private static void testReturnsEmptyAT() {
    for (Class<?> toTest : nonNullTestData) {
        tests++;

        AnnotatedType res = toTest.getAnnotatedSuperclass();

        if (res == null) {
            failed++;
            System.out.println(toTest + ".getAnnotatedSuperclass() returns 'null' should  be non-null");
        } else if (res.getAnnotations().length != 0) {
            failed++;
            System.out.println(toTest + ".getAnnotatedSuperclass() returns: "
                    + Arrays.asList(res.getAnnotations()) + ", should be an empty AnnotatedType");
        }
    }
}
 
Example 2
private void verifyArrayFieldTypeAnnotations(Class c)
    throws NoSuchFieldException, NoSuchMethodException {

    Annotation anno;
    AnnotatedType at;

    at = c.getDeclaredField("typeAnnotatedArray").getAnnotatedType();
    anno = at.getAnnotations()[0];
    verifyTestAnn(arrayTA[0], anno, "array1");
    arrayTA[0] = anno;

    for (int i = 1; i <= 3; i++) {
        at = ((AnnotatedArrayType) at).getAnnotatedGenericComponentType();
        anno = at.getAnnotations()[0];
        verifyTestAnn(arrayTA[i], anno, "array" + (i + 1));
        arrayTA[i] = anno;
    }
}
 
Example 3
private static void testReturnsEmptyAT() {
    for (Class<?> toTest : nonNullTestData) {
        tests++;

        AnnotatedType res = toTest.getAnnotatedSuperclass();

        if (res == null) {
            failed++;
            System.out.println(toTest + ".getAnnotatedSuperclass() returns 'null' should  be non-null");
        } else if (res.getAnnotations().length != 0) {
            failed++;
            System.out.println(toTest + ".getAnnotatedSuperclass() returns: "
                    + Arrays.asList(res.getAnnotations()) + ", should be an empty AnnotatedType");
        }
    }
}
 
Example 4
Source Project: graphql-spqr   Source File: ClassUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean containsTypeAnnotation(AnnotatedType type, Class<? extends Annotation> annotation) {
    if (type.isAnnotationPresent(annotation)) {
        return true;
    }
    if (type instanceof AnnotatedParameterizedType) {
        AnnotatedParameterizedType parameterizedType = ((AnnotatedParameterizedType) type);
        return Arrays.stream(parameterizedType.getAnnotatedActualTypeArguments())
                .anyMatch(param -> containsTypeAnnotation(param, annotation));
    }
    if (type instanceof AnnotatedTypeVariable) {
        AnnotatedTypeVariable variable = ((AnnotatedTypeVariable) type);
        return Arrays.stream(variable.getAnnotatedBounds())
                .anyMatch(bound -> containsTypeAnnotation(bound, annotation));
    }
    if (type instanceof AnnotatedWildcardType) {
        AnnotatedWildcardType wildcard = ((AnnotatedWildcardType) type);
        return Stream.concat(
                Arrays.stream(wildcard.getAnnotatedLowerBounds()),
                Arrays.stream(wildcard.getAnnotatedUpperBounds()))
                .anyMatch(param -> containsTypeAnnotation(param, annotation));
    }
    return type instanceof AnnotatedArrayType && containsTypeAnnotation(((AnnotatedArrayType) type).getAnnotatedGenericComponentType(), annotation);
}
 
Example 5
Source Project: graphql-spqr   Source File: ResolutionEnvironment.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T, S> S convertOutput(T output, AnnotatedElement element, AnnotatedType type) {
    if (output == null) {
        return null;
    }

    // Transparently handle unexpected wrapped results. This enables elegant exception handling, partial results etc.
    if (DataFetcherResult.class.equals(output.getClass()) && !DataFetcherResult.class.equals(resolver.getRawReturnType())) {
        DataFetcherResult<?> result = (DataFetcherResult<?>) output;
        if (result.getData() != null) {
            Object convertedData = convert(result.getData(), element, type);
            return (S) DataFetcherResult.newResult()
                    .data(convertedData)
                    .errors(result.getErrors())
                    .localContext(result.getLocalContext())
                    .mapRelativeErrors(result.isMapRelativeErrors())
                    .build();
        }
    }

    return convert(output, element, type);
}
 
Example 6
Source Project: graphql-spqr   Source File: PublicResolverBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private Collection<Resolver> buildPropertyAccessors(Stream<Property> properties, ResolverBuilderParams params) {
    MessageBundle messageBundle = params.getEnvironment().messageBundle;
    AnnotatedType beanType = params.getBeanType();
    Predicate<Member> mergedFilters = getFilters().stream().reduce(Predicate::and).orElse(ACCEPT_ALL);

    return properties
            .filter(prop -> isQuery(prop, params))
            .filter(prop -> mergedFilters.test(prop.getField()) && mergedFilters.test(prop.getGetter()))
            .filter(prop -> params.getInclusionStrategy().includeOperation(Arrays.asList(prop.getField(), prop.getGetter()), beanType))
            .map(prop -> {
                TypedElement element = propertyElementReducer.apply(new TypedElement(getFieldType(prop.getField(), params), prop.getField()), new TypedElement(getReturnType(prop.getGetter(), params), prop.getGetter()));
                OperationInfoGeneratorParams infoParams = new OperationInfoGeneratorParams(element, beanType, params.getQuerySourceBeanSupplier(), messageBundle, OperationDefinition.Operation.QUERY);
                return new Resolver(
                        messageBundle.interpolate(operationInfoGenerator.name(infoParams)),
                        messageBundle.interpolate(operationInfoGenerator.description(infoParams)),
                        messageBundle.interpolate(ReservedStrings.decode(operationInfoGenerator.deprecationReason(infoParams))),
                        element.isAnnotationPresent(Batched.class),
                        params.getQuerySourceBeanSupplier() == null ? new MethodInvoker(prop.getGetter(), beanType) : new FixedMethodInvoker(params.getQuerySourceBeanSupplier(), prop.getGetter(), beanType),
                        element,
                        argumentBuilder.buildResolverArguments(new ArgumentBuilderParams(prop.getGetter(), beanType, params.getInclusionStrategy(), params.getTypeTransformer(), params.getEnvironment())),
                        element.isAnnotationPresent(GraphQLComplexity.class) ? element.getAnnotation(GraphQLComplexity.class).value() : null
                );
            })
            .collect(Collectors.toSet());
}
 
Example 7
Source Project: graphql-spqr   Source File: ClassUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends AnnotatedType> T transformType(T type, UnaryOperator<T> transformer) {
    if (type instanceof AnnotatedArrayType) {
        return (T) TypeFactory.arrayOf(transformer.apply((T) ((AnnotatedArrayType) type).getAnnotatedGenericComponentType()), type.getAnnotations());
    }
    if (type.getType() instanceof Class) {
        return type;
    }
    if (type instanceof AnnotatedParameterizedType) {
        AnnotatedParameterizedType parameterizedType = (AnnotatedParameterizedType) type;
        AnnotatedType[] arguments = Arrays.stream(parameterizedType.getAnnotatedActualTypeArguments())
                .map(param -> transformer.apply((T) param))
                .toArray(AnnotatedType[]::new);
        return (T) TypeFactory.parameterizedAnnotatedClass(GenericTypeReflector.erase(type.getType()), type.getAnnotations(), arguments);
    }
    throw new IllegalArgumentException("Can not find the mappable type for: " + type.getType().getTypeName());
}
 
Example 8
public void checkAnnotations(AnnotatedType type, String expected) {
    String actual = Arrays.asList(((AnnotatedParameterizedType) type)
                                  .getAnnotations())
                                  .toString()
                                   + "," +
                    Arrays.asList(((AnnotatedParameterizedType) type)
                                   .getAnnotatedActualTypeArguments()[0].getAnnotations())
                                   .toString();

    if (!actual.equals(expected))
        throw new AssertionError("Unexpected annotations" + actual);
}
 
Example 9
Source Project: graphql-spqr   Source File: AnnotatedArgumentBuilder.java    License: Apache License 2.0 5 votes vote down vote up
protected OperationArgument buildResolverArgument(Parameter parameter, AnnotatedType parameterType, ArgumentBuilderParams builderParams) {
    return new OperationArgument(
            parameterType,
            getArgumentName(parameter, parameterType, builderParams),
            getArgumentDescription(parameter, parameterType, builderParams.getEnvironment().messageBundle),
            defaultValue(parameter, parameterType, builderParams.getEnvironment()),
            parameter,
            parameter.isAnnotationPresent(GraphQLContext.class),
            builderParams.getInclusionStrategy().includeArgumentForMapping(parameter, parameterType, builderParams.getDeclaringType())
    );
}
 
Example 10
Source Project: graphql-spqr   Source File: DerivedTypeRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void derive(AnnotatedElement element, AnnotatedType type, List<DelegatingOutputConverter> derivers) {
    derivers.stream()
            .filter(deriver -> deriver.supports(element, type))
            .findFirst()
            .ifPresent(deriver -> registerDerivatives(element, type, deriver.getDerivedTypes(type), derivers));
}
 
Example 11
private void verifyMapFieldTypeAnnotations(Class c)
    throws NoSuchFieldException, NoSuchMethodException {

    Annotation anno;
    AnnotatedType atBase;
    AnnotatedType atParameter;
    atBase = c.getDeclaredField("typeAnnotatedMap").getAnnotatedType();

    anno = atBase.getAnnotations()[0];
    verifyTestAnn(mapTA[0], anno, "map1");
    mapTA[0] = anno;

    atParameter =
        ((AnnotatedParameterizedType) atBase).
        getAnnotatedActualTypeArguments()[0];
    anno = ((AnnotatedWildcardType) atParameter).getAnnotations()[0];
    verifyTestAnn(mapTA[1], anno, "map2");
    mapTA[1] = anno;

    anno =
        ((AnnotatedWildcardType) atParameter).
        getAnnotatedUpperBounds()[0].getAnnotations()[0];
    verifyTestAnn(mapTA[2], anno, "map3");
    mapTA[2] = anno;

    atParameter =
        ((AnnotatedParameterizedType) atBase).
        getAnnotatedActualTypeArguments()[1];
    anno = ((AnnotatedParameterizedType) atParameter).getAnnotations()[0];
    verifyTestAnn(mapTA[3], anno, "map4");
    mapTA[3] = anno;

    anno =
        ((AnnotatedParameterizedType) atParameter).
        getAnnotatedActualTypeArguments()[0].getAnnotations()[0];
    verifyTestAnn(mapTA[4], anno, "map5");
    mapTA[4] = anno;
}
 
Example 12
Source Project: graphql-spqr   Source File: TypeInferenceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSameClasses() throws AnnotationFormatException {
    Annotation[] nonNull = new Annotation[] {TypeFactory.annotation(Nonnull.class, Collections.emptyMap())};
    Annotation[] graphQLNonNull = new Annotation[] {TypeFactory.annotation(GraphQLNonNull.class, Collections.emptyMap())};
    Annotation[] mergedAnnotations = new Annotation[] {nonNull[0], graphQLNonNull[0]};
    AnnotatedType p1 = GenericTypeReflector.annotate(P.class, nonNull);
    AnnotatedType p2 = GenericTypeReflector.annotate(P.class, graphQLNonNull);
    AnnotatedType expected = GenericTypeReflector.annotate(P.class, mergedAnnotations);
    AnnotatedType inferred = ClassUtils.getCommonSuperType(Arrays.asList(p1, p2));
    assertTrue(GenericTypeReflector.equals(expected, inferred));
}
 
Example 13
Source Project: typescript-generator   Source File: JTypeVariable.java    License: MIT License 5 votes vote down vote up
public JTypeVariable(D genericDeclaration, String name, Type[] bounds, AnnotatedType[] annotatedBounds, Annotation[] annotations, Annotation[] declaredAnnotations) {
    this.genericDeclaration = genericDeclaration;
    this.name = Objects.requireNonNull(name, "name");
    this.bounds = bounds != null ? bounds : new Type[0];
    this.annotatedBounds = annotatedBounds != null ? annotatedBounds : new AnnotatedType[0];
    this.annotations = annotations != null ? annotations : new Annotation[0];
    this.declaredAnnotations = declaredAnnotations != null ? declaredAnnotations : this.annotations;
}
 
Example 14
Source Project: jdk8u60   Source File: RedefineAnnotations.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void verifyInnerFieldTypeAnnotations(Class c)
    throws NoSuchFieldException, NoSuchMethodException {

    AnnotatedType at = c.getDeclaredField("typeAnnotatedInner").getAnnotatedType();
    Annotation anno = at.getAnnotations()[0];
    verifyTestAnn(innerTA, anno, "inner");
    innerTA = anno;
}
 
Example 15
Source Project: graphql-spqr   Source File: AbstractResolverBuilder.java    License: Apache License 2.0 5 votes vote down vote up
protected AnnotatedType getReturnType(Method method, ResolverBuilderParams params) {
    try {
        return params.getTypeTransformer().transform(ClassUtils.getReturnType(method, params.getBeanType()));
    } catch (TypeMappingException e) {
        throw TypeMappingException.ambiguousMemberType(method, params.getBeanType(), e);
    }
}
 
Example 16
Source Project: graphql-spqr   Source File: ArrayAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AnnotatedType getSubstituteType(AnnotatedType original) {
    AnnotatedType component = ((AnnotatedArrayType) original).getAnnotatedGenericComponentType();
    Class<?> raw = ClassUtils.getRawType(component.getType());
    if (raw.isPrimitive()) {
        component = GenericTypeReflector.annotate(GenericTypeReflector.box(raw), component.getAnnotations());
    }
    return TypeFactory.parameterizedAnnotatedClass(List.class, original.getAnnotations(), component);
}
 
Example 17
Source Project: graphql-spqr   Source File: TypeInferenceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLists() throws AnnotationFormatException {
    Annotation[] annotations = new Annotation[] {TypeFactory.annotation(GraphQLNonNull.class, Collections.emptyMap())};
    AnnotatedType nonNullLongType = GenericTypeReflector.annotate(Long.class, annotations);
    AnnotatedType doubleType = GenericTypeReflector.annotate(Double.class);
    AnnotatedType nonNullNumberType = TypeFactory.parameterizedAnnotatedClass(Number.class, annotations);
    AnnotatedType expected = TypeFactory.parameterizedAnnotatedClass(AbstractList.class, annotations, nonNullNumberType);
    AnnotatedType list1 = TypeFactory.parameterizedAnnotatedClass(ArrayList.class, annotations, nonNullLongType);
    AnnotatedType list2 = TypeFactory.parameterizedAnnotatedClass(LinkedList.class, new Annotation[0], doubleType);
    AnnotatedType inferred = ClassUtils.getCommonSuperType(Arrays.asList(list1, list2));
    assertTrue(GenericTypeReflector.equals(expected, inferred));
}
 
Example 18
Source Project: graphql-spqr   Source File: ArgumentInjectorParams.java    License: Apache License 2.0 5 votes vote down vote up
public ArgumentInjectorParams(Object input, boolean present, AnnotatedType type, AnnotatedType baseType, Parameter parameter, ResolutionEnvironment resolutionEnvironment) {
    this.input = input;
    this.present = present;
    this.type = Objects.requireNonNull(type);
    this.baseType = baseType;
    this.parameter = parameter;
    this.resolutionEnvironment = Objects.requireNonNull(resolutionEnvironment);
}
 
Example 19
@Override
public Object convertOutput(Mono<T> original, AnnotatedType type, ResolutionEnvironment resolutionEnvironment) {
    //For subscriptions, Mono<T> (Publisher<T>) should be returned directly
    if (resolutionEnvironment.dataFetchingEnvironment.getParentType() == resolutionEnvironment.dataFetchingEnvironment.getGraphQLSchema().getSubscriptionType()) {
        return original;
    }
    //For other operations it must be converted into a CompletableFuture<T>
    return original.toFuture();
}
 
Example 20
Source Project: oval   Source File: AnnotationsConfigurer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private List<ParameterConfiguration> _createParameterConfigs(final Class<?>[] paramTypes, final Annotation[][] paramAnnos,
   final AnnotatedType[] annotatedParamTypes) {
   final CollectionFactory cf = getCollectionFactory();

   final List<ParameterConfiguration> paramCfgs = cf.createList(paramAnnos.length);

   List<Check> paramChecks = cf.createList(2);
   List<CheckExclusion> paramCheckExclusions = cf.createList(2);

   // loop over all parameters of the current constructor
   for (int i = 0; i < paramAnnos.length; i++) {

      // loop over all annotations of the current constructor parameter
      for (final Annotation anno : paramAnnos[i]) {
         // check if the current annotation is a constraint annotation
         if (anno.annotationType().isAnnotationPresent(Constraint.class)) {
            paramChecks.add(initializeCheck(anno));
         } else if (anno.annotationType().isAnnotationPresent(Constraints.class)) {
            initializeChecks(anno, paramChecks);
         } else if (anno.annotationType().isAnnotationPresent(Exclusion.class)) {
            paramCheckExclusions.add(initializeExclusion(anno));
         }
      }

      initializeGenericTypeChecks(paramTypes[i], annotatedParamTypes[i], paramChecks);

      final ParameterConfiguration paramCfg = new ParameterConfiguration();
      paramCfgs.add(paramCfg);
      paramCfg.type = paramTypes[i];
      if (paramChecks.size() > 0) {
         paramCfg.checks = paramChecks;
         paramChecks = cf.createList(2); // create a new list for the next parameter having checks
      }
      if (paramCheckExclusions.size() > 0) {
         paramCfg.checkExclusions = paramCheckExclusions;
         paramCheckExclusions = cf.createList(2); // create a new list for the next parameter having check exclusions
      }
   }
   return paramCfgs;
}
 
Example 21
Source Project: graphql-spqr   Source File: DefaultTypeInfoGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public String generateTypeDescription(AnnotatedType type, MessageBundle messageBundle) {
    Optional<String>[] descriptions = new Optional[]{
            Optional.ofNullable(type.getAnnotation(GraphQLUnion.class))
                    .map(GraphQLUnion::description),
            Optional.ofNullable(type.getAnnotation(GraphQLInterface.class))
                    .map(GraphQLInterface::description),
            Optional.ofNullable(type.getAnnotation(GraphQLType.class))
                    .map(GraphQLType::description)
    };
    return messageBundle.interpolate(getFirstNonEmptyOrDefault(descriptions, () -> ""));
}
 
Example 22
Source Project: hottub   Source File: RedefineAnnotations.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void verifyMapFieldTypeAnnotations(Class c)
    throws NoSuchFieldException, NoSuchMethodException {

    Annotation anno;
    AnnotatedType atBase;
    AnnotatedType atParameter;
    atBase = c.getDeclaredField("typeAnnotatedMap").getAnnotatedType();

    anno = atBase.getAnnotations()[0];
    verifyTestAnn(mapTA[0], anno, "map1");
    mapTA[0] = anno;

    atParameter =
        ((AnnotatedParameterizedType) atBase).
        getAnnotatedActualTypeArguments()[0];
    anno = ((AnnotatedWildcardType) atParameter).getAnnotations()[0];
    verifyTestAnn(mapTA[1], anno, "map2");
    mapTA[1] = anno;

    anno =
        ((AnnotatedWildcardType) atParameter).
        getAnnotatedUpperBounds()[0].getAnnotations()[0];
    verifyTestAnn(mapTA[2], anno, "map3");
    mapTA[2] = anno;

    atParameter =
        ((AnnotatedParameterizedType) atBase).
        getAnnotatedActualTypeArguments()[1];
    anno = ((AnnotatedParameterizedType) atParameter).getAnnotations()[0];
    verifyTestAnn(mapTA[3], anno, "map4");
    mapTA[3] = anno;

    anno =
        ((AnnotatedParameterizedType) atParameter).
        getAnnotatedActualTypeArguments()[0].getAnnotations()[0];
    verifyTestAnn(mapTA[4], anno, "map5");
    mapTA[4] = anno;
}
 
Example 23
Source Project: graphql-spqr   Source File: NonNullMapper.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public GraphQLNonNull toGraphQLInputType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
    mappersToSkip.add(this.getClass());
    GraphQLInputType inner = env.operationMapper.toGraphQLInputType(javaType, mappersToSkip, env);
    return inner instanceof GraphQLNonNull ? (GraphQLNonNull) inner : new GraphQLNonNull(inner);
}
 
Example 24
Source Project: graphql-spqr   Source File: MapToListTypeAdapter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(AnnotatedType type) {
    return ClassUtils.isSuperClass(Map.class, type) && !type.isAnnotationPresent(GraphQLScalar.class);
}
 
Example 25
Source Project: graphql-spqr   Source File: AbstractTypeAdapter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(AnnotatedElement element, AnnotatedType type) {
    return supports(type);
}
 
Example 26
Source Project: jdk8u-jdk   Source File: TestTypeResolver.java    License: GNU General Public License v2.0 4 votes vote down vote up
public AnnotatedType[] getAnnotatedBounds() {
    return null; // not used
}
 
Example 27
@Override
public Collection<AnnotatedType> getInterfaces(AnnotatedType type) {
    Map<Class<?>, AnnotatedType> interfaces = new HashMap<>();
    collectInterfaces(type, interfaces);
    return interfaces.values();
}
 
Example 28
Source Project: graphql-spqr   Source File: GraphQLSchemaGenerator.java    License: Apache License 2.0 4 votes vote down vote up
private void checkType(AnnotatedType type) {
    if (type == null) {
        throw TypeMappingException.unknownType();
    }
    checkType(type.getType());
}
 
Example 29
Source Project: graphql-spqr   Source File: InterfaceMapper.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public GraphQLInputObjectType toGraphQLInputType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    return objectTypeMapper.toGraphQLInputType(typeName, javaType, env);
}
 
Example 30
Source Project: graphql-spqr   Source File: ResolverBuilderTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(AnnotatedType type) {
    return ClassUtils.isSuperClass(StrangelyNamedProperties.class, type);
}