| 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.Metadata; |
| 19 | import com.datastax.driver.core.TypeCodec; |
| 20 | import com.google.common.reflect.TypeToken; |
| 21 | |
| 22 | import java.lang.reflect.Field; |
| 23 | import java.util.concurrent.atomic.AtomicInteger; |
| 24 | |
| 25 | abstract class ColumnMapper<T> { |
| 26 | |
| 27 | enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED} |
| 28 | |
| 29 | private final String columnName; |
| 30 | private final String alias; |
| 31 | protected final String fieldName; |
| 32 | /** |
| 33 | * The type of the Java field in the mapped class |
| 34 | */ |
| 35 | protected final TypeToken<Object> fieldType; |
| 36 | protected final Kind kind; |
| 37 | protected final int position; |
| 38 | protected final TypeCodec<Object> customCodec; |
| 39 | |
| 40 | @SuppressWarnings("unchecked") |
| 41 | protected ColumnMapper(Field field, int position, AtomicInteger columnCounter) { |
| 42 | this.columnName = AnnotationParser.columnName(field); |
| 43 | this.alias = (columnCounter != null) |
| 44 | ? AnnotationParser.newAlias(field, columnCounter.incrementAndGet()) |
| 45 | : null; |
| 46 | this.fieldName = field.getName(); |
| 47 | this.fieldType = (TypeToken<Object>) TypeToken.of(field.getGenericType()); |
| 48 | this.kind = AnnotationParser.kind(field); |
| 49 | this.position = position; |
| 50 | this.customCodec = AnnotationParser.customCodec(field); |
| 51 | } |
| 52 | |
| 53 | abstract Object getValue(T entity); |
| 54 | |
| 55 | abstract void setValue(T entity, Object value); |
| 56 | |
| 57 | String getColumnName() { |
| 58 | return kind == Kind.COMPUTED |
| 59 | ? columnName |
| 60 | : Metadata.quote(columnName); |
| 61 | } |
| 62 | |
| 63 | String getAlias() { |
| 64 | return alias; |
| 65 | } |
| 66 | |
| 67 | public TypeCodec<Object> getCustomCodec() { |
| 68 | return customCodec; |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * The Java type of this column. |
| 73 | */ |
| 74 | public TypeToken<Object> getJavaType() { |
| 75 | return fieldType; |
| 76 | } |
| 77 | } |