Elffuss BraidHub

kikocis/java-driver public

b0ad3785b703 · 8.1 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 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.datastax.driver.mapping.annotations.*;
24
25/**
26 * Various checks on mapping annotations.
27 */
28class AnnotationChecks {
29
30 // The package containing the mapping annotations
31 private static final Package MAPPING_PACKAGE = Table.class.getPackage();
32
33 /**
34 * Checks that a class is decorated with the given annotation, and return the annotation instance.
35 * Also validates that no other mapping annotation is present.
36 */
37 static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) {
38 T instance = annotatedClass.getAnnotation(annotation);
39 if (instance == null)
40 throw new IllegalArgumentException(String.format("@%s annotation was not found on type %s",
41 annotation.getSimpleName(), annotatedClass.getName()));
42
43 // Check that no other mapping annotations are present
44 validateAnnotations(annotatedClass, annotation);
45
46 return instance;
47 }
48
49 private static void validateAnnotations(Class<?> clazz, Class<? extends Annotation> allowed) {
50 @SuppressWarnings("unchecked")
51 Class<? extends Annotation> invalid = validateAnnotations(clazz.getAnnotations(), allowed);
52 if (invalid != null)
53 throw new IllegalArgumentException(String.format("Cannot have both @%s and @%s on type %s",
54 allowed.getSimpleName(), invalid.getSimpleName(),
55 clazz.getName()));
56 }
57
58 /**
59 * Checks that a field is only annotated with the given mapping annotations, and that its "frozen" annotations are valid.
60 */
61 static void validateAnnotations(Field field, String classDescription, Class<? extends Annotation>... allowed) {
62 Class<? extends Annotation> invalid = validateAnnotations(field.getAnnotations(), allowed);
63 if (invalid != null)
64 throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on field %s of %s %s",
65 invalid.getSimpleName(),
66 field.getName(), classDescription,
67 field.getDeclaringClass().getName()));
68
69 if (field.getAnnotation(Transient.class) == null) {
70 try {
71 checkFrozenTypes(field);
72 } catch (IllegalArgumentException e) {
73 throw new IllegalArgumentException(String.format("Error while checking frozen types on field %s of %s %s: %s",
74 field.getName(), classDescription,
75 field.getDeclaringClass().getName(), e.getMessage()));
76 }
77 }
78 checkValidComputed(field);
79 }
80
81 // Returns the offending annotation if there is one
82 private static Class<? extends Annotation> validateAnnotations(Annotation[] annotations, Class<? extends Annotation>... allowed) {
83 for (Annotation annotation : annotations) {
84 Class<? extends Annotation> actual = annotation.annotationType();
85 if (actual.getPackage().equals(MAPPING_PACKAGE) && !contains(allowed, actual))
86 return actual;
87 }
88 return null;
89 }
90
91 private static boolean contains(Object[] array, Object target) {
92 for (Object element : array)
93 if (element.equals(target))
94 return true;
95 return false;
96 }
97
98 static void checkFrozenTypes(Field field) {
99 Type javaType = field.getGenericType();
100 DeclaredFrozenType declaredFrozenType = getDeclaredFrozenType(field);
101 checkFrozenTypes(javaType, declaredFrozenType);
102 }
103
104 static void checkValidComputed(Field field) {
105 Computed computed = field.getAnnotation(Computed.class);
106 if (computed != null && computed.value().isEmpty()){
107 throw new IllegalArgumentException(String.format("Field %s: attribute 'value' of annotation @Computed is mandatory for computed fields", field.getName()));
108 }
109 }
110
111 // Builds a DeclaredFrozenType hierarchy based on the @Frozen* annotations on a field.
112 private static DeclaredFrozenType getDeclaredFrozenType(Field field) {
113 Frozen frozen = field.getAnnotation(Frozen.class);
114 if (frozen != null)
115 return DeclaredFrozenType.parse(frozen.value());
116
117 boolean frozenKey = field.getAnnotation(FrozenKey.class) != null;
118 boolean frozenValue = field.getAnnotation(FrozenValue.class) != null;
119 if (frozenKey && frozenValue)
120 return DeclaredFrozenType.FROZEN_MAP_KEY_AND_VALUE;
121 else if (frozenKey)
122 return DeclaredFrozenType.FROZEN_MAP_KEY;
123 else if (frozenValue && field.getType().equals(Map.class))
124 return DeclaredFrozenType.FROZEN_MAP_VALUE;
125 else if (frozenValue)
126 return DeclaredFrozenType.FROZEN_ELEMENT;
127 else
128 return DeclaredFrozenType.UNFROZEN_SIMPLE;
129 }
130
131 // Traverses the Java type and CQLType hierarchies in parallel, to ensure that all
132 // Java types mapping to UDTs, tuples and nested collections are marked as frozen in the CQLType.
133 // We accept that parts of the CQLType be null, in which case the matching parts
134 // in the Java type will be considered as not frozen.
135 private static void checkFrozenTypes(Type javaType, DeclaredFrozenType declaredFrozenType) {
136 checkFrozenTypes(javaType, declaredFrozenType, true);
137 }
138
139 private static void checkFrozenTypes(Type javaType, DeclaredFrozenType declaredFrozenType, boolean isRoot) {
140 Class<?> javaClass;
141 Type[] childrenJavaTypes;
142 if (javaType instanceof Class<?>) {
143 javaClass = (Class<?>)javaType;
144 childrenJavaTypes = null;
145 } else if (javaType instanceof ParameterizedType){
146 ParameterizedType pt = (ParameterizedType)javaType;
147 javaClass = (Class<?>)pt.getRawType();
148 childrenJavaTypes = pt.getActualTypeArguments();
149 } else
150 throw new IllegalArgumentException("unexpected type: " + javaType);
151
152 boolean frozen = (declaredFrozenType != null && declaredFrozenType.frozen);
153 checkValidFrozen(javaClass, isRoot, frozen);
154
155 if (childrenJavaTypes != null) {
156 for (int i = 0; i < childrenJavaTypes.length; i++) {
157 Type childJavaType = childrenJavaTypes[i];
158 DeclaredFrozenType childDeclaredFrozenType = null;
159 if (declaredFrozenType != null && declaredFrozenType.subTypes != null && declaredFrozenType.subTypes.size() > i)
160 childDeclaredFrozenType = declaredFrozenType.subTypes.get(i);
161 checkFrozenTypes(childJavaType, childDeclaredFrozenType, false);
162 }
163 }
164 }
165
166 private static void checkValidFrozen(Class<?> clazz, boolean isRoot, boolean isDeclaredFrozen) {
167 boolean shouldBeFrozen = (TypeMappings.mapsToCollection(clazz) && !isRoot)
168 || TypeMappings.mapsToUserTypeOrTuple(clazz);
169 if (shouldBeFrozen != isDeclaredFrozen)
170 throw new IllegalArgumentException(String.format("expected %s to be %sfrozen but was %sfrozen",
171 clazz.getSimpleName(),
172 shouldBeFrozen ? "" : "not ",
173 isDeclaredFrozen ? "" : "not "));
174 }
175}