Search in sources :

Example 1 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project camel by apache.

the class CdiCamelExtension method beans.

private void beans(@Observes ProcessBean<?> pb, BeanManager manager) {
    cdiBeans.add(pb.getBean());
    // Lookup for CDI event endpoint injection points
    pb.getBean().getInjectionPoints().stream().filter(ip -> CdiEventEndpoint.class.equals(getRawType(ip.getType()))).forEach(ip -> {
        Type type = ip.getType() instanceof ParameterizedType ? ((ParameterizedType) ip.getType()).getActualTypeArguments()[0] : Object.class;
        String uri = eventEndpointUri(type, ip.getQualifiers());
        cdiEventEndpoints.put(uri, new CdiEventEndpoint<>(uri, type, ip.getQualifiers(), manager));
    });
}
Also used : CdiSpiHelper.isAnnotationType(org.apache.camel.cdi.CdiSpiHelper.isAnnotationType) Produces(javax.enterprise.inject.Produces) AfterBeanDiscovery(javax.enterprise.inject.spi.AfterBeanDiscovery) LoggerFactory(org.slf4j.LoggerFactory) ProcessBean(javax.enterprise.inject.spi.ProcessBean) Endpoint(org.apache.camel.Endpoint) PropertyInject(org.apache.camel.PropertyInject) EventObject(java.util.EventObject) ProcessProducerField(javax.enterprise.inject.spi.ProcessProducerField) ProcessObserverMethod(javax.enterprise.inject.spi.ProcessObserverMethod) Map(java.util.Map) Observes(javax.enterprise.event.Observes) ProducerTemplate(org.apache.camel.ProducerTemplate) ANY(org.apache.camel.cdi.AnyLiteral.ANY) Method(java.lang.reflect.Method) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) Collectors.toSet(java.util.stream.Collectors.toSet) CamelContextAware(org.apache.camel.CamelContextAware) Annotated(javax.enterprise.inject.spi.Annotated) Extension(javax.enterprise.inject.spi.Extension) CdiSpiHelper.hasType(org.apache.camel.cdi.CdiSpiHelper.hasType) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ProcessAnnotatedType(javax.enterprise.inject.spi.ProcessAnnotatedType) BeanManagerHelper.getReference(org.apache.camel.cdi.BeanManagerHelper.getReference) Set(java.util.Set) ResourceHelper.getResource(org.apache.camel.cdi.ResourceHelper.getResource) CdiSpiHelper.getRawType(org.apache.camel.cdi.CdiSpiHelper.getRawType) ProcessProducerMethod(javax.enterprise.inject.spi.ProcessProducerMethod) BeanInject(org.apache.camel.BeanInject) Stream(java.util.stream.Stream) Type(java.lang.reflect.Type) CdiEventEndpoint.eventEndpointUri(org.apache.camel.cdi.CdiEventEndpoint.eventEndpointUri) Annotation(java.lang.annotation.Annotation) ConsumerTemplate(org.apache.camel.ConsumerTemplate) EXCLUDED(org.apache.camel.cdi.Excluded.EXCLUDED) Bean(javax.enterprise.inject.spi.Bean) RoutesBuilder(org.apache.camel.RoutesBuilder) EndpointInject(org.apache.camel.EndpointInject) Component(org.apache.camel.Component) AbstractExchangeEvent(org.apache.camel.management.event.AbstractExchangeEvent) Collectors.collectingAndThen(java.util.stream.Collectors.collectingAndThen) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) Produce(org.apache.camel.Produce) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ProcessProducer(javax.enterprise.inject.spi.ProcessProducer) Collections.newSetFromMap(java.util.Collections.newSetFromMap) APPLICATION_SCOPED(org.apache.camel.cdi.ApplicationScopedLiteral.APPLICATION_SCOPED) BeanManagerHelper.getReferencesByType(org.apache.camel.cdi.BeanManagerHelper.getReferencesByType) FluentProducerTemplate(org.apache.camel.FluentProducerTemplate) AfterDeploymentValidation(javax.enterprise.inject.spi.AfterDeploymentValidation) Stream.concat(java.util.stream.Stream.concat) Named(javax.inject.Named) DEFAULT(org.apache.camel.cdi.DefaultLiteral.DEFAULT) ServiceStatus(org.apache.camel.ServiceStatus) CamelContext(org.apache.camel.CamelContext) Default(javax.enterprise.inject.Default) Logger(org.slf4j.Logger) CdiSpiHelper.getQualifiers(org.apache.camel.cdi.CdiSpiHelper.getQualifiers) Consume(org.apache.camel.Consume) Predicate.isEqual(java.util.function.Predicate.isEqual) STARTUP(org.apache.camel.cdi.Startup.Literal.STARTUP) InjectionException(javax.enterprise.inject.InjectionException) Converter(org.apache.camel.Converter) ProcessInjectionTarget(javax.enterprise.inject.spi.ProcessInjectionTarget) TypeConverter(org.apache.camel.TypeConverter) ParameterizedType(java.lang.reflect.ParameterizedType) RouteContainer(org.apache.camel.model.RouteContainer) CdiSpiHelper.hasAnnotation(org.apache.camel.cdi.CdiSpiHelper.hasAnnotation) InjectionPoint(javax.enterprise.inject.spi.InjectionPoint) BeanManager(javax.enterprise.inject.spi.BeanManager) ParameterizedType(java.lang.reflect.ParameterizedType) CdiSpiHelper.isAnnotationType(org.apache.camel.cdi.CdiSpiHelper.isAnnotationType) CdiSpiHelper.hasType(org.apache.camel.cdi.CdiSpiHelper.hasType) ProcessAnnotatedType(javax.enterprise.inject.spi.ProcessAnnotatedType) CdiSpiHelper.getRawType(org.apache.camel.cdi.CdiSpiHelper.getRawType) Type(java.lang.reflect.Type) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) BeanManagerHelper.getReferencesByType(org.apache.camel.cdi.BeanManagerHelper.getReferencesByType) ParameterizedType(java.lang.reflect.ParameterizedType)

