Search in sources :

Example 46 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project rest.li by linkedin.

the class ReflectionUtils method walkTypeChain.

private static Type walkTypeChain(final Class<?> target, final Type type, final Map<Type, Type> resolvedTypes) {
    if (type == null) {
        return null;
    }
    Type result;
    if (type instanceof Class) {
        // there is no useful information for us in raw types, so just keep going.
        result = walkParentsTypeChain(target, (Class) type, resolvedTypes);
        if (result != null) {
            return result;
        }
    } else {
        mapTypeParameters((ParameterizedType) type, resolvedTypes);
        Class<?> rawType = (Class) ((ParameterizedType) type).getRawType();
        if (rawType.equals(target)) {
            return type;
        } else {
            result = walkParentsTypeChain(target, rawType, resolvedTypes);
            if (result != null) {
                return result;
            }
        }
    }
    return null;
}
Also used : GenericArrayType(java.lang.reflect.GenericArrayType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type)

Example 47 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project rest.li by linkedin.

the class RestLiAnnotationReader method processCollection.

@SuppressWarnings("unchecked")
private static ResourceModel processCollection(final Class<? extends KeyValueResource<?, ?>> collectionResourceClass, ResourceModel parentResourceModel) {
    Class<?> keyClass;
    Class<? extends RecordTemplate> keyKeyClass = null;
    Class<? extends RecordTemplate> keyParamsClass = null;
    Class<? extends RecordTemplate> valueClass;
    Class<?> complexKeyResourceBase = null;
    // type V and the resource key type is ComplexResourceKey<K,P>
    if (ComplexKeyResource.class.isAssignableFrom(collectionResourceClass)) {
        complexKeyResourceBase = ComplexKeyResource.class;
    } else if (ComplexKeyResourceAsync.class.isAssignableFrom(collectionResourceClass)) {
        complexKeyResourceBase = ComplexKeyResourceAsync.class;
    } else if (ComplexKeyResourceTask.class.isAssignableFrom(collectionResourceClass)) {
        complexKeyResourceBase = ComplexKeyResourceTask.class;
    } else if (ComplexKeyResourcePromise.class.isAssignableFrom(collectionResourceClass)) {
        complexKeyResourceBase = ComplexKeyResourcePromise.class;
    }
    if (complexKeyResourceBase != null) {
        List<Class<?>> kvParams;
        if (complexKeyResourceBase.equals(ComplexKeyResource.class)) {
            kvParams = ReflectionUtils.getTypeArguments(ComplexKeyResource.class, (Class<? extends ComplexKeyResource<?, ?, ?>>) collectionResourceClass);
        } else if (complexKeyResourceBase.equals(ComplexKeyResourceAsync.class)) {
            kvParams = ReflectionUtils.getTypeArguments(ComplexKeyResourceAsync.class, (Class<? extends ComplexKeyResourceAsync<?, ?, ?>>) collectionResourceClass);
        } else if (complexKeyResourceBase.equals(ComplexKeyResourceTask.class)) {
            kvParams = ReflectionUtils.getTypeArguments(ComplexKeyResourceTask.class, (Class<? extends ComplexKeyResourceTask<?, ?, ?>>) collectionResourceClass);
        } else {
            kvParams = ReflectionUtils.getTypeArguments(ComplexKeyResourcePromise.class, (Class<? extends ComplexKeyResourcePromise<?, ?, ?>>) collectionResourceClass);
        }
        keyClass = ComplexResourceKey.class;
        keyKeyClass = kvParams.get(0).asSubclass(RecordTemplate.class);
        keyParamsClass = kvParams.get(1).asSubclass(RecordTemplate.class);
        valueClass = kvParams.get(2).asSubclass(RecordTemplate.class);
    } else // Otherwise, it's a KeyValueResource, whose parameters are resource key and resource
    // value
    {
        List<Type> actualTypeArguments = ReflectionUtils.getTypeArgumentsParametrized(KeyValueResource.class, collectionResourceClass);
        keyClass = ReflectionUtils.getClass(actualTypeArguments.get(0));
        if (RecordTemplate.class.isAssignableFrom(keyClass)) {
            // ComplexResourceKey
            throw new ResourceConfigException("Class '" + collectionResourceClass.getName() + "' should implement 'ComplexKeyResource' as a complex key '" + keyClass.getName() + "' is being used.");
        } else if (TyperefInfo.class.isAssignableFrom(keyClass)) {
            throw new ResourceConfigException("Typeref '" + keyClass.getName() + "' cannot be key type for class '" + collectionResourceClass.getName() + "'.");
        }
        if (keyClass.equals(ComplexResourceKey.class)) {
            @SuppressWarnings("unchecked") Type[] typeArguments = ((ParameterizedType) actualTypeArguments.get(0)).getActualTypeArguments();
            keyKeyClass = ReflectionUtils.getClass(typeArguments[0]).asSubclass(RecordTemplate.class);
            keyParamsClass = ReflectionUtils.getClass(typeArguments[1]).asSubclass(RecordTemplate.class);
        }
        valueClass = ReflectionUtils.getClass(actualTypeArguments.get(1)).asSubclass(RecordTemplate.class);
    }
    ResourceType resourceType = getResourceType(collectionResourceClass);
    RestLiAnnotationData annotationData;
    if (collectionResourceClass.isAnnotationPresent(RestLiCollection.class)) {
        annotationData = new RestLiAnnotationData(collectionResourceClass.getAnnotation(RestLiCollection.class));
    } else if (collectionResourceClass.isAnnotationPresent(RestLiAssociation.class)) {
        annotationData = new RestLiAnnotationData(collectionResourceClass.getAnnotation(RestLiAssociation.class));
    } else {
        throw new ResourceConfigException("No valid annotation on resource class '" + collectionResourceClass.getName() + "'");
    }
    String name = annotationData.name();
    String namespace = annotationData.namespace();
    String keyName;
    if (annotationData.keyName() == null) {
        keyName = name + "Id";
    } else {
        keyName = annotationData.keyName();
    }
    Key primaryKey = buildKey(name, keyName, keyClass, annotationData.typerefInfoClass());
    Set<Key> keys = new HashSet<Key>();
    if (annotationData.keys() == null) {
        keys.add(primaryKey);
    } else {
        keys.addAll(buildKeys(name, annotationData.keys()));
    }
    Class<?> parentResourceClass = annotationData.parent().equals(RestAnnotations.ROOT.class) ? null : annotationData.parent();
    ResourceModel collectionModel = new ResourceModel(primaryKey, keyKeyClass, keyParamsClass, keys, valueClass, collectionResourceClass, parentResourceClass, name, resourceType, namespace);
    collectionModel.setParentResourceModel(parentResourceModel);
    addResourceMethods(collectionResourceClass, collectionModel);
    log.info("Processed collection resource '" + collectionResourceClass.getName() + "'");
    return collectionModel;
}
Also used : RestLiAssociation(com.linkedin.restli.server.annotations.RestLiAssociation) ComplexKeyResourceTask(com.linkedin.restli.server.resources.ComplexKeyResourceTask) ComplexKeyResource(com.linkedin.restli.server.resources.ComplexKeyResource) ParameterizedType(java.lang.reflect.ParameterizedType) RecordTemplate(com.linkedin.data.template.RecordTemplate) ComplexKeyResourcePromise(com.linkedin.restli.server.resources.ComplexKeyResourcePromise) HashSet(java.util.HashSet) ComplexKeyResourceAsync(com.linkedin.restli.server.resources.ComplexKeyResourceAsync) TyperefInfo(com.linkedin.data.template.TyperefInfo) HasTyperefInfo(com.linkedin.data.template.HasTyperefInfo) ParameterizedType(java.lang.reflect.ParameterizedType) InterfaceType(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor.InterfaceType) Type(java.lang.reflect.Type) ResourceConfigException(com.linkedin.restli.server.ResourceConfigException) AlternativeKey(com.linkedin.restli.server.annotations.AlternativeKey) ComplexResourceKey(com.linkedin.restli.common.ComplexResourceKey) Key(com.linkedin.restli.server.Key) AssocKey(com.linkedin.restli.server.annotations.AssocKey)

