Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.datastax.driver.mapping;
  
  import java.util.*;
  
 
Static metods that facilitates parsing class annotations into the corresponding EntityMapper.
 
 class AnnotationParser {
 
     private static final Comparator<FieldfieldComparator = new Comparator<Field>() {
         public int compare(Field f1Field f2) {
             return position(f2) - position(f1);
         }
     };
 
     private AnnotationParser() {}
 
     public static <T> EntityMapper<T> parseEntity(Class<T> entityClassEntityMapper.Factory factoryMappingManager mappingManager) {
         Table table = getTypeAnnotation(Table.classentityClass);
 
         String ksName = table.caseSensitiveKeyspace() ? table.keyspace() : table.keyspace().toLowerCase();
         String tableName = table.caseSensitiveTable() ? table.name() : table.name().toLowerCase();
 
         ConsistencyLevel writeConsistency = table.writeConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.writeConsistency().toUpperCase());
         ConsistencyLevel readConsistency = table.readConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.readConsistency().toUpperCase());
 
         EntityMapper<T> mapper = factory.create(entityClassksNametableNamewriteConsistencyreadConsistency);
 
         List<Fieldpks = new ArrayList<Field>();
         List<Fieldccs = new ArrayList<Field>();
         List<Fieldrgs = new ArrayList<Field>();
 
         for (Field field : entityClass.getDeclaredFields()) {
             validateAnnotations(field"entity",
                                 Column.classClusteringColumn.classEnumerated.classPartitionKey.classTransient.class);
 
             if (field.getAnnotation(Transient.class) != null)
                 continue;
 
             switch (kind(field)) {
                 case :
                     pks.add(field);
                     break;
                 case :
                     ccs.add(field);
                     break;
                 default:
                     rgs.add(field);
                     break;
             }
         }
 
         Collections.sort(pks);
         Collections.sort(ccs);
 
         validateOrder(pks"@PartitionKey");
         validateOrder(ccs"@ClusteringColumn");
 
         mapper.addColumns(convert(pksfactorymapper.entityClassmappingManager),
                           convert(ccsfactorymapper.entityClassmappingManager),
                           convert(rgsfactorymapper.entityClassmappingManager));
         return mapper;
     }
 
     public static <T> EntityMapper<T> parseUDT(Class<T> udtClassEntityMapper.Factory factoryMappingManager mappingManager) {
         UDT udt = getTypeAnnotation(UDT.classudtClass);
 
         String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase();
         String udtName = udt.caseSensitiveType() ? udt.name() : udt.name().toLowerCase();
 
         EntityMapper<T> mapper = factory.create(udtClassksNameudtNamenullnull);
 
         List<Fieldcolumns = new ArrayList<Field>();
 
         for (Field field : udtClass.getDeclaredFields()) {
             validateAnnotations(field"UDT",
                                 com.datastax.driver.mapping.annotations.Field.classEnumerated.classTransient.class);
 
             if (field.getAnnotation(Transient.class) != null)
                 continue;
 
             switch (kind(field)) {
                 case :
                     throw new IllegalArgumentException("Annotation @PartitionKey is not allowed in a class annotated by @UDT");
                case :
                    throw new IllegalArgumentException("Annotation @ClusteringColumn is not allowed in a class annotated by @UDT");
                default:
                    columns.add(field);
                    break;
            }
        }
        mapper.addColumns(convert(columnsfactoryudtClassmappingManager));
        return mapper;
    }
    private static <T> List<ColumnMapper<T>> convert(List<FieldfieldsEntityMapper.Factory factoryClass<T> klassMappingManager mappingManager) {
        List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
        for (int i = 0; i < fields.size(); i++) {
            Field field = fields.get(i);
            int pos = position(field);
            mappers.add(factory.createColumnMapper(klassfieldpos < 0 ? i : posmappingManager));
        }
        return mappers;
    }
    private static void validateOrder(List<FieldfieldsString annotation) {
        for (int i = 0; i < fields.size(); i++) {
            int pos = position(fields.get(i));
            if (pos < i)
                throw new IllegalArgumentException("Missing ordering value " + i + " for " + annotation + " annotation");
            else if (pos > i)
                throw new IllegalArgumentException("Duplicate ordering value " + i + " for " + annotation + " annotation");
        }
    }
    private static int position(Field field) {
        switch (kind(field)) {
            case :
                return field.getAnnotation(PartitionKey.class).value();
            case :
                return field.getAnnotation(ClusteringColumn.class).value();
            default:
                return -1;
        }
    }
    public static ColumnMapper.Kind kind(Field field) {
        PartitionKey pk = field.getAnnotation(PartitionKey.class);
        ClusteringColumn cc = field.getAnnotation(ClusteringColumn.class);
        if (pk != null && cc != null)
            throw new IllegalArgumentException("Field " + field.getName() + " cannot have both the @PartitionKey and @ClusteringColumn annotations");
        return pk != null
             ? ..
             : (cc != null ? .. : ..);
    }
    public static EnumType enumType(Field field) {
        Class<?> type = field.getType();
        if (!type.isEnum())
            return null;
        Enumerated enumerated = field.getAnnotation(Enumerated.class);
        return (enumerated == null) ? . : enumerated.value();
    }
    public static String columnName(Field field) {
        Column column = field.getAnnotation(Column.class);
        if (column != null) {
            return column.caseSensitive() ? column.name() : column.name().toLowerCase();
        }
        if (udtField != null) {
            return udtField.caseSensitive() ? udtField.name() : udtField.name().toLowerCase();
        }
        return field.getName();
    }
    public static <T> AccessorMapper<T> parseAccessor(Class<T> accClassAccessorMapper.Factory factoryMappingManager mappingManager) {
        if (!accClass.isInterface())
            throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
        getTypeAnnotation(Accessor.classaccClass);
        List<MethodMappermethods = new ArrayList<MethodMapper>();
        for (Method m : accClass.getDeclaredMethods()) {
            Query query = m.getAnnotation(Query.class);
            if (query == null)
                continue;
            String queryString = query.value();
            Annotation[][] paramAnnotations = m.getParameterAnnotations();
            Type[] paramTypes = m.getGenericParameterTypes();
            ParamMapper[] paramMappers = new ParamMapper[paramAnnotations.length];
            Boolean hasParamAnnotation = null;
            for (int i = 0; i < paramMappers.lengthi++) {
                String paramName = null;
                for (Annotation a : paramAnnotations[i]) {
                    if (a.annotationType().equals(Param.class)) {
                        paramName = ((Parama).value();
                        break;
                    }
                }
                if (hasParamAnnotation == null)
                    hasParamAnnotation = (paramName != null);
                if (hasParamAnnotation != (paramName != null))
                    throw new IllegalArgumentException(String.format("For method '%s', either all or none of the paramaters of a method must have a @Param annotation"m.getName()));
                paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), iparamNameparamTypes[i], paramAnnotations[i], mappingManager);
            }
            ConsistencyLevel cl = null;
            int fetchSize = -1;
            boolean tracing = false;
            QueryParameters options = m.getAnnotation(QueryParameters.class);
            if (options != null) {
                cl = options.consistency().isEmpty() ? null : ConsistencyLevel.valueOf(options.consistency().toUpperCase());
                fetchSize = options.fetchSize();
                tracing = options.tracing();
            }
            methods.add(new MethodMapper(mqueryStringparamMappersclfetchSizetracing));
        }
        return factory.create(accClassmethods);
    }
    @SuppressWarnings({ "unchecked""rawtypes" })
    private static ParamMapper newParamMapper(String classNameString methodNameint idxString paramNameType paramTypeAnnotation[] paramAnnotationsMappingManager mappingManager) {
        if (paramType instanceof Class) {
            Class<?> paramClass = (Class<?>) paramType;
            if (paramClass.isAnnotationPresent(UDT.class)) {
                UDTMapper<?> udtMapper = mappingManager.getUDTMapper(paramClass);
                return new UDTParamMapper(paramNameidxudtMapper);
            } else if (paramClass.isEnum()) {
                EnumType enumType = .;
                for (Annotation annotation : paramAnnotations) {
                    if (annotation instanceof Enumerated) {
                        enumType = ((Enumeratedannotation).value();
                    }
                }
                return new EnumParamMapper(paramNameidxenumType);
            }
            return new ParamMapper(paramNameidx);
        } if (paramType instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedTypeparamType;
            Type raw = pt.getRawType();
            if (!(raw instanceof Class))
                throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s"paramTypeparamNameclassNamemethodName));
            Class<?> klass = (Class<?>)raw;
            Class<?> firstTypeParam = ReflectionUtils.getParam(pt, 0, paramName);
            if (List.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
                UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
                return new UDTListParamMapper(paramNameidxvalueMapper);
            }
            if (Set.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
                UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
                return new UDTSetParamMapper(paramNameidxvalueMapper);
            }
            if (Map.class.isAssignableFrom(klass)) {
                Class<?> secondTypeParam = ReflectionUtils.getParam(pt, 1, paramName);
                UDTMapper<?> keyMapper = firstTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(firstTypeParam) : null;
                UDTMapper<?> valueMapper = secondTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(secondTypeParam) : null;
                if (keyMapper != null || valueMapper != null) {
                    return new UDTMapParamMapper(paramNameidxkeyMappervalueMapper);
                }
            }
            return new ParamMapper(paramNameidx);
        } else {
            throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s"paramTypeparamNameclassNamemethodName));
        }
    }
    private static <T extends Annotation> T getTypeAnnotation(Class<T> annotationClass<?> annotatedClass) {
        T instance = annotatedClass.getAnnotation(annotation);
        if (instance == null)
            throw new IllegalArgumentException(String.format("@%s annotation was not found on type %s",
                                                             annotation.getSimpleName(), annotatedClass.getName()));
        // Check that no other mapping annotations are present
        validateAnnotations(annotatedClassannotation);
        return instance;
    }
    private static void validateAnnotations(Class<?> clazzClass<? extends Annotationallowed) {
        @SuppressWarnings("unchecked")
        Class<? extends Annotationinvalid = validateAnnotations(clazz.getAnnotations(), allowed);
        if (invalid != null)
            throw new IllegalArgumentException(String.format("Cannot have both @%s and @%s on type %s",
                                                             allowed.getSimpleName(), invalid.getSimpleName(),
                                                             clazz.getName()));
    }
    private static void validateAnnotations(Field fieldString classDescriptionClass<? extends Annotation>... allowed) {
        Class<? extends Annotationinvalid = validateAnnotations(field.getAnnotations(), allowed);
        if (invalid != null)
            throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on field %s of %s %s",
                                                             invalid.getSimpleName(),
                                                             field.getName(), classDescription,
                                                             field.getDeclaringClass().getName()));
    }
    private static final Package MAPPING_PACKAGE = Table.class.getPackage();
    // Returns the offending annotation if there is one
    private static Class<? extends AnnotationvalidateAnnotations(Annotation[] annotationsClass<? extends Annotation>... allowed) {
        for (Annotation annotation : annotations) {
            Class<? extends Annotationactual = annotation.annotationType();
            if (actual.getPackage().equals() && !contains(allowedactual))
                return actual;
        }
        return null;
    }
    private static boolean contains(Object[] arrayObject target) {
        for (Object element : array)
            if (element.equals(target))
                return true;
        return false;
    }
New to GrepCode? Check out our FAQ X