Elffuss BraidHub

kikocis/java-driver public

5dad311f5093 · 14.5 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.Field;
20import java.lang.reflect.*;
21import java.util.ArrayList;
22import java.util.Collections;
23import java.util.Comparator;
24import java.util.List;
25import java.util.concurrent.atomic.AtomicInteger;
26
27import com.google.common.base.Strings;
28
29import com.datastax.driver.core.ConsistencyLevel;
30import com.datastax.driver.mapping.MethodMapper.EnumParamMapper;
31import com.datastax.driver.mapping.MethodMapper.NestedUDTParamMapper;
32import com.datastax.driver.mapping.MethodMapper.ParamMapper;
33import com.datastax.driver.mapping.MethodMapper.UDTParamMapper;
34import com.datastax.driver.mapping.annotations.*;
35
36/**
37 * Static metods that facilitates parsing class annotations into the corresponding {@link EntityMapper}.
38 */
39class AnnotationParser {
40
41 private static final Comparator<Field> fieldComparator = new Comparator<Field>() {
42 public int compare(Field f1, Field f2) {
43 return position(f1) - position(f2);
44 }
45 };
46
47 private AnnotationParser() {}
48
49 public static <T> EntityMapper<T> parseEntity(Class<T> entityClass, EntityMapper.Factory factory, MappingManager mappingManager) {
50 Table table = AnnotationChecks.getTypeAnnotation(Table.class, entityClass);
51
52 String ksName = table.caseSensitiveKeyspace() ? table.keyspace() : table.keyspace().toLowerCase();
53 String tableName = table.caseSensitiveTable() ? table.name() : table.name().toLowerCase();
54
55 ConsistencyLevel writeConsistency = table.writeConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.writeConsistency().toUpperCase());
56 ConsistencyLevel readConsistency = table.readConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.readConsistency().toUpperCase());
57
58 if (Strings.isNullOrEmpty(table.keyspace())) {
59 ksName = mappingManager.getSession().getLoggedKeyspace();
60 if (Strings.isNullOrEmpty(ksName))
61 throw new IllegalArgumentException(String.format(
62 "Error creating mapper for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
63 entityClass.getSimpleName(),
64 Table.class.getSimpleName()
65 ));
66 }
67
68 EntityMapper<T> mapper = factory.create(entityClass, ksName, tableName, writeConsistency, readConsistency);
69
70 List<Field> pks = new ArrayList<Field>();
71 List<Field> ccs = new ArrayList<Field>();
72 List<Field> rgs = new ArrayList<Field>();
73
74 for (Field field : entityClass.getDeclaredFields()) {
75 if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
76 continue;
77
78 AnnotationChecks.validateAnnotations(field, "entity",
79 Column.class, ClusteringColumn.class, Enumerated.class, Frozen.class, FrozenKey.class,
80 FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
81
82 if (field.getAnnotation(Transient.class) != null)
83 continue;
84
85 switch (kind(field)) {
86 case PARTITION_KEY:
87 pks.add(field);
88 break;
89 case CLUSTERING_COLUMN:
90 ccs.add(field);
91 break;
92 default:
93 rgs.add(field);
94 break;
95 }
96 }
97
98 AtomicInteger columnCounter = new AtomicInteger(0);
99
100 Collections.sort(pks, fieldComparator);
101 Collections.sort(ccs, fieldComparator);
102
103 validateOrder(pks, "@PartitionKey");
104 validateOrder(ccs, "@ClusteringColumn");
105
106 mapper.addColumns(convert(pks, factory, mapper.entityClass, mappingManager, columnCounter),
107 convert(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
108 convert(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
109 return mapper;
110 }
111
112 public static <T> EntityMapper<T> parseUDT(Class<T> udtClass, EntityMapper.Factory factory, MappingManager mappingManager) {
113 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
114
115 String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase();
116 String udtName = udt.caseSensitiveType() ? udt.name() : udt.name().toLowerCase();
117
118 if (Strings.isNullOrEmpty(udt.keyspace())) {
119 ksName = mappingManager.getSession().getLoggedKeyspace();
120 if (Strings.isNullOrEmpty(ksName))
121 throw new IllegalArgumentException(String.format(
122 "Error creating UDT mapper for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
123 udtClass.getSimpleName(),
124 UDT.class.getSimpleName()
125 ));
126 }
127
128 EntityMapper<T> mapper = factory.create(udtClass, ksName, udtName, null, null);
129
130 List<Field> columns = new ArrayList<Field>();
131
132 for (Field field : udtClass.getDeclaredFields()) {
133 if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
134 continue;
135
136 AnnotationChecks.validateAnnotations(field, "UDT",
137 com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
138 FrozenValue.class, Enumerated.class, Transient.class);
139
140 if (field.getAnnotation(Transient.class) != null)
141 continue;
142
143 switch (kind(field)) {
144 case PARTITION_KEY:
145 throw new IllegalArgumentException("Annotation @PartitionKey is not allowed in a class annotated by @UDT");
146 case CLUSTERING_COLUMN:
147 throw new IllegalArgumentException("Annotation @ClusteringColumn is not allowed in a class annotated by @UDT");
148 default:
149 columns.add(field);
150 break;
151 }
152 }
153
154 mapper.addColumns(convert(columns, factory, udtClass, mappingManager, null));
155 return mapper;
156 }
157
158 private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
159 List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
160 for (int i = 0; i < fields.size(); i++) {
161 Field field = fields.get(i);
162 int pos = position(field);
163 mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter));
164 }
165 return mappers;
166 }
167
168 private static void validateOrder(List<Field> fields, String annotation) {
169 for (int i = 0; i < fields.size(); i++) {
170 Field field = fields.get(i);
171 int pos = position(field);
172 if (pos != i)
173 throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of column %s, was expecting %d",
174 pos, annotation, field.getName(), i));
175 }
176 }
177
178 private static int position(Field field) {
179 switch (kind(field)) {
180 case PARTITION_KEY:
181 return field.getAnnotation(PartitionKey.class).value();
182 case CLUSTERING_COLUMN:
183 return field.getAnnotation(ClusteringColumn.class).value();
184 default:
185 return -1;
186 }
187 }
188
189 public static ColumnMapper.Kind kind(Field field) {
190 PartitionKey pk = field.getAnnotation(PartitionKey.class);
191 ClusteringColumn cc = field.getAnnotation(ClusteringColumn.class);
192 Computed comp = field.getAnnotation(Computed.class);
193 if (pk != null && cc != null)
194 throw new IllegalArgumentException("Field " + field.getName() + " cannot have both the @PartitionKey and @ClusteringColumn annotations");
195
196 if (pk != null) {
197 return ColumnMapper.Kind.PARTITION_KEY;
198 }
199 if (cc != null) {
200 return ColumnMapper.Kind.CLUSTERING_COLUMN;
201 }
202 if (comp != null) {
203 return ColumnMapper.Kind.COMPUTED;
204 }
205 return ColumnMapper.Kind.REGULAR;
206 }
207
208 public static EnumType enumType(Field field) {
209 Class<?> type = field.getType();
210 if (!type.isEnum())
211 return null;
212
213 Enumerated enumerated = field.getAnnotation(Enumerated.class);
214 return (enumerated == null) ? EnumType.STRING : enumerated.value();
215 }
216
217 public static String columnName(Field field) {
218 Column column = field.getAnnotation(Column.class);
219 Computed computedField = field.getAnnotation(Computed.class);
220 if (column != null && !column.name().isEmpty()) {
221 if (computedField != null){
222 throw new IllegalArgumentException("Cannot use @Column and @Computed on the same field");
223 }
224 return column.caseSensitive() ? column.name() : column.name().toLowerCase();
225 }
226
227 com.datastax.driver.mapping.annotations.Field udtField = field.getAnnotation(com.datastax.driver.mapping.annotations.Field.class);
228 if (udtField != null && !udtField.name().isEmpty()) {
229 return udtField.caseSensitive() ? udtField.name() : udtField.name().toLowerCase();
230 }
231
232 if (computedField != null) {
233 return computedField.formula();
234 }
235
236 return field.getName().toLowerCase();
237 }
238
239 public static String newAlias(Field field, int columnNumber) {
240 return "col" + columnNumber;
241
242 }
243
244 public static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) {
245 if (!accClass.isInterface())
246 throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
247
248 AnnotationChecks.getTypeAnnotation(Accessor.class, accClass);
249
250 List<MethodMapper> methods = new ArrayList<MethodMapper>();
251 for (Method m : accClass.getDeclaredMethods()) {
252 Query query = m.getAnnotation(Query.class);
253 if (query == null)
254 continue;
255
256 String queryString = query.value();
257
258 Annotation[][] paramAnnotations = m.getParameterAnnotations();
259 Type[] paramTypes = m.getGenericParameterTypes();
260 ParamMapper[] paramMappers = new ParamMapper[paramAnnotations.length];
261 Boolean hasParamAnnotation = null;
262 for (int i = 0; i < paramMappers.length; i++) {
263 String paramName = null;
264 for (Annotation a : paramAnnotations[i]) {
265 if (a.annotationType().equals(Param.class)) {
266 paramName = ((Param) a).value();
267 break;
268 }
269 }
270 if (hasParamAnnotation == null)
271 hasParamAnnotation = (paramName != null);
272 if (hasParamAnnotation != (paramName != null))
273 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()));
274
275 paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), i, paramName, paramTypes[i], paramAnnotations[i], mappingManager);
276 }
277
278 ConsistencyLevel cl = null;
279 int fetchSize = -1;
280 boolean tracing = false;
281
282 QueryParameters options = m.getAnnotation(QueryParameters.class);
283 if (options != null) {
284 cl = options.consistency().isEmpty() ? null : ConsistencyLevel.valueOf(options.consistency().toUpperCase());
285 fetchSize = options.fetchSize();
286 tracing = options.tracing();
287 }
288
289 methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing));
290 }
291
292 return factory.create(accClass, methods);
293 }
294
295 @SuppressWarnings({ "unchecked", "rawtypes" })
296 private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
297 if (paramType instanceof Class) {
298 Class<?> paramClass = (Class<?>) paramType;
299 if (paramClass.isAnnotationPresent(UDT.class)) {
300 UDTMapper<?> udtMapper = mappingManager.getUDTMapper(paramClass);
301 return new UDTParamMapper(paramName, idx, udtMapper);
302 } else if (paramClass.isEnum()) {
303 EnumType enumType = EnumType.STRING;
304 for (Annotation annotation : paramAnnotations) {
305 if (annotation instanceof Enumerated) {
306 enumType = ((Enumerated) annotation).value();
307 }
308 }
309 return new EnumParamMapper(paramName, idx, enumType);
310 }
311 return new ParamMapper(paramName, idx);
312 } if (paramType instanceof ParameterizedType) {
313 InferredCQLType inferredCQLType = InferredCQLType.from(className, methodName, idx, paramName, paramType, mappingManager);
314 if (inferredCQLType.containsMappedUDT) {
315 // We need a specialized mapper to convert UDT instances in the hierarchy.
316 return new NestedUDTParamMapper(paramName, idx, inferredCQLType);
317 } else {
318 // Use the default mapper but provide the extracted type
319 return new ParamMapper(paramName, idx, inferredCQLType.dataType);
320 }
321 } else {
322 throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName));
323 }
324 }
325}