Example 2 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project hive by apache.

the class ObjectInspectorFactory method getReflectionObjectInspectorNoCache.

private static ObjectInspector getReflectionObjectInspectorNoCache(Type t, ObjectInspectorOptions options, boolean ensureInited) {
    if (t instanceof GenericArrayType) {
        GenericArrayType at = (GenericArrayType) t;
        return getStandardListObjectInspector(getReflectionObjectInspector(at.getGenericComponentType(), options, ensureInited));
    }
    if (t instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) t;
        // List?
        if (List.class.isAssignableFrom((Class<?>) pt.getRawType()) || Set.class.isAssignableFrom((Class<?>) pt.getRawType())) {
            return getStandardListObjectInspector(getReflectionObjectInspector(pt.getActualTypeArguments()[0], options, ensureInited));
        }
        // Map?
        if (Map.class.isAssignableFrom((Class<?>) pt.getRawType())) {
            return getStandardMapObjectInspector(getReflectionObjectInspector(pt.getActualTypeArguments()[0], options, ensureInited), getReflectionObjectInspector(pt.getActualTypeArguments()[1], options, ensureInited));
        }
        // Otherwise convert t to RawType so we will fall into the following if
        // block.
        t = pt.getRawType();
    }
    // Must be a class.
    if (!(t instanceof Class)) {
        throw new RuntimeException(ObjectInspectorFactory.class.getName() + " internal error:" + t);
    }
    Class<?> c = (Class<?>) t;
    // Java Primitive Type?
    if (PrimitiveObjectInspectorUtils.isPrimitiveJavaType(c)) {
        return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveJavaType(c).primitiveCategory);
    }
    // Java Primitive Class?
    if (PrimitiveObjectInspectorUtils.isPrimitiveJavaClass(c)) {
        return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveJavaClass(c).primitiveCategory);
    }
    // Primitive Writable class?
    if (PrimitiveObjectInspectorUtils.isPrimitiveWritableClass(c)) {
        return PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveWritableClass(c).primitiveCategory);
    }
    // Enum class?
    if (Enum.class.isAssignableFrom(c)) {
        return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveObjectInspector.PrimitiveCategory.STRING);
    }
    // Must be struct because List and Map need to be ParameterizedType
    assert (!List.class.isAssignableFrom(c));
    assert (!Map.class.isAssignableFrom(c));
    // Create StructObjectInspector
    ReflectionStructObjectInspector oi;
    switch(options) {
        case JAVA:
            oi = new ReflectionStructObjectInspector();
            break;
        case THRIFT:
            oi = TUnion.class.isAssignableFrom(c) ? new ThriftUnionObjectInspector() : new ThriftStructObjectInspector();
            break;
        case PROTOCOL_BUFFERS:
            oi = new ProtocolBuffersStructObjectInspector();
            break;
        default:
            throw new RuntimeException(ObjectInspectorFactory.class.getName() + ": internal error.");
    }
    // put it into the cache BEFORE it is initialized to make sure we can catch
    // recursive types.
    ReflectionStructObjectInspector prev = (ReflectionStructObjectInspector) objectInspectorCache.putIfAbsent(t, oi);
    if (prev != null) {
        oi = prev;
    } else {
        try {
            oi.init(t, c, options);
        } finally {
            if (!oi.inited) {
                // Failed to init, remove it from cache
                objectInspectorCache.remove(t, oi);
            }
        }
    }
    return oi;
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) List(java.util.List) GenericArrayType(java.lang.reflect.GenericArrayType) PrimitiveObjectInspectorFactory(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory)