Example 48 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project rest.li by linkedin.

the class RestLiAnnotationReader method addFinderResourceMethod.

private static void addFinderResourceMethod(final ResourceModel model, final Method method) {
    Finder finderAnno = method.getAnnotation(Finder.class);
    if (finderAnno == null) {
        return;
    }
    String queryType = finderAnno.value();
    List<Parameter<?>> queryParameters = getParameters(model, method, ResourceMethod.FINDER);
    if (queryType != null) {
        Class<? extends RecordTemplate> metadataType = null;
        final Class<?> returnClass = getLogicalReturnClass(method);
        if (CollectionResult.class.isAssignableFrom(returnClass)) {
            final List<Class<?>> typeArguments = ReflectionUtils.getTypeArguments(CollectionResult.class, returnClass.asSubclass(CollectionResult.class));
            final Class<?> metadataClass;
            if (typeArguments == null || typeArguments.get(1) == null) {
                // the return type may leave metadata type as parameterized and specify in runtime
                metadataClass = ((Class<?>) ((ParameterizedType) getLogicalReturnType(method)).getActualTypeArguments()[1]);
            } else {
                metadataClass = typeArguments.get(1);
            }
            if (!metadataClass.equals(NoMetadata.class)) {
                metadataType = metadataClass.asSubclass(RecordTemplate.class);
            }
        }
        DataMap annotationsMap = ResourceModelAnnotation.getAnnotationsMap(method.getAnnotations());
        addDeprecatedAnnotation(annotationsMap, method);
        ResourceMethodDescriptor finderMethodDescriptor = ResourceMethodDescriptor.createForFinder(method, queryParameters, queryType, metadataType, getInterfaceType(method), annotationsMap);
        validateFinderMethod(finderMethodDescriptor, model);
        if (!Modifier.isPublic(method.getModifiers())) {
            throw new ResourceConfigException(String.format("Resource '%s' contains non-public finder method '%s'.", model.getName(), method.getName()));
        }
        model.addResourceMethodDescriptor(finderMethodDescriptor);
    }
}
Also used : NoMetadata(com.linkedin.restli.server.NoMetadata) Finder(com.linkedin.restli.server.annotations.Finder) DataMap(com.linkedin.data.DataMap) ParameterizedType(java.lang.reflect.ParameterizedType) CollectionResult(com.linkedin.restli.server.CollectionResult) RecordTemplate(com.linkedin.data.template.RecordTemplate) ResourceConfigException(com.linkedin.restli.server.ResourceConfigException)

