Java Code Examples for com.googlecode.gentyref.GenericTypeReflector

The following examples show how to use com.googlecode.gentyref.GenericTypeReflector. 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
Source Project: elepy   Source File: ContextKey.java    License: Apache License 2.0 6 votes vote down vote up
static ContextKey<?> forAnnotatedElement(AnnotatedElement element) {
    final Class<?> returnType = ReflectionUtils.returnTypeOf(element);

    if (Crud.class.equals(returnType)) {
        return getTypeArgument(toParameterizedType(element));
    } else if (Crud.class.isAssignableFrom(returnType)) {
        final var exactSuperType = (ParameterizedType) GenericTypeReflector
                .getExactSuperType(
                        getGenericType(element),
                        Crud.class);

        return getTypeArgument(exactSuperType);
    } else {
        return new ContextKey<>(returnType, null);
    }
}
 
Example 2
Source Project: glitr   Source File: CustomFieldArgumentsFunc.java    License: MIT License 6 votes vote down vote up
@Override
public List<GraphQLArgument> call(@Nullable Field field, Method method, Class declaringClass, Annotation annotation) {
    // if same annotation is detected on both field and getter we fail. Only one annotation is allowed. We can talk about having precedence logic later.
    if (method.isAnnotationPresent(annotation.annotationType()) && field != null && field.isAnnotationPresent(annotation.annotationType())) {
        throw new IllegalArgumentException("Conflict: GraphQL Annotations can't be added to both field and getter. Pick one for "+
                                                   annotation.annotationType() + " on " + field.getName() + " and " + method.getName());
    }

    Type returnType = GenericTypeReflector.getExactReturnType(method, declaringClass);
    if (returnType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) returnType;

        Type containerType = parameterizedType.getRawType();
        if (Collection.class.isAssignableFrom((Class) containerType)) {
            List<GraphQLArgument> arguments = new ArrayList<>();
            arguments.add(newArgument().name(GlitrForwardPagingArguments.FIRST).type(GraphQLInt).build());
            arguments.add(newArgument().name(GlitrForwardPagingArguments.AFTER).type(GraphQLString).build());
            return arguments;
        }
    }

    return new ArrayList<>();
}
 
Example 3
Source Project: rest-schemagen   Source File: LinkCreator.java    License: Apache License 2.0 6 votes vote down vote up
private void setQueryParameters(final UriBuilder uriBuilder, Scope scope, Object[] parameters) {
    Type[] realParamTypes = GenericTypeReflector.getExactParameterTypes(scope
            .getInvokedMethod(), scope.getInvokedClass());
    visitAnnotations((parameter, parameterIndex, annotation) -> {
        if (annotation instanceof QueryParam && parameter != null) {
            final String parameterName = ((QueryParam) annotation).value();
            if (parameter instanceof Iterable) {
                uriBuilder.queryParam(parameterName, Iterables.toArray((Iterable) parameter, Object.class));
            } else {
                uriBuilder.queryParam(parameterName, parameter.toString());
            }
        } else if (annotation instanceof BeanParam && parameter != null) {
            if (realParamTypes[parameterIndex] instanceof Class<?>) {
                BeanParamExtractor beanParamExtractor = new BeanParamExtractor();
                Map<String, Object[]> queryParameter = beanParamExtractor.getQueryParameters(
                        parameter);
                queryParameter.forEach((uriBuilder::queryParam));
            }
        }
    }, scope.getInvokedMethod(), parameters);
}
 
Example 4
Source Project: zstack   Source File: FieldUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static GenericType inferCollection(Type type) {
    CollectionGenericType ret = new CollectionGenericType();
    Type valueType = GenericTypeReflector.getTypeParameter(type, Collection.class.getTypeParameters()[0]);
    ret.isInferred = valueType != null;
    if (valueType == null) {
        return ret;
    }

    ret.valueType = GenericTypeReflector.erase(valueType);
    if (Map.class.isAssignableFrom(ret.valueType)) {
        ret.nestedGenericValue = inferMap(valueType);
    } else if (Collection.class.isAssignableFrom(ret.valueType)) {
        ret.nestedGenericValue = inferCollection(valueType);
    }
    return ret;
}
 
