Elffuss BraidHub

kikocis/java-driver public

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