| 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.DataType; |
| 19 | |
| 20 | import java.lang.reflect.Field; |
| 21 | import java.util.concurrent.atomic.AtomicInteger; |
| 22 | |
| 23 | import static com.datastax.driver.core.querybuilder.QueryBuilder.quote; |
| 24 | |
| 25 | abstract class ColumnMapper<T> { |
| 26 | |
| 27 | public enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED} |
| 28 | |
| 29 | ; |
| 30 | |
| 31 | private final String columnName; |
| 32 | private final String alias; |
| 33 | protected final String fieldName; |
| 34 | protected final Class<?> javaType; |
| 35 | // Note: dataType is not guaranteed to be exact. Typically, it will be uuid even if the underlying |
| 36 | // type is timeuuid. Currently, this is not a problem, but we might allow some @Timeuuid annotation |
| 37 | // for the sake of validation (similarly, we'll always have text, never ascii). |
| 38 | protected final DataType dataType; |
| 39 | protected final Kind kind; |
| 40 | protected final int position; |
| 41 | |
| 42 | protected ColumnMapper(Field field, DataType dataType, int position, AtomicInteger columnCounter) { |
| 43 | this.columnName = AnnotationParser.columnName(field); |
| 44 | this.alias = (columnCounter != null) |
| 45 | ? AnnotationParser.newAlias(field, columnCounter.incrementAndGet()) |
| 46 | : null; |
| 47 | this.fieldName = field.getName(); |
| 48 | this.javaType = field.getType(); |
| 49 | this.dataType = dataType; |
| 50 | this.kind = AnnotationParser.kind(field); |
| 51 | this.position = position; |
| 52 | } |
| 53 | |
| 54 | public abstract Object getValue(T entity); |
| 55 | |
| 56 | public abstract void setValue(T entity, Object value); |
| 57 | |
| 58 | public String getColumnName() { |
| 59 | return kind == Kind.COMPUTED |
| 60 | ? columnName |
| 61 | : quote(columnName); |
| 62 | } |
| 63 | |
| 64 | public String getAlias() { |
| 65 | return alias; |
| 66 | } |
| 67 | |
| 68 | public DataType getDataType() { |
| 69 | return dataType; |
| 70 | } |
| 71 | |
| 72 | } |