Example 5
Source Project: elepy   Source File: ReflectionUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Class<?> returnTypeOf(AnnotatedElement field) {
    if (field instanceof AnnotatedType) {
        return (Class) ((AnnotatedType) field).getType();
    }
    if (field instanceof Parameter) {
        return GenericTypeReflector.erase(((Parameter) field).getType());
    }
    return (field instanceof Field) ? ((Field) field).getType() : ((Method) field).getReturnType();
}
 
Example 6
Source Project: glitr   Source File: GraphQLInputObjectTypeFactory.java    License: MIT License 5 votes vote down vote up
private GraphQLInputObjectField getGraphQLInputObjectField(Pair<Method, Class> pair) {
    Method method = pair.getLeft();
    Class declaringClass = pair.getRight();

    String name = ReflectionUtil.sanitizeMethodName(method.getName());
    String description = ReflectionUtil.getDescriptionFromAnnotatedElement(method);
    if (description != null && description.equals(GlitrDescription.DEFAULT_DESCRIPTION)) {
        description = ReflectionUtil.getDescriptionFromAnnotatedField(declaringClass, method);
    }

    GraphQLType graphQLType = typeRegistry.convertToGraphQLInputType(GenericTypeReflector.getExactReturnType(method, declaringClass), name);
    if (!(graphQLType instanceof GraphQLInputType)) {
        throw new GlitrException("Failed to create GraphQLInputType [" + graphQLType.getName() + "] in class [" + declaringClass.getName() + "]. " +
                "This is most often the result of a GraphQLOutputType of the same name already existing as input types require unique names. " +
                "Please make sure the name used for this input does not match that of another domain class.");
    }
    GraphQLInputType graphQLInputType = (GraphQLInputType) graphQLType;

    boolean nullable = ReflectionUtil.isAnnotatedElementNullable(method);
    if (nullable) { // check the field too
        try {
            Field field = declaringClass.getDeclaredField(name);
            nullable = ReflectionUtil.isAnnotatedElementNullable(field);
        } catch (NoSuchFieldException e) {
            // do nothing
        }
    }

    if (!nullable || name.equals("id")) {
        graphQLInputType = new GraphQLNonNull(graphQLInputType);
    }

    return newInputObjectField()
            .type(graphQLInputType)
            .name(name)
            .description(description)
            // TODO: add default value feature, via annotation?
            .build();
}
 
Example 7
Source Project: glitr   Source File: TypeRegistry.java    License: MIT License 5 votes vote down vote up
public GraphQLOutputType retrieveGraphQLOutputType(Class declaringClass, Method method) {
    GraphQLOutputType graphQLOutputType;
    String name = ReflectionUtil.sanitizeMethodName(method.getName());

    graphQLOutputType = getGraphQLOutputTypeFromAnnotationsOnGetter(declaringClass, method);
    graphQLOutputType = getGraphQLOutputTypeFromAnnotationsOnField(declaringClass, method, graphQLOutputType, name);

    // default OutputType
    if (graphQLOutputType == null) {
        graphQLOutputType = (GraphQLOutputType) convertToGraphQLOutputType(GenericTypeReflector.getExactReturnType(method, declaringClass), name);

        // is this an optional field
        boolean nullable = ReflectionUtil.isAnnotatedElementNullable(method);
        if (nullable) { // check the field too
            try {
                Field field = declaringClass.getDeclaredField(name);
                nullable = ReflectionUtil.isAnnotatedElementNullable(field);
            } catch (NoSuchFieldException e) {
                // do nothing
            }
        }

        if (!nullable || name.equals("id")) {
            graphQLOutputType = new GraphQLNonNull(graphQLOutputType);
        }
    }

    return graphQLOutputType;
}
 
Example 8
Source Project: rest-schemagen   Source File: GenericClass.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GenericType<?> getContainedType() {
    if (getRawType().isArray()) {
        return GenericType.of(GenericTypeReflector.getArrayComponentType(getRawType()),
                getRawType().getComponentType());
    }
    throw new IllegalAccessError("GenericClass " + getSimpleName() + " has no contained type");
}
 
