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