Example 49 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project JessMA by ldcsaa.

the class DaoInjectFilter method parseSessionMgr.

@SuppressWarnings("rawtypes")
private void parseSessionMgr(ActionExecutor executor, String mgrName, DaoAttr daoAttr) throws Exception {
    if (GeneralHelper.isStrEmpty(mgrName))
        daoAttr.mgr = null;
    else {
        SessionMgr mgr = AppConfig.getSessionManager(mgrName);
        if (mgr != null)
            daoAttr.mgr = mgr;
        else
            throwParseException(executor, daoAttr.name, String.format("Session Manager named '%s' not found", mgrName));
    }
    if (daoAttr.mgr != null) {
        Class<?> clazz = daoAttr.daoClass;
        while (clazz.getSuperclass() != AbstractFacade.class) clazz = clazz.getSuperclass();
        Type type = clazz.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Class<?> paramClazz = (Class<?>) (((ParameterizedType) type).getActualTypeArguments()[0]);
            if (!paramClazz.isAssignableFrom(daoAttr.mgr.getClass())) {
                String cause = String.format("DAO class (%s) does not match SessionMgr '%s' (%s)", daoAttr.daoClass.getName(), mgrName, daoAttr.mgr.getClass().getName());
                throwParseException(executor, daoAttr.name, cause);
            }
        }
    }
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) SessionMgr(org.jessma.dao.SessionMgr)

Example 50 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project siena by mandubian.

the class ClassInfo method buildMany.