Example 9
@Test
public void testGetContainedType() throws NoSuchFieldException {
    final Field field = getClass().getDeclaredField("doubleList");
    final Type type = GenericTypeReflector.getExactFieldType(field, getClass());

    @SuppressWarnings("rawtypes")
    final GenericParameterizedType<List> genericType = new GenericParameterizedType<>(
            (ParameterizedType) type, List.class);

    final GenericType<?> containedType1 = genericType.getContainedType();
    assertThat(containedType1.getRawType()).isEqualTo(List.class);

    final GenericType<?> containedType2 = containedType1.getContainedType();
    assertThat(containedType2.getRawType()).isEqualTo(Double.class);
}
 
Example 10
@Test
public void testGetContainedTypeWithGenericTypeParameter() throws NoSuchFieldException {
    final Class<?> superclass = getClass().getSuperclass();
    final Field field = superclass.getDeclaredField("object");
    final Type type = GenericTypeReflector.getExactFieldType(field, getClass());

    final GenericType<?> genericType = GenericType.of(type);

    assertThat(genericType.getRawType()).isEqualTo(Boolean.class);
}
 
Example 11
Source Project: zstack   Source File: FieldUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static GenericType inferMap(Type type) {
    MapGenericType ret = new MapGenericType();
    Type keyType = GenericTypeReflector.getTypeParameter(type, Map.class.getTypeParameters()[0]);
    Type valueType = GenericTypeReflector.getTypeParameter(type, Map.class.getTypeParameters()[1]);
    ret.isInferred = keyType != null && valueType != null;
    if (keyType == null || valueType == null) {
        return ret;
    }

    ret.keyType = GenericTypeReflector.erase(keyType);
    ret.valueType = GenericTypeReflector.erase(valueType);
    if (!ret.isInferred) {
        return ret;
    }

    if (Map.class.isAssignableFrom(ret.keyType)) {
        ret.nestedGenericKey = inferMap(keyType);
    } else if (Collection.class.isAssignableFrom(ret.keyType)) {
        ret.nestedGenericKey = inferCollection(keyType);
    }

    if (Map.class.isAssignableFrom(ret.valueType)) {
        ret.nestedGenericValue = inferMap(valueType);
    } else if (Collection.class.isAssignableFrom(ret.valueType)) {
        ret.nestedGenericValue = inferCollection(valueType);
    }

    return ret;
}
 
Example 12
Source Project: zstack   Source File: FieldUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static GenericType inferGenericTypeOnMapOrCollectionField(Field field) {
    Class owner = field.getDeclaringClass();
    Type t = GenericTypeReflector.getExactFieldType(field, owner);
    if (Map.class.isAssignableFrom(field.getType())) {
        return inferMap(t);
    } else if (Collection.class.isAssignableFrom(field.getType())) {
        return inferCollection(t);
    } else {
        throw new IllegalArgumentException(String.format("field is type of %s, only Map or Collection field can be inferred", field.getType().getName()));
    }
}
 
Example 13
Source Project: flow   Source File: ModelEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the decoded type of this encoder.
 *
 * @return the application type
 */
@SuppressWarnings("unchecked")
default Class<D> getDecodedType() {
    Type type = GenericTypeReflector.getTypeParameter(this.getClass(),
            ModelEncoder.class.getTypeParameters()[0]);
    if (type instanceof Class<?>) {
        return (Class<D>) GenericTypeReflector.erase(type);
    }
    throw new InvalidTemplateModelException(String.format(
            "Could not detect the model type of %s '%s'. "
                    + "The method 'getDecodedType' needs to be overridden manually.",
            ModelEncoder.class.getSimpleName(), this.getClass().getName()));
}
 
Example 14
Source Project: flow   Source File: ModelEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the encoded type of this encoder.
 *
 * @return the model type
 */
@SuppressWarnings("unchecked")
default Class<E> getEncodedType() {
    Type type = GenericTypeReflector.getTypeParameter(this.getClass(),
            ModelEncoder.class.getTypeParameters()[1]);
    if (type instanceof Class<?>) {
        return (Class<E>) GenericTypeReflector.erase(type);
    }
    throw new InvalidTemplateModelException(String.format(
            "Could not detect the presentation type of %s '%s'. "
                    + "The method 'getEncodedType' needs to be overridden manually.",
            ModelEncoder.class.getSimpleName(), this.getClass().getName()));
}
 
