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