Elffuss BraidHub

kikocis/java-driver public

6b338834ef4e · 14.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 java.lang.annotation.Annotation;
19import java.lang.reflect.Field;
20import java.lang.reflect.*;
21import java.util.ArrayList;
22import java.util.Collections;
23import java.util.Comparator;
24import java.util.List;
25import java.util.concurrent.atomic.AtomicInteger;
26
27import com.google.common.base.Strings;
28
29import com.datastax.driver.core.ConsistencyLevel;
30import com.datastax.driver.mapping.MethodMapper.EnumParamMapper;
31import com.datastax.driver.mapping.MethodMapper.NestedUDTParamMapper;
32import com.datastax.driver.mapping.MethodMapper.ParamMapper;
33import com.datastax.driver.mapping.MethodMapper.UDTParamMapper;
34import com.datastax.driver.mapping.annotations.*;
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 public int compare(Field f1, Field f2) {
43 return position(f1) - position(f2);
44 }
45 };
46
47 private AnnotationParser() {}
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, Enumerated.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(convert(pks, factory, mapper.entityClass, mappingManager, columnCounter),
110 convert(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
111 convert(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
112 return mapper;
113 }
114
115 public static <T> EntityMapper<T> parseUDT(Class<T> udtClass, EntityMapper.Factory factory, MappingManager mappingManager) {
116 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
117
118 String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase();
119 String udtName = udt.caseSensitiveType() ? udt.name() : udt.name().toLowerCase();
120
121 if (Strings.isNullOrEmpty(udt.keyspace())) {
122 ksName = mappingManager.getSession().getLoggedKeyspace();
123 if (Strings.isNullOrEmpty(ksName))
124 throw new IllegalArgumentException(String.format(
125 "Error creating UDT mapper for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
126 udtClass.getSimpleName(),
127 UDT.class.getSimpleName()
128 ));
129 }
130
131 EntityMapper<T> mapper = factory.create(udtClass, ksName, udtName, null, null);
132
133 List<Field> columns = new ArrayList<Field>();
134
135 for (Field field : udtClass.getDeclaredFields()) {
136 if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
137 continue;
138
139 AnnotationChecks.validateAnnotations(field, "UDT",
140 com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
141 FrozenValue.class, Enumerated.class, Transient.class);
142
143 if (field.getAnnotation(Transient.class) != null)
144 continue;
145
146 switch (kind(field)) {
147 case PARTITION_KEY:
148 throw new IllegalArgumentException("Annotation @PartitionKey is not allowed in a class annotated by @UDT");
149 case CLUSTERING_COLUMN:
150 throw new IllegalArgumentException("Annotation @ClusteringColumn is not allowed in a class annotated by @UDT");
151 default:
152 columns.add(field);
153 break;
154 }
155 }
156
157 mapper.addColumns(convert(columns, factory, udtClass, mappingManager, null));
158 return mapper;
159 }
160
161 private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
162 List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
163 for (int i = 0; i < fields.size(); i++) {
164 Field field = fields.get(i);
165 int pos = position(field);
166 mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter));
167 }
168 return mappers;
169 }
170
171 private static void validateOrder(List<Field> fields, String annotation) {
172 for (int i = 0; i < fields.size(); i++) {
173 Field field = fields.get(i);
174 int pos = position(field);
175 if (pos != i)
176 throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of column %s, was expecting %d",
177 pos, annotation, field.getName(), i));
178 }
179 }
180
181 private static int position(Field field) {
182 switch (kind(field)) {
183 case PARTITION_KEY:
184 return field.getAnnotation(PartitionKey.class).value();
185 case CLUSTERING_COLUMN:
186 return field.getAnnotation(ClusteringColumn.class).value();
187 default:
188 return -1;
189 }
190 }
191
192 public static ColumnMapper.Kind kind(Field field) {
193 PartitionKey pk = field.getAnnotation(PartitionKey.class);
194 ClusteringColumn cc = field.getAnnotation(ClusteringColumn.class);
195 Computed comp = field.getAnnotation(Computed.class);
196 if (pk != null && cc != null)
197 throw new IllegalArgumentException("Field " + field.getName() + " cannot have both the @PartitionKey and @ClusteringColumn annotations");
198
199 if (pk != null) {
200 return ColumnMapper.Kind.PARTITION_KEY;
201 }
202 if (cc != null) {
203 return ColumnMapper.Kind.CLUSTERING_COLUMN;
204 }
205 if (comp != null) {
206 return ColumnMapper.Kind.COMPUTED;
207 }
208 return ColumnMapper.Kind.REGULAR;
209 }
210
211 public static EnumType enumType(Field field) {
212 Class<?> type = field.getType();
213 if (!type.isEnum())
214 return null;
215
216 Enumerated enumerated = field.getAnnotation(Enumerated.class);
217 return (enumerated == null) ? EnumType.STRING : enumerated.value();
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 <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) {
248 if (!accClass.isInterface())
249 throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
250
251 AnnotationChecks.getTypeAnnotation(Accessor.class, accClass);
252
253 List<MethodMapper> methods = new ArrayList<MethodMapper>();
254 for (Method m : accClass.getDeclaredMethods()) {
255 Query query = m.getAnnotation(Query.class);
256 if (query == null)
257 continue;
258
259 String queryString = query.value();
260
261 Annotation[][] paramAnnotations = m.getParameterAnnotations();
262 Type[] paramTypes = m.getGenericParameterTypes();
263 ParamMapper[] paramMappers = new ParamMapper[paramAnnotations.length];
264 Boolean hasParamAnnotation = null;
265 for (int i = 0; i < paramMappers.length; i++) {
266 String paramName = null;
267 for (Annotation a : paramAnnotations[i]) {
268 if (a.annotationType().equals(Param.class)) {
269 paramName = ((Param) a).value();
270 break;
271 }
272 }
273 if (hasParamAnnotation == null)
274 hasParamAnnotation = (paramName != null);
275 if (hasParamAnnotation != (paramName != null))
276 throw new IllegalArgumentException(String.format("For method '%s', either all or none of the paramaters of a method must have a @Param annotation", m.getName()));
277
278 paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), i, paramName, paramTypes[i], paramAnnotations[i], mappingManager);
279 }
280
281 ConsistencyLevel cl = null;
282 int fetchSize = -1;
283 boolean tracing = false;
284
285 QueryParameters options = m.getAnnotation(QueryParameters.class);
286 if (options != null) {
287 cl = options.consistency().isEmpty() ? null : ConsistencyLevel.valueOf(options.consistency().toUpperCase());
288 fetchSize = options.fetchSize();
289 tracing = options.tracing();
290 }
291
292 methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing));
293 }
294
295 return factory.create(accClass, methods);
296 }
297
298 @SuppressWarnings({ "unchecked", "rawtypes" })
299 private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
300 if (paramType instanceof Class) {
301 Class<?> paramClass = (Class<?>) paramType;
302 if (paramClass.isAnnotationPresent(UDT.class)) {
303 UDTMapper<?> udtMapper = mappingManager.getUDTMapper(paramClass);
304 return new UDTParamMapper(paramName, idx, udtMapper);
305 } else if (paramClass.isEnum()) {
306 EnumType enumType = EnumType.STRING;
307 for (Annotation annotation : paramAnnotations) {
308 if (annotation instanceof Enumerated) {
309 enumType = ((Enumerated) annotation).value();
310 }
311 }
312 return new EnumParamMapper(paramName, idx, enumType);
313 }
314 return new ParamMapper(paramName, idx);
315 } if (paramType instanceof ParameterizedType) {
316 InferredCQLType inferredCQLType = InferredCQLType.from(className, methodName, idx, paramName, paramType, mappingManager);
317 if (inferredCQLType.containsMappedUDT) {
318 // We need a specialized mapper to convert UDT instances in the hierarchy.
319 return new NestedUDTParamMapper(paramName, idx, inferredCQLType);
320 } else {
321 // Use the default mapper but provide the extracted type
322 return new ParamMapper(paramName, idx, inferredCQLType.dataType);
323 }
324 } else {
325 throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName));
326 }
327 }
328}