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