private void buildMany(Field field, Class<?> c) {
    Class<?> type = field.getType();
    ParameterizedType pt = (ParameterizedType) field.getGenericType();
    Class<?> cl = (Class<?>) pt.getActualTypeArguments()[0];
    Aggregated agg = field.getAnnotation(Aggregated.class);
    Filter filter = field.getAnnotation(Filter.class);
    Owned related = field.getAnnotation(Owned.class);
    if ((agg != null && filter != null) || (agg != null && related != null)) {
        throw new SienaException("Found Many<T> field " + c.getName() + "." + field.getName() + "with @Filter+@Owned or @Filter+@Owned: this is not authorized");
    }
    if (agg != null) {
        try {
            Map<FieldMapKeys, Object> fieldMap = new HashMap<FieldMapKeys, Object>();
            fieldMap.put(FieldMapKeys.CLASS, cl);
            fieldMap.put(FieldMapKeys.MODE, RelationMode.AGGREGATION);
            manyFieldMap.put(field, fieldMap);
            aggregatedFields.add(field);
            hasAggregatedFields = true;
        } catch (Exception e) {
            throw new SienaException(e);
        }
    } else if (filter != null) {
        try {
            Field filterField = cl.getField(filter.value());
            if (filterField == null) {
                throw new SienaException("@Filter error: Couldn't find field " + filter.value() + "in class " + cl.getName());
            }
            Map<FieldMapKeys, Object> fieldMap = new HashMap<FieldMapKeys, Object>();
            fieldMap.put(FieldMapKeys.CLASS, cl);
            fieldMap.put(FieldMapKeys.MODE, RelationMode.RELATION);
            fieldMap.put(FieldMapKeys.FIELD, filterField);
            fieldMap.put(FieldMapKeys.FILTER, filter.value());
            manyFieldMap.put(field, fieldMap);
            ownedFields.add(field);
            hasOwnedFields = true;
        } catch (Exception e) {
            throw new SienaException(e);
        }
    } else if (related != null) {
        String as = related.mappedBy();
        // if related.as not specified, tries to find the first field with this type
        if ("".equals(as) || as == null) {
            ClassInfo fieldInfo = ClassInfo.getClassInfo(cl);
            Field f = fieldInfo.getFirstFieldFromType(clazz);
            if (f == null) {
                throw new SienaException("@Owned without 'as' attribute and no field of type " + clazz.getName() + "found in class " + type.getName());
            }
            as = ClassInfo.getSimplestColumnName(f);
        }
        try {
            Field asField = cl.getField(as);
            if (asField == null) {
                throw new SienaException("@Filter error: Couldn't find field " + as + "in class " + cl.getName());
            }
            Map<FieldMapKeys, Object> fieldMap = new HashMap<FieldMapKeys, Object>();
            fieldMap.put(FieldMapKeys.CLASS, cl);
            fieldMap.put(FieldMapKeys.MODE, RelationMode.RELATION);
            fieldMap.put(FieldMapKeys.FIELD, asField);
            fieldMap.put(FieldMapKeys.FILTER, as);
            manyFieldMap.put(field, fieldMap);
            ownedFields.add(field);
            hasOwnedFields = true;
        } catch (Exception e) {
            throw new SienaException(e);
        }
    }
    allExtendedFields.add(field);
}
Also used : Aggregated(siena.core.Aggregated) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ParameterizedType(java.lang.reflect.ParameterizedType) Field(java.lang.reflect.Field) Owned(siena.core.Owned) InheritFilter(siena.core.InheritFilter) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Aggregations

ParameterizedType (java.lang.reflect.ParameterizedType)704 Type (java.lang.reflect.Type)532 GenericArrayType (java.lang.reflect.GenericArrayType)226 WildcardType (java.lang.reflect.WildcardType)182 TypeVariable (java.lang.reflect.TypeVariable)137 ArrayList (java.util.ArrayList)94 Method (java.lang.reflect.Method)71 Test (org.junit.Test)59 List (java.util.List)55 Field (java.lang.reflect.Field)49 Map (java.util.Map)47 HashMap (java.util.HashMap)42 Collection (java.util.Collection)26 MediaType (javax.ws.rs.core.MediaType)23 Annotation (java.lang.annotation.Annotation)18 HashSet (java.util.HashSet)13 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)13 ImmutableList (com.google.common.collect.ImmutableList)12 TypeLiteral (com.google.inject.TypeLiteral)12 IOException (java.io.IOException)11