Example 3 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project tomcat by apache.

the class Util method getGenericType.

private static <T> TypeResult getGenericType(Class<T> type, Class<? extends T> clazz) {
    // Look to see if this class implements the interface of interest
    // Get all the interfaces
    Type[] interfaces = clazz.getGenericInterfaces();
    for (Type iface : interfaces) {
        // Only need to check interfaces that use generics
        if (iface instanceof ParameterizedType) {
            ParameterizedType pi = (ParameterizedType) iface;
            // Look for the interface of interest
            if (pi.getRawType() instanceof Class) {
                if (type.isAssignableFrom((Class<?>) pi.getRawType())) {
                    return getTypeParameter(clazz, pi.getActualTypeArguments()[0]);
                }
            }
        }
    }
    // Interface not found on this class. Look at the superclass.
    @SuppressWarnings("unchecked") Class<? extends T> superClazz = (Class<? extends T>) clazz.getSuperclass();
    if (superClazz == null) {
        // Finished looking up the class hierarchy without finding anything
        return null;
    }
    TypeResult superClassTypeResult = getGenericType(type, superClazz);
    int dimension = superClassTypeResult.getDimension();
    if (superClassTypeResult.getIndex() == -1 && dimension == 0) {
        // the interface of interest
        return superClassTypeResult;
    }
    if (superClassTypeResult.getIndex() > -1) {
        // Superclass implements interface and defines unknown type for
        // the interface of interest
        // Map that unknown type to the generic types defined in this class
        ParameterizedType superClassType = (ParameterizedType) clazz.getGenericSuperclass();
        TypeResult result = getTypeParameter(clazz, superClassType.getActualTypeArguments()[superClassTypeResult.getIndex()]);
        result.incrementDimension(superClassTypeResult.getDimension());
        if (result.getClazz() != null && result.getDimension() > 0) {
            superClassTypeResult = result;
        } else {
            return result;
        }
    }
    if (superClassTypeResult.getDimension() > 0) {
        StringBuilder className = new StringBuilder();
        for (int i = 0; i < dimension; i++) {
            className.append('[');
        }
        className.append('L');
        className.append(superClassTypeResult.getClazz().getCanonicalName());
        className.append(';');
        Class<?> arrayClazz;
        try {
            arrayClazz = Class.forName(className.toString());
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException(e);
        }
        return new TypeResult(arrayClazz, -1, 0);
    }
    // Error will be logged further up the call stack
    return null;
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type)

Example 4 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project persistence by casidiablo.

the class SqliteAdapterImpl method getSqlInsertForChildrenOf.

