Elffuss BraidHub

kikocis/java-driver public

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