Elffuss BraidHub

kikocis/java-driver public

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