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