Elffuss BraidHub

kikocis/java-driver public

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