java.lang.reflect.AnnotatedType Java Examples

The following examples show how to use java.lang.reflect.AnnotatedType. 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
Source File: ClassUtils.java    From graphql-spqr with 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 #2
Source File: ResolutionEnvironment.java    From graphql-spqr with 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 #3
Source File: PublicResolverBuilder.java    From graphql-spqr with 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 #4
Source File: ClassUtils.java    From graphql-spqr with 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 #5
Source File: GetAnnotatedSuperclass.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 #6
Source File: RedefineAnnotations.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 #7
Source File: GetAnnotatedSuperclass.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
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 #8
Source File: JTypeVariable.java    From typescript-generator with 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 #9
Source File: DefaultTypeInfoGenerator.java    From graphql-spqr with 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 #10
Source File: AnonymousExtendsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 #11
Source File: AnnotatedArgumentBuilder.java    From graphql-spqr with 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 #12
Source File: AnnotationsConfigurer.java    From oval with 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 #13
Source File: DerivedTypeRegistry.java    From graphql-spqr with 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 #14
Source File: RedefineAnnotations.java    From hottub with 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 #15
Source File: ArrayAdapter.java    From graphql-spqr with 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 #16
Source File: TypeInferenceTest.java    From graphql-spqr with 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 #17
Source File: RedefineAnnotations.java    From TencentKona-8 with 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 #18
Source File: MonoAdapter.java    From graphql-spqr-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: ArgumentInjectorParams.java    From graphql-spqr with 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 #20
Source File: TypeInferenceTest.java    From graphql-spqr with 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 #21
Source File: RedefineAnnotations.java    From jdk8u60 with 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 #22
Source File: AbstractResolverBuilder.java    From graphql-spqr with 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 #23
Source File: ResolutionEnvironment.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public List<AnnotatedType> getDerived(AnnotatedType type) {
    return derivedTypes.getDerived(type);
}
 
Example #24
Source File: ClassUtils.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public static <T> T instance(AnnotatedType type) {
    return instance(getRawType(type.getType()));
}
 
Example #25
Source File: JacksonValueMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
ElementFactory(AnnotatedType type, TypeTransformer typeTransformer) {
    this.type = type;
    this.transformer = typeTransformer;
}
 
Example #26
Source File: SuperTypeBasedInterfaceStrategy.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supportsInterface(AnnotatedType inter) {
    Class<?> raw = ClassUtils.getRawType(inter.getType());
    return mappedTypes.stream().anyMatch(type -> type.isAssignableFrom(raw));
}
 
Example #27
Source File: StreamToCollectionTypeAdapter.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public List<AnnotatedType> getDerivedTypes(AnnotatedType streamType) {
    return Collections.singletonList(getElementType(streamType));
}
 
Example #28
Source File: Union4.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public Union4(String name, String description, List<AnnotatedType> javaTypes) {
    super(name, description, javaTypes);
}
 
Example #29
Source File: StubClass.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
public AnnotatedType api()
{
  return _annType;
}
 
Example #30
Source File: ResolutionEnvironment.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T, S> S convert(T output, AnnotatedElement element, AnnotatedType type) {
    OutputConverter<T, S> outputConverter = converters.getOutputConverter(element, type);
    return outputConverter == null ? (S) output : outputConverter.convertOutput(output, type, this);
}