Elffuss BraidHub

kikocis/java-driver public

01c1288c6b3c · 15.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 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;
28import com.google.common.reflect.TypeToken;
29
30import com.datastax.driver.core.ConsistencyLevel;
31import com.datastax.driver.core.TypeCodec;
32import com.datastax.driver.core.UserType;
33import com.datastax.driver.mapping.MethodMapper.ParamMapper;
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, 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> MappedUDTCodec<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 codec 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 UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName);
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, 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 List<ColumnMapper<T>> columnMappers = convert(columns, factory, udtClass, mappingManager, null);
157 return new MappedUDTCodec<T>(userType, udtClass, columnMappers, mappingManager);
158 }
159
160 private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
161 List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
162 for (int i = 0; i < fields.size(); i++) {
163 Field field = fields.get(i);
164 int pos = position(field);
165 mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter));
166 }
167 return mappers;
168 }
169
170 private static void validateOrder(List<Field> fields, String annotation) {
171 for (int i = 0; i < fields.size(); i++) {
172 Field field = fields.get(i);
173 int pos = position(field);
174 if (pos != i)
175 throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of column %s, was expecting %d",
176 pos, annotation, field.getName(), i));
177 }
178 }
179
180 private static int position(Field field) {
181 switch (kind(field)) {
182 case PARTITION_KEY:
183 return field.getAnnotation(PartitionKey.class).value();
184 case CLUSTERING_COLUMN:
185 return field.getAnnotation(ClusteringColumn.class).value();
186 default:
187 return -1;
188 }
189 }
190
191 public static ColumnMapper.Kind kind(Field field) {
192 PartitionKey pk = field.getAnnotation(PartitionKey.class);
193 ClusteringColumn cc = field.getAnnotation(ClusteringColumn.class);
194 Computed comp = field.getAnnotation(Computed.class);
195 if (pk != null && cc != null)
196 throw new IllegalArgumentException("Field " + field.getName() + " cannot have both the @PartitionKey and @ClusteringColumn annotations");
197
198 if (pk != null) {
199 return ColumnMapper.Kind.PARTITION_KEY;
200 }
201 if (cc != null) {
202 return ColumnMapper.Kind.CLUSTERING_COLUMN;
203 }
204 if (comp != null) {
205 return ColumnMapper.Kind.COMPUTED;
206 }
207 return ColumnMapper.Kind.REGULAR;
208 }
209
210 public static String columnName(Field field) {
211 Column column = field.getAnnotation(Column.class);
212 Computed computedField = field.getAnnotation(Computed.class);
213 if (column != null && !column.name().isEmpty()) {
214 if (computedField != null){
215 throw new IllegalArgumentException("Cannot use @Column and @Computed on the same field");
216 }
217 return column.caseSensitive() ? column.name() : column.name().toLowerCase();
218 }
219
220 com.datastax.driver.mapping.annotations.Field udtField = field.getAnnotation(com.datastax.driver.mapping.annotations.Field.class);
221 if (udtField != null && !udtField.name().isEmpty()) {
222 return udtField.caseSensitive() ? udtField.name() : udtField.name().toLowerCase();
223 }
224
225 if (computedField != null) {
226 return computedField.value();
227 }
228
229 return field.getName().toLowerCase();
230 }
231
232 public static String newAlias(Field field, int columnNumber) {
233 return "col" + columnNumber;
234
235 }
236
237 public static TypeCodec<Object> customCodec(Field field) {
238 Class<? extends TypeCodec<?>> codecClass = getCodecClass(field);
239
240 if (codecClass.equals(Defaults.NoCodec.class))
241 return null;
242
243 try {
244 @SuppressWarnings("unchecked")
245 TypeCodec<Object> instance = (TypeCodec<Object>)codecClass.newInstance();
246 return instance;
247 } catch (Exception e) {
248 throw new IllegalArgumentException(String.format(
249 "Cannot create an instance of custom codec %s for field %s",
250 codecClass, field
251 ), e);
252 }
253 }
254
255 private static Class<? extends TypeCodec<?>> getCodecClass(Field field) {
256 Column column = field.getAnnotation(Column.class);
257 if (column != null)
258 return column.codec();
259
260 com.datastax.driver.mapping.annotations.Field udtField = field.getAnnotation(com.datastax.driver.mapping.annotations.Field.class);
261 if (udtField != null)
262 return udtField.codec();
263
264 return Defaults.NoCodec.class;
265 }
266
267 public static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) {
268 if (!accClass.isInterface())
269 throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
270
271 AnnotationChecks.getTypeAnnotation(Accessor.class, accClass);
272
273 List<MethodMapper> methods = new ArrayList<MethodMapper>();
274 for (Method m : accClass.getDeclaredMethods()) {
275 Query query = m.getAnnotation(Query.class);
276 if (query == null)
277 continue;
278
279 String queryString = query.value();
280
281 Annotation[][] paramAnnotations = m.getParameterAnnotations();
282 Type[] paramTypes = m.getGenericParameterTypes();
283 ParamMapper[] paramMappers = new ParamMapper[paramAnnotations.length];
284 Boolean allParamsNamed = null;
285 for (int i = 0; i < paramMappers.length; i++) {
286 String paramName = null;
287 Class<? extends TypeCodec<?>> codecClass = null;
288 for (Annotation a : paramAnnotations[i]) {
289 if (a.annotationType().equals(Param.class)) {
290 Param param = (Param)a;
291 paramName = param.value();
292 if (paramName.isEmpty())
293 paramName = null;
294 codecClass = param.codec();
295 if (Defaults.NoCodec.class.equals(codecClass))
296 codecClass = null;
297 break;
298 }
299 }
300 boolean thisParamNamed = (paramName != null);
301 if (allParamsNamed == null)
302 allParamsNamed = thisParamNamed;
303 else if (allParamsNamed != thisParamNamed)
304 throw new IllegalArgumentException(String.format("For method '%s', either all or none of the parameters must be named", m.getName()));
305
306 paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), i, paramName, codecClass, paramTypes[i], paramAnnotations[i], mappingManager);
307 }
308
309 ConsistencyLevel cl = null;
310 int fetchSize = -1;
311 boolean tracing = false;
312
313 QueryParameters options = m.getAnnotation(QueryParameters.class);
314 if (options != null) {
315 cl = options.consistency().isEmpty() ? null : ConsistencyLevel.valueOf(options.consistency().toUpperCase());
316 fetchSize = options.fetchSize();
317 tracing = options.tracing();
318 }
319
320 methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing));
321 }
322
323 return factory.create(accClass, methods);
324 }
325
326 @SuppressWarnings({ "unchecked", "rawtypes" })
327 private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Class<? extends TypeCodec<?>> codecClass, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
328 if (paramType instanceof Class) {
329 Class<?> paramClass = (Class<?>) paramType;
330 if (TypeMappings.isMappedUDT(paramClass))
331 mappingManager.getUDTCodec(paramClass);
332
333 return new ParamMapper(paramName, idx, TypeToken.of(paramType), codecClass);
334 } else if (paramType instanceof ParameterizedType) {
335 for (Class<?> udt : TypeMappings.findUDTs(paramType))
336 mappingManager.getUDTCodec(udt);
337
338 return new ParamMapper(paramName, idx, TypeToken.of(paramType), codecClass);
339 } else {
340 throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName));
341 }
342 }
343}