Elffuss BraidHub

kikocis/java-driver public

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