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