Elffuss BraidHub

kikocis/java-driver public

7fd6e7576530 · 14.1 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2014 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.*;
20import java.lang.reflect.Field;
21import java.util.*;
22
23import com.google.common.collect.ImmutableSet.Builder;
24import com.google.common.collect.ImmutableSet;
25
26import com.datastax.driver.mapping.annotations.Frozen;
27
28import com.datastax.driver.core.ConsistencyLevel;
29import com.datastax.driver.core.DataType;
30
31import com.datastax.driver.mapping.MethodMapper.ParamMapper;
32import com.datastax.driver.mapping.MethodMapper.UDTListParamMapper;
33import com.datastax.driver.mapping.MethodMapper.UDTMapParamMapper;
34import com.datastax.driver.mapping.MethodMapper.UDTParamMapper;
35import com.datastax.driver.mapping.MethodMapper.UDTSetParamMapper;
36import com.datastax.driver.mapping.MethodMapper.EnumParamMapper;
37import com.datastax.driver.mapping.annotations.*;
38import com.google.common.base.Strings;
39
40/**
41 * Static metods that facilitates parsing class annotations into the corresponding {@link EntityMapper}.
42 */
43class AnnotationParser {
44
45 private static final Comparator<Field> fieldComparator = new Comparator<Field>() {
46 public int compare(Field f1, Field f2) {
47 return position(f1) - position(f2);
48 }
49 };
50
51 private AnnotationParser() {}
52
53 public static <T> EntityMapper<T> parseEntity(Class<T> entityClass, EntityMapper.Factory factory, MappingManager mappingManager) {
54 Table table = AnnotationChecks.getTypeAnnotation(Table.class, entityClass);
55
56 String ksName = table.caseSensitiveKeyspace() ? table.keyspace() : table.keyspace().toLowerCase();
57 String tableName = table.caseSensitiveTable() ? table.name() : table.name().toLowerCase();
58
59 ConsistencyLevel writeConsistency = table.writeConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.writeConsistency().toUpperCase());
60 ConsistencyLevel readConsistency = table.readConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.readConsistency().toUpperCase());
61
62 if (Strings.isNullOrEmpty(table.keyspace())) {
63 ksName = mappingManager.getSession().getLoggedKeyspace();
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 AnnotationChecks.validateAnnotations(field, "entity",
77 Column.class, ClusteringColumn.class, Enumerated.class, Frozen.class, FrozenKey.class,
78 FrozenValue.class, PartitionKey.class, Transient.class);
79
80 if (field.getAnnotation(Transient.class) != null)
81 continue;
82
83 switch (kind(field)) {
84 case PARTITION_KEY:
85 pks.add(field);
86 break;
87 case CLUSTERING_COLUMN:
88 ccs.add(field);
89 break;
90 default:
91 rgs.add(field);
92 break;
93 }
94 }
95
96 Collections.sort(pks, fieldComparator);
97 Collections.sort(ccs, fieldComparator);
98
99 validateOrder(pks, "@PartitionKey");
100 validateOrder(ccs, "@ClusteringColumn");
101
102 mapper.addColumns(convert(pks, factory, mapper.entityClass, mappingManager),
103 convert(ccs, factory, mapper.entityClass, mappingManager),
104 convert(rgs, factory, mapper.entityClass, mappingManager));
105 return mapper;
106 }
107
108 public static <T> EntityMapper<T> parseUDT(Class<T> udtClass, EntityMapper.Factory factory, MappingManager mappingManager) {
109 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
110
111 String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase();
112 String udtName = udt.caseSensitiveType() ? udt.name() : udt.name().toLowerCase();
113
114 if (Strings.isNullOrEmpty(udt.keyspace())) {
115 ksName = mappingManager.getSession().getLoggedKeyspace();
116 }
117
118 EntityMapper<T> mapper = factory.create(udtClass, ksName, udtName, null, null);
119
120 List<Field> columns = new ArrayList<Field>();
121
122 for (Field field : udtClass.getDeclaredFields()) {
123 if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
124 continue;
125
126 AnnotationChecks.validateAnnotations(field, "UDT",
127 com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
128 FrozenValue.class, Enumerated.class, Transient.class);
129
130 if (field.getAnnotation(Transient.class) != null)
131 continue;
132
133 switch (kind(field)) {
134 case PARTITION_KEY:
135 throw new IllegalArgumentException("Annotation @PartitionKey is not allowed in a class annotated by @UDT");
136 case CLUSTERING_COLUMN:
137 throw new IllegalArgumentException("Annotation @ClusteringColumn is not allowed in a class annotated by @UDT");
138 default:
139 columns.add(field);
140 break;
141 }
142 }
143
144 mapper.addColumns(convert(columns, factory, udtClass, mappingManager));
145 return mapper;
146 }
147
148 private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager) {
149 List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
150 for (int i = 0; i < fields.size(); i++) {
151 Field field = fields.get(i);
152 int pos = position(field);
153 mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager));
154 }
155 return mappers;
156 }
157
158 private static void validateOrder(List<Field> fields, String annotation) {
159 for (int i = 0; i < fields.size(); i++) {
160 Field field = fields.get(i);
161 int pos = position(field);
162 if (pos != i)
163 throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of column %s, was expecting %d",
164 pos, annotation, field.getName(), i));
165 }
166 }
167
168 private static int position(Field field) {
169 switch (kind(field)) {
170 case PARTITION_KEY:
171 return field.getAnnotation(PartitionKey.class).value();
172 case CLUSTERING_COLUMN:
173 return field.getAnnotation(ClusteringColumn.class).value();
174 default:
175 return -1;
176 }
177 }
178
179 public static ColumnMapper.Kind kind(Field field) {
180 PartitionKey pk = field.getAnnotation(PartitionKey.class);
181 ClusteringColumn cc = field.getAnnotation(ClusteringColumn.class);
182 if (pk != null && cc != null)
183 throw new IllegalArgumentException("Field " + field.getName() + " cannot have both the @PartitionKey and @ClusteringColumn annotations");
184
185 return pk != null
186 ? ColumnMapper.Kind.PARTITION_KEY
187 : (cc != null ? ColumnMapper.Kind.CLUSTERING_COLUMN : ColumnMapper.Kind.REGULAR);
188 }
189
190 public static EnumType enumType(Field field) {
191 Class<?> type = field.getType();
192 if (!type.isEnum())
193 return null;
194
195 Enumerated enumerated = field.getAnnotation(Enumerated.class);
196 return (enumerated == null) ? EnumType.STRING : enumerated.value();
197 }
198
199 public static String columnName(Field field) {
200 Column column = field.getAnnotation(Column.class);
201 if (column != null) {
202 return column.caseSensitive() ? column.name() : column.name().toLowerCase();
203 }
204
205 com.datastax.driver.mapping.annotations.Field udtField = field.getAnnotation(com.datastax.driver.mapping.annotations.Field.class);
206 if (udtField != null) {
207 return udtField.caseSensitive() ? udtField.name() : udtField.name().toLowerCase();
208 }
209
210 return field.getName().toLowerCase();
211 }
212
213 public static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) {
214 if (!accClass.isInterface())
215 throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
216
217 AnnotationChecks.getTypeAnnotation(Accessor.class, accClass);
218
219 List<MethodMapper> methods = new ArrayList<MethodMapper>();
220 for (Method m : accClass.getDeclaredMethods()) {
221 Query query = m.getAnnotation(Query.class);
222 if (query == null)
223 continue;
224
225 String queryString = query.value();
226
227 Annotation[][] paramAnnotations = m.getParameterAnnotations();
228 Type[] paramTypes = m.getGenericParameterTypes();
229 ParamMapper[] paramMappers = new ParamMapper[paramAnnotations.length];
230 Boolean hasParamAnnotation = null;
231 for (int i = 0; i < paramMappers.length; i++) {
232 String paramName = null;
233 for (Annotation a : paramAnnotations[i]) {
234 if (a.annotationType().equals(Param.class)) {
235 paramName = ((Param) a).value();
236 break;
237 }
238 }
239 if (hasParamAnnotation == null)
240 hasParamAnnotation = (paramName != null);
241 if (hasParamAnnotation != (paramName != null))
242 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()));
243
244 paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), i, paramName, paramTypes[i], paramAnnotations[i], mappingManager);
245 }
246
247 ConsistencyLevel cl = null;
248 int fetchSize = -1;
249 boolean tracing = false;
250
251 QueryParameters options = m.getAnnotation(QueryParameters.class);
252 if (options != null) {
253 cl = options.consistency().isEmpty() ? null : ConsistencyLevel.valueOf(options.consistency().toUpperCase());
254 fetchSize = options.fetchSize();
255 tracing = options.tracing();
256 }
257
258 methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing));
259 }
260
261 return factory.create(accClass, methods);
262 }
263
264 @SuppressWarnings({ "unchecked", "rawtypes" })
265 private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
266 if (paramType instanceof Class) {
267 Class<?> paramClass = (Class<?>) paramType;
268 if (paramClass.isAnnotationPresent(UDT.class)) {
269 UDTMapper<?> udtMapper = mappingManager.getUDTMapper(paramClass);
270 return new UDTParamMapper(paramName, idx, udtMapper);
271 } else if (paramClass.isEnum()) {
272 EnumType enumType = EnumType.STRING;
273 for (Annotation annotation : paramAnnotations) {
274 if (annotation instanceof Enumerated) {
275 enumType = ((Enumerated) annotation).value();
276 }
277 }
278 return new EnumParamMapper(paramName, idx, enumType);
279 }
280 return new ParamMapper(paramName, idx);
281 } if (paramType instanceof ParameterizedType) {
282 ParameterizedType pt = (ParameterizedType) paramType;
283 Type raw = pt.getRawType();
284 if (!(raw instanceof Class))
285 throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName));
286 Class<?> klass = (Class<?>)raw;
287 Class<?> firstTypeParam = ReflectionUtils.getParam(pt, 0, paramName);
288 if (List.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
289 UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
290 return new UDTListParamMapper(paramName, idx, valueMapper);
291 }
292 if (Set.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
293 UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
294 return new UDTSetParamMapper(paramName, idx, valueMapper);
295 }
296 if (Map.class.isAssignableFrom(klass)) {
297 Class<?> secondTypeParam = ReflectionUtils.getParam(pt, 1, paramName);
298 UDTMapper<?> keyMapper = firstTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(firstTypeParam) : null;
299 UDTMapper<?> valueMapper = secondTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(secondTypeParam) : null;
300 if (keyMapper != null || valueMapper != null) {
301 return new UDTMapParamMapper(paramName, idx, keyMapper, valueMapper);
302 }
303 }
304 return new ParamMapper(paramName, idx);
305 } else {
306 throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName));
307 }
308 }
309}