Elffuss BraidHub

kikocis/java-driver public

0d06ef6c86a5 · 9.5 KiBRawPermalink
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 */
16package com.datastax.driver.mapping;
17
18import java.beans.IntrospectionException;
19import java.beans.PropertyDescriptor;
20import java.lang.reflect.Field;
21import java.lang.reflect.ParameterizedType;
22import java.lang.reflect.Type;
23import java.lang.reflect.Method;
24import java.util.*;
25import java.util.concurrent.atomic.AtomicInteger;
26
27import com.datastax.driver.core.*;
28import com.datastax.driver.mapping.annotations.Computed;
29
30/**
31 * An {@link EntityMapper} implementation that use reflection to read and write fields
32 * of an entity.
33 */
34class ReflectionMapper<T> extends EntityMapper<T> {
35
36 private static ReflectionFactory factory = new ReflectionFactory();
37
38 private ReflectionMapper(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
39 super(entityClass, keyspace, table, writeConsistency, readConsistency);
40 }
41
42 public static Factory factory() {
43 return factory;
44 }
45
46 @Override
47 public T newEntity() {
48 try {
49 return entityClass.newInstance();
50 } catch (Exception e) {
51 throw new RuntimeException("Can't create an instance of " + entityClass.getName());
52 }
53 }
54
55 private static class LiteralMapper<T> extends ColumnMapper<T> {
56
57 private final Method readMethod;
58 private final Method writeMethod;
59
60 private LiteralMapper(Field field, int position, PropertyDescriptor pd, AtomicInteger columnNumber) {
61 this(field, extractSimpleType(field), position, pd, columnNumber);
62 }
63
64 private LiteralMapper(Field field, DataType type, int position, PropertyDescriptor pd, AtomicInteger columnCounter) {
65 super(field, type, position, columnCounter);
66 this.readMethod = pd.getReadMethod();
67 this.writeMethod = pd.getWriteMethod();
68 }
69
70 @Override
71 public Object getValue(T entity) {
72 try {
73 return readMethod.invoke(entity);
74 } catch (IllegalArgumentException e) {
75 throw new IllegalArgumentException("Could not get field '" + fieldName + "'");
76 } catch (Exception e) {
77 throw new IllegalStateException("Unable to access getter for '" + fieldName + "' in " + entity.getClass().getName(), e);
78 }
79 }
80
81 @Override
82 public void setValue(Object entity, Object value) {
83 try {
84 writeMethod.invoke(entity, value);
85 } catch (IllegalArgumentException e) {
86 throw new IllegalArgumentException("Could not set field '" + fieldName + "' to value '" + value + "'");
87 } catch (Exception e) {
88 throw new IllegalStateException("Unable to access setter for '" + fieldName + "' in " + entity.getClass().getName(), e);
89 }
90 }
91 }
92
93 private static class EnumMapper<T> extends LiteralMapper<T> {
94
95 private final EnumType enumType;
96 private final Map<String, Object> fromString;
97
98 private EnumMapper(Field field, int position, PropertyDescriptor pd, EnumType enumType, AtomicInteger columnCounter) {
99 super(field, enumType == EnumType.STRING ? DataType.text() : DataType.cint(), position, pd, columnCounter);
100 this.enumType = enumType;
101
102 if (enumType == EnumType.STRING) {
103 fromString = new HashMap<String, Object>(javaType.getEnumConstants().length);
104 for (Object constant : javaType.getEnumConstants())
105 fromString.put(constant.toString().toLowerCase(), constant);
106
107 } else {
108 fromString = null;
109 }
110 }
111
112 @SuppressWarnings("rawtypes")
113 @Override
114 public Object getValue(T entity) {
115 Object value = super.getValue(entity);
116 switch (enumType) {
117 case STRING:
118 return (value == null) ? null : value.toString();
119 case ORDINAL:
120 return (value == null) ? null : ((Enum)value).ordinal();
121 }
122 throw new AssertionError();
123 }
124
125 @Override
126 public void setValue(Object entity, Object value) {
127 Object converted = null;
128 switch (enumType) {
129 case STRING:
130 converted = fromString.get(value.toString().toLowerCase());
131 break;
132 case ORDINAL:
133 converted = javaType.getEnumConstants()[(Integer)value];
134 break;
135 }
136 super.setValue(entity, converted);
137 }
138 }
139
140 private static class UDTColumnMapper<T, U> extends LiteralMapper<T> {
141 private final UDTMapper<U> udtMapper;
142
143 private UDTColumnMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<U> udtMapper, AtomicInteger columnCounter) {
144 super(field, udtMapper.getUserType(), position, pd, columnCounter);
145 this.udtMapper = udtMapper;
146 }
147
148 @Override
149 public Object getValue(T entity) {
150 @SuppressWarnings("unchecked")
151 U udtEntity = (U) super.getValue(entity);
152 return udtEntity == null ? null : udtMapper.toUDT(udtEntity);
153 }
154
155 @Override
156 public void setValue(Object entity, Object value) {
157 assert value instanceof UDTValue;
158 UDTValue udtValue = (UDTValue) value;
159 assert udtValue.getType().equals(udtMapper.getUserType());
160
161 super.setValue(entity, udtMapper.toEntity((udtValue)));
162 }
163 }
164
165 private static class NestedUDTMapper<T> extends LiteralMapper<T> {
166 private final InferredCQLType inferredCQLType;
167
168 public NestedUDTMapper(Field field, int position, PropertyDescriptor pd, InferredCQLType inferredCQLType, AtomicInteger columnCounter) {
169 super(field, inferredCQLType.dataType, position, pd, columnCounter);
170 this.inferredCQLType = inferredCQLType;
171 }
172
173 @Override
174 @SuppressWarnings("unchecked")
175 public Object getValue(T entity) {
176 Object valueWithEntities = super.getValue(entity);
177 return (T)UDTMapper.convertEntitiesToUDTs(valueWithEntities, inferredCQLType);
178 }
179
180 @Override
181 public void setValue(Object entity, Object valueWithUDTValues) {
182 super.setValue(entity, UDTMapper.convertUDTsToEntities(valueWithUDTValues, inferredCQLType));
183 }
184 }
185
186 static DataType extractSimpleType(Field f) {
187 Type type = f.getGenericType();
188
189 assert !(type instanceof ParameterizedType);
190
191 if (!(type instanceof Class))
192 throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName()));
193
194 return TypeMappings.getSimpleType((Class<?>)type, f.getName());
195 }
196
197 private static class ReflectionFactory implements Factory {
198
199 public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
200 return new ReflectionMapper<T>(entityClass, keyspace, table, writeConsistency, readConsistency);
201 }
202
203 @SuppressWarnings({ "unchecked", "rawtypes" })
204 public <T> ColumnMapper<T> createColumnMapper(Class<T> entityClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter) {
205 String fieldName = field.getName();
206 try {
207 PropertyDescriptor pd = new PropertyDescriptor(fieldName, field.getDeclaringClass());
208
209 if (field.getType().isEnum()) {
210 return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field), columnCounter);
211 }
212
213 if (TypeMappings.isMappedUDT(field.getType())) {
214 UDTMapper<?> udtMapper = mappingManager.getUDTMapper(field.getType());
215 return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper, columnCounter);
216 }
217
218 if (field.getGenericType() instanceof ParameterizedType) {
219 InferredCQLType inferredCQLType = InferredCQLType.from(field, mappingManager);
220 if (inferredCQLType.containsMappedUDT) {
221 // We need a specialized mapper to convert UDT instances in the hierarchy.
222 return (ColumnMapper<T>)new NestedUDTMapper(field, position, pd, inferredCQLType, columnCounter);
223 } else {
224 // The default codecs will know how to handle the extracted datatype.
225 return new LiteralMapper<T>(field, inferredCQLType.dataType, position, pd, columnCounter);
226 }
227 }
228
229 return new LiteralMapper<T>(field, position, pd, columnCounter);
230
231 } catch (IntrospectionException e) {
232 throw new IllegalArgumentException("Cannot find matching getter and setter for field '" + fieldName + "'");
233 }
234 }
235 }
236}