Elffuss BraidHub

kikocis/java-driver public

f2aa3eff0cc5 · 8.1 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2014 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.mapping;
17
18import java.lang.annotation.Annotation;
19import java.lang.reflect.*;
20import java.lang.reflect.Field;
21import java.util.*;
22
23import com.google.common.primitives.Primitives;
24
25import com.datastax.driver.mapping.annotations.*;
26import com.google.common.collect.ImmutableSet;
27import com.google.common.collect.ImmutableSet.Builder;
28
29import com.datastax.driver.core.DataType;
30
31/**
32 * Various checks on mapping annotations.
33 */
34class AnnotationChecks {
35
36 // The package containing the mapping annotations
37 private static final Package MAPPING_PACKAGE = Table.class.getPackage();
38
39 // The Java types that should not be annotated with @Frozen. Any other type is supposed
40 // to map to a UDT or tuple.
41 private static final Set<Class<?>> EXPECTED_NON_FROZEN_CLASSES;
42 static {
43 Builder<Class<?>> builder = ImmutableSet.<Class<?>>builder();
44 for (DataType type : DataType.allPrimitiveTypes()) {
45 builder.add(type.asJavaClass());
46 builder.add(Primitives.unwrap(type.asJavaClass()));
47 }
48 builder.add(List.class);
49 builder.add(Set.class);
50 builder.add(Map.class);
51
52 EXPECTED_NON_FROZEN_CLASSES = builder.build();
53 }
54
55 /**
56 * Checks that a class is decorated with the given annotation, and return the annotation instance.
57 * Also validates that no other mapping annotation is present.
58 */
59 static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) {
60 T instance = annotatedClass.getAnnotation(annotation);
61 if (instance == null)
62 throw new IllegalArgumentException(String.format("@%s annotation was not found on type %s",
63 annotation.getSimpleName(), annotatedClass.getName()));
64
65 // Check that no other mapping annotations are present
66 validateAnnotations(annotatedClass, annotation);
67
68 return instance;
69 }
70
71 private static void validateAnnotations(Class<?> clazz, Class<? extends Annotation> allowed) {
72 @SuppressWarnings("unchecked")
73 Class<? extends Annotation> invalid = validateAnnotations(clazz.getAnnotations(), allowed);
74 if (invalid != null)
75 throw new IllegalArgumentException(String.format("Cannot have both @%s and @%s on type %s",
76 allowed.getSimpleName(), invalid.getSimpleName(),
77 clazz.getName()));
78 }
79
80 /**
81 * Checks that a field is only annotated with the given mapping annotations, and that its "frozen" annotations are valid.
82 */
83 static void validateAnnotations(Field field, String classDescription, Class<? extends Annotation>... allowed) {
84 Class<? extends Annotation> invalid = validateAnnotations(field.getAnnotations(), allowed);
85 if (invalid != null)
86 throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on field %s of %s %s",
87 invalid.getSimpleName(),
88 field.getName(), classDescription,
89 field.getDeclaringClass().getName()));
90
91 if (field.getAnnotation(Transient.class) == null) {
92 try {
93 checkFrozenTypes(field);
94 } catch (IllegalArgumentException e) {
95 throw new IllegalArgumentException(String.format("Error while checking frozen types on field %s of %s %s: %s",
96 field.getName(), classDescription,
97 field.getDeclaringClass().getName(), e.getMessage()));
98 }
99 }
100 }
101
102 // Returns the offending annotation if there is one
103 private static Class<? extends Annotation> validateAnnotations(Annotation[] annotations, Class<? extends Annotation>... allowed) {
104 for (Annotation annotation : annotations) {
105 Class<? extends Annotation> actual = annotation.annotationType();
106 if (actual.getPackage().equals(MAPPING_PACKAGE) && !contains(allowed, actual))
107 return actual;
108 }
109 return null;
110 }
111
112 private static boolean contains(Object[] array, Object target) {
113 for (Object element : array)
114 if (element.equals(target))
115 return true;
116 return false;
117 }
118
119 static void checkFrozenTypes(Field field) {
120 Type javaType = field.getGenericType();
121 CQLType cqlType = getCQLType(field);
122 checkFrozenTypes(javaType, cqlType);
123 }
124
125 // Builds a CQLType hierarchy based on the @Frozen* annotations on a field.
126 private static CQLType getCQLType(Field field) {
127 Frozen frozen = field.getAnnotation(Frozen.class);
128 if (frozen != null)
129 return CQLType.parse(frozen.value());
130
131 boolean frozenKey = field.getAnnotation(FrozenKey.class) != null;
132 boolean frozenValue = field.getAnnotation(FrozenValue.class) != null;
133 if (frozenKey && frozenValue)
134 return CQLType.FROZEN_MAP_KEY_AND_VALUE;
135 else if (frozenKey)
136 return CQLType.FROZEN_MAP_KEY;
137 else if (frozenValue && field.getType().equals(Map.class))
138 return CQLType.FROZEN_MAP_VALUE;
139 else if (frozenValue)
140 return CQLType.FROZEN_ELEMENT;
141 else
142 return CQLType.UNFROZEN_SIMPLE;
143 }
144
145 // Traverses the Java type and CQLType hierarchies in parallel, to ensure that all
146 // Java types mapping to UDTs and tuples are marked as frozen in the CQLType.
147 // We accept that parts of the CQLType be null, in which case the matching parts
148 // in the Java type will be considered as not frozen.
149 private static void checkFrozenTypes(Type javaType, CQLType cqlType) {
150 Class<?> javaClass;
151 Type[] childrenJavaTypes;
152 if (javaType instanceof Class<?>) {
153 javaClass = (Class<?>)javaType;
154 childrenJavaTypes = null;
155 } else if (javaType instanceof ParameterizedType){
156 ParameterizedType pt = (ParameterizedType)javaType;
157 javaClass = (Class<?>)pt.getRawType();
158 childrenJavaTypes = pt.getActualTypeArguments();
159 } else
160 throw new IllegalArgumentException("unexpected type: " + javaType);
161
162 boolean frozen = (cqlType != null && cqlType.frozen);
163 checkValidFrozen(javaClass, frozen);
164
165 if (childrenJavaTypes != null) {
166 for (int i = 0; i < childrenJavaTypes.length; i++) {
167 Type childJavaType = childrenJavaTypes[i];
168 CQLType childCQLType = null;
169 if (cqlType != null && cqlType.subTypes != null && cqlType.subTypes.size() > i)
170 childCQLType = cqlType.subTypes.get(i);
171 checkFrozenTypes(childJavaType, childCQLType);
172 }
173 }
174 }
175
176 private static void checkValidFrozen(Class<?> clazz, boolean declared) {
177 boolean expected = !EXPECTED_NON_FROZEN_CLASSES.contains(clazz) && !clazz.isEnum();
178 if (expected != declared)
179 throw new IllegalArgumentException(String.format("expected %s to be %sfrozen but was %sfrozen",
180 clazz.getSimpleName(),
181 expected ? "" : "not ",
182 declared ? "" : "not "));
183 }
184}