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