Elffuss BraidHub

kikocis/java-driver public

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