Elffuss BraidHub

kikocis/java-driver public

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