Example 15
Source Project: flow   Source File: ListModelType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <C> ComplexModelType<C> cast(Class<C> proxyType) {
    if (getItemType() instanceof ListModelType<?>
            && GenericTypeReflector.erase(proxyType).equals(List.class)) {
        return (ComplexModelType<C>) this;
    }
    throw new IllegalArgumentException(
            "Got " + proxyType + ", expected list type");

}
 
Example 16
Source Project: flow   Source File: ClassFinder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> Set<Class<? extends T>> getSubTypesOf(Class<T> type) {
    return this.classes.stream()
            .filter(cl -> GenericTypeReflector.isSuperType(type, cl)
                    && !type.equals(cl))
            .map(cl -> (Class<T>) cl).collect(Collectors.toSet());
}
 
Example 17
Source Project: flow   Source File: RouteRegistryInitializer.java    License: Apache License 2.0 5 votes vote down vote up
private boolean handleAmbiguousRoute(RouteConfiguration routeConfiguration,
        Class<? extends Component> configuredNavigationTarget,
        Class<? extends Component> navigationTarget) {
    if (GenericTypeReflector.isSuperType(navigationTarget,
            configuredNavigationTarget)) {
        return true;
    } else if (GenericTypeReflector.isSuperType(configuredNavigationTarget,
            navigationTarget)) {
        routeConfiguration.removeRoute(configuredNavigationTarget);
        routeConfiguration.setAnnotatedRoute(navigationTarget);
        return true;
    }
    return false;
}
 
Example 18
Source Project: flow   Source File: WebComponentExporterAwareValidator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Optional<String> handleNonRouterLayout(Class<?> clazz) {
    if (WebComponentExporter.class
            .isAssignableFrom(GenericTypeReflector.erase(clazz))) {
        return Optional.empty();
    }
    return Optional.of(String.format(
            "Class '%s' contains '%s', but it is not a router "
                    + "layout/top level route/web component.",
            clazz.getName(), getClassAnnotations(clazz)));
}
 
Example 19
Source Project: flow   Source File: AbstractServerHandlers.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private final Class<T> getType() {
    Type type = GenericTypeReflector.getTypeParameter(
            getClass().getGenericSuperclass(),
            getClass().getSuperclass().getTypeParameters()[0]);
    if (type instanceof Class || type instanceof ParameterizedType) {
        return (Class<T>) GenericTypeReflector.erase(type);
    }
    throw new IllegalStateException(getExceptionMessage(type));
}
 
Example 20
Source Project: flow   Source File: ReflectTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the Class type for the generic interface class extended by given
 * class if exists.
 *
 * @param clazz
 *            class that should extend interface
 * @param interfaceType
 *            class type of interface to get generic for
 * @return Class if found else {@code null}
 */
public static Class<?> getGenericInterfaceType(Class<?> clazz,
        Class<?> interfaceType) {
    Type type = GenericTypeReflector.getTypeParameter(clazz,
            interfaceType.getTypeParameters()[0]);

    if (type instanceof Class || type instanceof ParameterizedType) {
        return GenericTypeReflector.erase(type);
    }
    return null;
}
 
Example 21
Source Project: flow   Source File: Composite.java    License: Apache License 2.0 5 votes vote down vote up
private static Class<? extends Component> findContentType(
        Class<? extends Composite<?>> compositeClass) {
    Type type = GenericTypeReflector.getTypeParameter(
            compositeClass.getGenericSuperclass(),
            Composite.class.getTypeParameters()[0]);
    if (type instanceof Class || type instanceof ParameterizedType) {
        return GenericTypeReflector.erase(type).asSubclass(Component.class);
    }
    throw new IllegalStateException(getExceptionMessage(type));
}
 
Example 22
Source Project: flow   Source File: AbstractTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the type of the template model to use with with this template.
 *
 * @return the model type, not <code>null</code>
 */
@SuppressWarnings("unchecked")
protected Class<? extends M> getModelType() {
    Type type = GenericTypeReflector.getTypeParameter(
            getClass().getGenericSuperclass(),
            AbstractTemplate.class.getTypeParameters()[0]);
    if (type instanceof Class || type instanceof ParameterizedType) {
        return (Class<M>) GenericTypeReflector.erase(type);
    }
    throw new IllegalStateException(getExceptionMessage(type));
}
 