private <T> String getSqlInsertForChildrenOf(T bean, Node tree) throws IllegalAccessException {
    // bodom
    // get a list with the fields that are lists
    Class<?> theClass = bean.getClass();
    Field[] fields = SQLHelper.getDeclaredFields(theClass);
    List<Field> collectionFields = new ArrayList<Field>();
    for (Field field : fields) {
        if (field.getType() == List.class) {
            collectionFields.add(field);
            field.setAccessible(true);
        }
    }
    String sqlStatement = "";
    for (Field field : collectionFields) {
        // get the generic type for this list field
        ParameterizedType stringListType = (ParameterizedType) field.getGenericType();
        Class<?> collectionClass = (Class<?>) stringListType.getActualTypeArguments()[0];
        Node child = new Node(collectionClass);
        if (!tree.addChild(child)) {
            continue;
        }
        switch(mDatabaseSpec.getRelationship(theClass, collectionClass)) {
            case MANY_TO_MANY:
                {
                    List list = (List) field.get(bean);
                    if (list != null) {
                        for (Object object : list) {
                            // get the insertion SQL
                            String partialSqlStatement = getSqlStatement(object, tree, null);
                            if (partialSqlStatement != null) {
                                sqlStatement += partialSqlStatement;
                            }
                            // insert items in the joined table
                            // get the table name and columns
                            String relationTableName = ManyToMany.buildTableName(theClass, collectionClass);
                            String mainForeignKey = SQLHelper.getTableName(theClass) + "_id";
                            String secondaryForeignKey = SQLHelper.getTableName(collectionClass) + "_id";
                            // get the value for the main bean ID
                            Object beanId;
                            if (mDatabaseSpec.isAutoincrement(theClass)) {
                                beanId = String.format(SQLHelper.SELECT_AUTOINCREMENT_FORMAT, SQLHelper.getTableName(theClass));
                            } else {
                                Field mainId = SQLHelper.getPrimaryKeyField(theClass);
                                mainId.setAccessible(true);
                                beanId = mainId.get(bean);
                            }
                            // get the value for the secondary bean ID
                            Object secondaryId;
                            if (mDatabaseSpec.isAutoincrement(collectionClass)) {
                                secondaryId = String.format(SQLHelper.SELECT_AUTOINCREMENT_FORMAT, SQLHelper.getTableName(collectionClass));
                            } else {
                                Field secondaryIdField = SQLHelper.getPrimaryKeyField(collectionClass);
                                secondaryIdField.setAccessible(true);
                                secondaryId = secondaryIdField.get(object);
                            }
                            // build the sql statement for the insertion of the many-to-many relation
                            String hack = String.format(HACK_INSERT_FORMAT, relationTableName, mainForeignKey, String.valueOf(beanId), secondaryForeignKey, String.valueOf(secondaryId), String.valueOf(beanId));
                            sqlStatement += String.format("INSERT OR IGNORE INTO %s (%s, %s) VALUES (%s, %s);%s", relationTableName, mainForeignKey, secondaryForeignKey, hack, String.valueOf(secondaryId), SQLHelper.STATEMENT_SEPARATOR);
                        }
                    }
                    break;
                }
            case HAS_MANY:
                List list = (List) field.get(bean);
                if (list == null) {
                    break;
                }
                for (Object object : list) {
                    // prepare the object by setting the foreign value
                    String partialSqlStatement = getSqlStatement(object, tree, bean);
                    if (partialSqlStatement != null) {
                        sqlStatement += partialSqlStatement;
                    }
                }
                break;
        }
        tree.removeChild(child);
    }
    return sqlStatement;
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList)

Example 5 with ParameterizedType

use of java.lang.reflect.ParameterizedType in project cucumber-jvm by cucumber.

the class ParameterInfo method getListConverter.

private SingleValueConverter getListConverter(Type type, LocalizedXStreams.LocalizedXStream xStream) {
    Class elementType = type instanceof ParameterizedType ? getRawType(((ParameterizedType) type).getActualTypeArguments()[0]) : Object.class;
    SingleValueConverter elementConverter = xStream.getSingleValueConverter(elementType);
    if (elementConverter == null) {
        return null;
    } else {
        return xStream.createListConverter(delimiter, elementConverter);
    }
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) SingleValueConverter(cucumber.deps.com.thoughtworks.xstream.converters.SingleValueConverter)

Aggregations

ParameterizedType (java.lang.reflect.ParameterizedType)605 Type (java.lang.reflect.Type)456 GenericArrayType (java.lang.reflect.GenericArrayType)203 WildcardType (java.lang.reflect.WildcardType)162 TypeVariable (java.lang.reflect.TypeVariable)126 ArrayList (java.util.ArrayList)79 Method (java.lang.reflect.Method)60 Test (org.junit.Test)55 List (java.util.List)45 Field (java.lang.reflect.Field)43 Map (java.util.Map)39 HashMap (java.util.HashMap)32 Collection (java.util.Collection)18 Annotation (java.lang.annotation.Annotation)13 ImmutableList (com.google.common.collect.ImmutableList)12 TypeLiteral (com.google.inject.TypeLiteral)12 HashSet (java.util.HashSet)11 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)10 GenericType (javax.ws.rs.core.GenericType)10 MediaType (javax.ws.rs.core.MediaType)10