Elffuss BraidHub

kikocis/java-driver public

f0d09a3f14f2 · 13.1 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.TableMetadata;
21import com.datastax.driver.core.TypeCodec;
22import com.datastax.driver.core.UserType;
23import com.datastax.driver.mapping.MethodMapper.ParamMapper;
24import com.datastax.driver.mapping.annotations.*;
25import com.google.common.annotations.VisibleForTesting;
26import com.google.common.base.Strings;
27import com.google.common.collect.ImmutableSet;
28import com.google.common.reflect.TypeToken;
29
30import java.beans.PropertyDescriptor;
31import java.lang.annotation.Annotation;
32import java.lang.reflect.Method;
33import java.lang.reflect.ParameterizedType;
34import java.lang.reflect.Type;
35import java.util.*;
36import java.util.concurrent.atomic.AtomicInteger;
37
38/**
39 * Static methods that facilitates parsing:
40 * - {@link #parseEntity(Class, MappingManager)}: entity classes into {@link EntityMapper} instances
41 * - {@link #parseUDT(Class, MappingManager)}: UDT classes into {@link MappedUDTCodec} instances.
42 * - {@link #parseAccessor(Class, MappingManager)}: Accessor interfaces into {@link AccessorMapper} instances.
43 */
44@SuppressWarnings({"unchecked", "WeakerAccess"})
45class AnnotationParser {
46
47 @VisibleForTesting
48 static final Set<Class<? extends Annotation>> VALID_PROPERTY_ANNOTATIONS = ImmutableSet.of(
49 Column.class,
50 Computed.class,
51 ClusteringColumn.class,
52 Frozen.class,
53 FrozenKey.class,
54 FrozenValue.class,
55 PartitionKey.class,
56 Transient.class);
57
58 @VisibleForTesting
59 static final Set<Class<? extends Annotation>> VALID_FIELD_ANNOTATIONS = ImmutableSet.of(
60 Field.class,
61 Frozen.class,
62 FrozenKey.class,
63 FrozenValue.class,
64 Transient.class);
65
66 private static final Comparator<PropertyMapper> POSITION_COMPARATOR = new Comparator<PropertyMapper>() {
67 @Override
68 public int compare(PropertyMapper o1, PropertyMapper o2) {
69 return o1.position - o2.position;
70 }
71 };
72
73 private AnnotationParser() {
74 }
75
76 static <T> EntityMapper<T> parseEntity(final Class<T> entityClass, MappingManager mappingManager) {
77 Table table = AnnotationChecks.getTypeAnnotation(Table.class, entityClass);
78
79 String ksName = table.caseSensitiveKeyspace() ? Metadata.quote(table.keyspace()) : table.keyspace().toLowerCase();
80 String tableName = table.caseSensitiveTable() ? Metadata.quote(table.name()) : table.name().toLowerCase();
81
82 ConsistencyLevel writeConsistency = table.writeConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.writeConsistency().toUpperCase());
83 ConsistencyLevel readConsistency = table.readConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.readConsistency().toUpperCase());
84
85 if (Strings.isNullOrEmpty(table.keyspace())) {
86 String loggedKeyspace = mappingManager.getSession().getLoggedKeyspace();
87 if (Strings.isNullOrEmpty(loggedKeyspace))
88 throw new IllegalArgumentException(String.format(
89 "Error creating mapper for %s, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace",
90 entityClass
91 ));
92 ksName = Metadata.quote(loggedKeyspace);
93 }
94
95 EntityMapper<T> mapper = new EntityMapper<T>(entityClass, ksName, tableName, writeConsistency, readConsistency);
96 TableMetadata tableMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getTable(tableName);
97
98 if (tableMetadata == null)
99 throw new IllegalArgumentException(String.format("Table %s does not exist in keyspace %s", tableName, ksName));
100
101 List<PropertyMapper> pks = new ArrayList<PropertyMapper>();
102 List<PropertyMapper> ccs = new ArrayList<PropertyMapper>();
103 List<PropertyMapper> rgs = new ArrayList<PropertyMapper>();
104
105 Map<String, Object[]> fieldsAndProperties = ReflectionUtils.scanFieldsAndProperties(entityClass);
106 AtomicInteger columnCounter = mappingManager.isCassandraV1 ? null : new AtomicInteger(0);
107
108 for (Map.Entry<String, Object[]> entry : fieldsAndProperties.entrySet()) {
109
110 String propertyName = entry.getKey();
111 java.lang.reflect.Field field = (java.lang.reflect.Field) entry.getValue()[0];
112 PropertyDescriptor property = (PropertyDescriptor) entry.getValue()[1];
113 String alias = (columnCounter != null)
114 ? "col" + columnCounter.incrementAndGet()
115 : null;
116
117 PropertyMapper propertyMapper = new PropertyMapper(entityClass, propertyName, alias, field, property);
118
119 if (mappingManager.isCassandraV1 && propertyMapper.isComputed())
120 throw new UnsupportedOperationException("Computed properties are not supported with native protocol v1");
121
122 AnnotationChecks.validateAnnotations(propertyMapper, VALID_PROPERTY_ANNOTATIONS);
123
124 if (propertyMapper.isTransient())
125 continue;
126
127 if (!propertyMapper.isComputed() && tableMetadata.getColumn(propertyMapper.columnName) == null)
128 throw new IllegalArgumentException(String.format("Column %s does not exist in table %s.%s",
129 propertyMapper.columnName, ksName, tableName));
130
131 if (propertyMapper.isPartitionKey())
132 pks.add(propertyMapper);
133 else if (propertyMapper.isClusteringColumn())
134 ccs.add(propertyMapper);
135 else
136 rgs.add(propertyMapper);
137
138 // if the property is of a UDT type, parse it now
139 for (Class<?> udt : TypeMappings.findUDTs(propertyMapper.javaType.getType()))
140 mappingManager.getUDTCodec(udt);
141 }
142
143 Collections.sort(pks, POSITION_COMPARATOR);
144 Collections.sort(ccs, POSITION_COMPARATOR);
145
146 AnnotationChecks.validateOrder(pks, "@PartitionKey");
147 AnnotationChecks.validateOrder(ccs, "@ClusteringColumn");
148
149 mapper.addColumns(pks, ccs, rgs);
150 return mapper;
151 }
152
153 static <T> MappedUDTCodec<T> parseUDT(Class<T> udtClass, MappingManager mappingManager) {
154 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
155
156 String ksName = udt.caseSensitiveKeyspace() ? Metadata.quote(udt.keyspace()) : udt.keyspace().toLowerCase();
157 String udtName = udt.caseSensitiveType() ? Metadata.quote(udt.name()) : udt.name().toLowerCase();
158
159 if (Strings.isNullOrEmpty(udt.keyspace())) {
160 String loggedKeyspace = mappingManager.getSession().getLoggedKeyspace();
161 if (Strings.isNullOrEmpty(loggedKeyspace))
162 throw new IllegalArgumentException(String.format(
163 "Error creating UDT codec for %s, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace",
164 udtClass
165 ));
166 ksName = Metadata.quote(loggedKeyspace);
167 }
168
169 UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName);
170 if (userType == null)
171 throw new IllegalArgumentException(String.format("User type %s does not exist in keyspace %s", udtName, ksName));
172
173 Map<String, PropertyMapper> propertyMappers = new HashMap<String, PropertyMapper>();
174
175 Map<String, Object[]> fieldsAndProperties = ReflectionUtils.scanFieldsAndProperties(udtClass);
176
177 for (Map.Entry<String, Object[]> entry : fieldsAndProperties.entrySet()) {
178
179 String propertyName = entry.getKey();
180 java.lang.reflect.Field field = (java.lang.reflect.Field) entry.getValue()[0];
181 PropertyDescriptor property = (PropertyDescriptor) entry.getValue()[1];
182
183 PropertyMapper propertyMapper = new PropertyMapper(udtClass, propertyName, null, field, property);
184
185 AnnotationChecks.validateAnnotations(propertyMapper, VALID_FIELD_ANNOTATIONS);
186
187 if (propertyMapper.isTransient())
188 continue;
189
190 if (!userType.contains(propertyMapper.columnName))
191 throw new IllegalArgumentException(String.format("Field %s does not exist in type %s.%s",
192 propertyMapper.columnName, ksName, userType.getTypeName()));
193
194 propertyMappers.put(propertyMapper.columnName, propertyMapper);
195 }
196
197 return new MappedUDTCodec<T>(userType, udtClass, propertyMappers, mappingManager);
198 }
199
200 static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, MappingManager mappingManager) {
201 if (!accClass.isInterface())
202 throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces, got " + accClass);
203
204 AnnotationChecks.getTypeAnnotation(Accessor.class, accClass);
205
206 List<MethodMapper> methods = new ArrayList<MethodMapper>();
207 for (Method m : accClass.getDeclaredMethods()) {
208 Query query = m.getAnnotation(Query.class);
209 if (query == null)
210 continue;
211
212 String queryString = query.value();
213
214 Annotation[][] paramAnnotations = m.getParameterAnnotations();
215 Type[] paramTypes = m.getGenericParameterTypes();
216 ParamMapper[] paramMappers = new ParamMapper[paramAnnotations.length];
217 Boolean allParamsNamed = null;
218 for (int i = 0; i < paramMappers.length; i++) {
219 String paramName = null;
220 Class<? extends TypeCodec<?>> codecClass = null;
221 for (Annotation a : paramAnnotations[i]) {
222 if (a.annotationType().equals(Param.class)) {
223 Param param = (Param) a;
224 paramName = param.value();
225 if (paramName.isEmpty())
226 paramName = null;
227 codecClass = param.codec();
228 if (Defaults.NoCodec.class.equals(codecClass))
229 codecClass = null;
230 break;
231 }
232 }
233 boolean thisParamNamed = (paramName != null);
234 if (allParamsNamed == null)
235 allParamsNamed = thisParamNamed;
236 else if (allParamsNamed != thisParamNamed)
237 throw new IllegalArgumentException(String.format("For method '%s', either all or none of the parameters must be named", m.getName()));
238
239 paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), i, paramName, codecClass, paramTypes[i], mappingManager);
240 }
241
242 ConsistencyLevel cl = null;
243 int fetchSize = -1;
244 boolean tracing = false;
245 Boolean idempotent = null;
246
247 QueryParameters options = m.getAnnotation(QueryParameters.class);
248 if (options != null) {
249 cl = options.consistency().isEmpty() ? null : ConsistencyLevel.valueOf(options.consistency().toUpperCase());
250 fetchSize = options.fetchSize();
251 tracing = options.tracing();
252 if (options.idempotent().length > 1) {
253 throw new IllegalStateException("idemtpotence() attribute can only accept one value");
254 }
255 idempotent = options.idempotent().length == 0 ? null : options.idempotent()[0];
256 }
257
258 methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing, idempotent));
259 }
260
261 return new AccessorMapper<T>(accClass, methods);
262 }
263
264 private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Class<? extends TypeCodec<?>> codecClass, Type paramType, MappingManager mappingManager) {
265 if (paramType instanceof Class) {
266 Class<?> paramClass = (Class<?>) paramType;
267 if (TypeMappings.isMappedUDT(paramClass))
268 mappingManager.getUDTCodec(paramClass);
269
270 return new ParamMapper(paramName, idx, TypeToken.of(paramType), codecClass);
271 } else if (paramType instanceof ParameterizedType) {
272 for (Class<?> udt : TypeMappings.findUDTs(paramType))
273 mappingManager.getUDTCodec(udt);
274
275 return new ParamMapper(paramName, idx, TypeToken.of(paramType), codecClass);
276 } else {
277 throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName));
278 }
279 }
280}