Example 23
Source Project: flow   Source File: AbstractSinglePropertyField.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Class<T> findElementPropertyTypeFromTypeParameter(
        Class<?> hasValueClass) {
    return (Class<T>) GenericTypeReflector
            .erase(GenericTypeReflector.getTypeParameter(hasValueClass,
                    HasValue.class.getTypeParameters()[1]));
}
 
Example 24
Source Project: flow   Source File: ParameterDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the parameter type class.
 *
 * @param navigationTarget
 *            navigation target to get parameter type class for
 * @return parameter type class
 */
public static Class<?> getClassType(Class<?> navigationTarget) {
    Type type = GenericTypeReflector.getTypeParameter(navigationTarget,
            HasUrlParameter.class.getTypeParameters()[0]);
    if (!(type instanceof Class<?>)) {
        throw new IllegalArgumentException(String.format(
                "Parameter type of the given navigationTarget '%s' could not be resolved.",
                navigationTarget.getName()));
    }
    return GenericTypeReflector.erase(type);
}
 
Example 25
Source Project: flow   Source File: AbstractNodeTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void assertMethodsReturnType(Class<? extends Node<?>> clazz,
        Set<String> ignore) {
    for (Method method : clazz.getMethods()) {
        if (method.getDeclaringClass().equals(Object.class)) {
            continue;
        }
        if (!Modifier.isPublic(method.getModifiers())) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        if (method.isBridge()) {
            continue;
        }
        if (method.getName().startsWith("get")
                || method.getName().startsWith("has")
                || method.getName().startsWith("is")
                || ignore.contains(method.getName())) {
            // Ignore
        } else {
            // Setters and such
            Type returnType = GenericTypeReflector
                    .getExactReturnType(method, clazz);
            Assert.assertEquals(
                    "Method " + method.getName()
                            + " has invalid return type",
                    clazz, returnType);
        }
    }
}
 
Example 26
Source Project: flow   Source File: Binder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Binds {@code property} with {@code propertyType} to the field in the
 * {@code objectWithMemberFields} instance using {@code memberField} as a
 * reference to a member.
 *
 * @param objectWithMemberFields
 *            the object that contains (Java) member fields to build and
 *            bind
 * @param memberField
 *            reference to a member field to bind
 * @param property
 *            property name to bind
 * @param propertyType
 *            type of the property
 * @return {@code true} if property is successfully bound
 */
private boolean bindProperty(Object objectWithMemberFields,
        Field memberField, String property, Class<?> propertyType) {
    Type valueType = GenericTypeReflector.getTypeParameter(
            memberField.getGenericType(),
            HasValue.class.getTypeParameters()[1]);
    if (valueType == null) {
        throw new IllegalStateException(String.format(
                "Unable to detect value type for the member '%s' in the "
                        + "class '%s'.",
                memberField.getName(),
                objectWithMemberFields.getClass().getName()));
    }
    if (propertyType.equals(GenericTypeReflector.erase(valueType))) {
        HasValue<?, ?> field;
        // Get the field from the object
        try {
            field = (HasValue<?, ?>) ReflectTools.getJavaFieldValue(
                    objectWithMemberFields, memberField, HasValue.class);
        } catch (IllegalArgumentException | IllegalAccessException
                | InvocationTargetException e) {
            // If we cannot determine the value, just skip the field
            return false;
        }
        if (field == null) {
            field = makeFieldInstance(
                    (Class<? extends HasValue<?, ?>>) memberField
                            .getType());
            initializeField(objectWithMemberFields, memberField, field);
        }
        forField(field).bind(property);
        return true;
    } else {
        throw new IllegalStateException(String.format(
                "Property type '%s' doesn't "
                        + "match the field type '%s'. "
                        + "Binding should be configured manually using converter.",
                propertyType.getName(), valueType.getTypeName()));
    }
}
 
