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