Example 27
Source Project: glitr   Source File: GraphQLInterfaceTypeFactory.java    License: MIT License 4 votes vote down vote up
private GraphQLFieldDefinition getGraphQLFieldDefinition(Class clazz, Method method) {
    String name = ReflectionUtil.sanitizeMethodName(method.getName());
    String description = ReflectionUtil.getDescriptionFromAnnotatedElement(method);
    if (description != null && description.equals(GlitrDescription.DEFAULT_DESCRIPTION)) {
        description = ReflectionUtil.getDescriptionFromAnnotatedField(clazz, method);
    }

    Type fieldType = GenericTypeReflector.getExactReturnType(method, clazz);
    GraphQLType type = typeRegistry.convertToGraphQLOutputType(fieldType, name, true);
    if (type instanceof GraphQLTypeReference) {
        typeRegistry.getRegistry().putIfAbsent((Class) fieldType, type);
    }

    boolean nullable = ReflectionUtil.isAnnotatedElementNullable(method);
    if (nullable) { // check the field too
        try {
            Field field = clazz.getDeclaredField(name);
            nullable = ReflectionUtil.isAnnotatedElementNullable(field);
        } catch (NoSuchFieldException e) {
            // do nothing
        }
    }

    if (!nullable || name.equals("id")) {
        type = new GraphQLNonNull(type);
    }

    Optional<GlitrQueryComplexity> glitrQueryComplexity = ReflectionUtil.getAnnotationOfMethodOrField(clazz, method, GlitrQueryComplexity.class);
    Set<GlitrMetaDefinition> metaDefinitions = new HashSet<>();
    glitrQueryComplexity.ifPresent(queryComplexity -> {
        metaDefinitions.add(new GlitrMetaDefinition(COMPLEXITY_FORMULA_KEY, queryComplexity.value()));
        metaDefinitions.add(new GlitrMetaDefinition(COMPLEXITY_IGNORE_KEY, queryComplexity.ignore()));
    });

    Optional<GlitrDeprecated> glitrDeprecated = ReflectionUtil.getAnnotationOfMethodOrField(clazz, method, GlitrDeprecated.class);

    codeRegistryBuilder.dataFetcher(coordinates(clazz.getSimpleName(), name), new PropertyDataFetcher(name));

    return newFieldDefinition()
            .name(name)
            .description(description)
            .type((GraphQLOutputType) type)
            .definition(new GlitrFieldDefinition(name, metaDefinitions))
            .deprecate(glitrDeprecated.map(GlitrDeprecated::value).orElse(null))
            .build();
}
 
Example 28
Source Project: rest-schemagen   Source File: ObjectContext.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <U> ObjectContext<U> forField(Field field) {
    final GenericType<U> fieldType = GenericType.of(GenericTypeReflector.getExactFieldType(
            field, getType()), (Class<U>) field.getType());
    final ObjectContextBuilder<U> builder = ObjectContext.buildFor(fieldType);

    T defaultValue = getDefaultValue();
    if (defaultValue != null) {
        builder.withDefaultValue(getFieldValue(field, defaultValue));
    }

    List<T> allowedValues = getAllowedValues();
    if (allowedValues != null && !fieldType.getRawType().isPrimitive()) {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        builder.withAllowedValues(allowedValues.stream()
                .filter(Objects::nonNull)
                .flatMap(value -> (Stream<U>) addToAllowedValues(field, value))
                .collect(Collectors.toList())
        );
    }

    if (isRequired(field)) {
        builder.withIsRequired(true);
    }

    determineConstraints(Size.class, field, SizeConstraints::new)
            .ifPresent(builder::withSizeConstraints);

    determineConstraints(Pattern.class, field, Pattern::regexp)
            .ifPresent(builder::withPattern);

    builder.withValueConstraints(new ValueConstraints(
            determineConstraints(Max.class, field, Max::value),
            determineConstraints(Min.class, field, Min::value)));

    final PropertySchema schemaGenerator = field.getAnnotation(PropertySchema.class);
    if (schemaGenerator != null) {
        builder.withSchemaGenerator(schemaGenerator.schemaGenerator());
    }

    return builder.build();
}
 
Example 29
Source Project: rest-schemagen   Source File: Scope.java    License: Apache License 2.0 4 votes vote down vote up
public Type[] getParameterTypes() {
    return GenericTypeReflector.getExactParameterTypes(invokedMethod, invokedClass);
}
 
Example 30
Source Project: rest-schemagen   Source File: Scope.java    License: Apache License 2.0 4 votes vote down vote up
public Type getReturnType() {
    return GenericTypeReflector.getExactReturnType(invokedMethod, invokedClass);
}