Elffuss BraidHub

kikocis/java-driver public

a2cee34f1f76 · 15.9 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2014 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.net.InetAddress;
25import java.nio.ByteBuffer;
26import java.math.BigInteger;
27import java.math.BigDecimal;
28import java.util.*;
29
30import com.datastax.driver.core.*;
31
32import com.datastax.driver.mapping.annotations.UDT;
33
34/**
35 * An {@link EntityMapper} implementation that use reflection to read and write fields
36 * of an entity.
37 */
38class ReflectionMapper<T> extends EntityMapper<T> {
39
40 private static ReflectionFactory factory = new ReflectionFactory();
41
42 private ReflectionMapper(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
43 super(entityClass, keyspace, table, writeConsistency, readConsistency);
44 }
45
46 public static Factory factory() {
47 return factory;
48 }
49
50 @Override
51 public T newEntity() {
52 try {
53 return entityClass.newInstance();
54 } catch (Exception e) {
55 throw new RuntimeException("Can't create an instance of " + entityClass.getName());
56 }
57 }
58
59 private static class LiteralMapper<T> extends ColumnMapper<T> {
60
61 private final Method readMethod;
62 private final Method writeMethod;
63
64 private LiteralMapper(Field field, int position, PropertyDescriptor pd) {
65 this(field, extractType(field), position, pd);
66 }
67
68 private LiteralMapper(Field field, DataType type, int position, PropertyDescriptor pd) {
69 super(field, type, position);
70 this.readMethod = pd.getReadMethod();
71 this.writeMethod = pd.getWriteMethod();
72 }
73
74 @Override
75 public Object getValue(T entity) {
76 try {
77 return readMethod.invoke(entity);
78 } catch (IllegalArgumentException e) {
79 throw new IllegalArgumentException("Could not get field '" + fieldName + "'");
80 } catch (Exception e) {
81 throw new IllegalStateException("Unable to access getter for '" + fieldName + "' in " + entity.getClass().getName(), e);
82 }
83 }
84
85 @Override
86 public void setValue(Object entity, Object value) {
87 try {
88 writeMethod.invoke(entity, value);
89 } catch (IllegalArgumentException e) {
90 throw new IllegalArgumentException("Could not set field '" + fieldName + "' to value '" + value + "'");
91 } catch (Exception e) {
92 throw new IllegalStateException("Unable to access setter for '" + fieldName + "' in " + entity.getClass().getName(), e);
93 }
94 }
95 }
96
97 private static class EnumMapper<T> extends LiteralMapper<T> {
98
99 private final EnumType enumType;
100 private final Map<String, Object> fromString;
101
102 private EnumMapper(Field field, int position, PropertyDescriptor pd, EnumType enumType) {
103 super(field, enumType == EnumType.STRING ? DataType.text() : DataType.cint(), position, pd);
104 this.enumType = enumType;
105
106 if (enumType == EnumType.STRING) {
107 fromString = new HashMap<String, Object>(javaType.getEnumConstants().length);
108 for (Object constant : javaType.getEnumConstants())
109 fromString.put(constant.toString().toLowerCase(), constant);
110
111 } else {
112 fromString = null;
113 }
114 }
115
116 @SuppressWarnings("rawtypes")
117 @Override
118 public Object getValue(T entity) {
119 Object value = super.getValue(entity);
120 switch (enumType) {
121 case STRING:
122 return (value == null) ? null : value.toString();
123 case ORDINAL:
124 return (value == null) ? null : ((Enum)value).ordinal();
125 }
126 throw new AssertionError();
127 }
128
129 @Override
130 public void setValue(Object entity, Object value) {
131 Object converted = null;
132 switch (enumType) {
133 case STRING:
134 converted = fromString.get(value.toString().toLowerCase());
135 break;
136 case ORDINAL:
137 converted = javaType.getEnumConstants()[(Integer)value];
138 break;
139 }
140 super.setValue(entity, converted);
141 }
142 }
143
144 private static class UDTColumnMapper<T, U> extends LiteralMapper<T> {
145 private final UDTMapper<U> udtMapper;
146
147 private UDTColumnMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<U> udtMapper) {
148 super(field, udtMapper.getUserType(), position, pd);
149 this.udtMapper = udtMapper;
150 }
151
152 @Override
153 public Object getValue(T entity) {
154 @SuppressWarnings("unchecked")
155 U udtEntity = (U) super.getValue(entity);
156 return udtEntity == null ? null : udtMapper.toUDT(udtEntity);
157 }
158
159 @Override
160 public void setValue(Object entity, Object value) {
161 assert value instanceof UDTValue;
162 UDTValue udtValue = (UDTValue) value;
163 assert udtValue.getType().equals(udtMapper.getUserType());
164
165 super.setValue(entity, udtMapper.toEntity((udtValue)));
166 }
167 }
168
169 private static class UDTListMapper<T, V> extends LiteralMapper<T> {
170
171 private final UDTMapper<V> valueMapper;
172
173 UDTListMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<V> valueMapper) {
174 super(field, DataType.list(valueMapper.getUserType()), position, pd);
175 this.valueMapper = valueMapper;
176 }
177
178 @Override
179 public Object getValue(T entity) {
180 @SuppressWarnings("unchecked")
181 List<V> entities = (List<V>) super.getValue(entity);
182 return valueMapper.toUDTValues(entities);
183 }
184
185 @Override
186 public void setValue(Object entity, Object value) {
187 @SuppressWarnings("unchecked")
188 List<UDTValue> udtValues = (List<UDTValue>) value;
189 super.setValue(entity, valueMapper.toEntities(udtValues));
190 }
191 }
192
193 private static class UDTSetMapper<T, V> extends LiteralMapper<T> {
194
195 private final UDTMapper<V> valueMapper;
196
197 UDTSetMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<V> valueMapper) {
198 super(field, DataType.set(valueMapper.getUserType()), position, pd);
199 this.valueMapper = valueMapper;
200 }
201
202 @Override
203 public Object getValue(T entity) {
204 @SuppressWarnings("unchecked")
205 Set<V> entities = (Set<V>) super.getValue(entity);
206 return valueMapper.toUDTValues(entities);
207 }
208
209 @Override
210 public void setValue(Object entity, Object value) {
211 @SuppressWarnings("unchecked")
212 Set<UDTValue> udtValues = (Set<UDTValue>) value;
213 super.setValue(entity, valueMapper.toEntities(udtValues));
214 }
215 }
216
217 /**
218 * A map field that contains UDT values.
219 * <p>
220 * UDTs may be used either as keys, or as values, or both. This is reflected
221 * in keyMapper and valueMapper being null or non-null.
222 * </p>
223 */
224 private static class UDTMapMapper<T, K, V> extends LiteralMapper<T> {
225 private final UDTMapper<K> keyMapper;
226 private final UDTMapper<V> valueMapper;
227
228 UDTMapMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper, Class<?> keyClass, Class<?> valueClass) {
229 super(field, buildDataType(field, keyMapper, valueMapper, keyClass, valueClass), position, pd);
230 this.keyMapper = keyMapper;
231 this.valueMapper = valueMapper;
232 }
233
234 @Override
235 public Object getValue(T entity) {
236 @SuppressWarnings("unchecked")
237 Map<K, V> entities = (Map<K, V>) super.getValue(entity);
238 return UDTMapper.toUDTValues(entities, keyMapper, valueMapper);
239 }
240
241 @Override
242 @SuppressWarnings("unchecked")
243 public void setValue(Object entity, Object fieldValue) {
244 Map<Object, Object> udtValues = (Map<Object, Object>) fieldValue;
245 super.setValue(entity, UDTMapper.toEntities(udtValues, keyMapper, valueMapper));
246 }
247
248 private static <K, V> DataType buildDataType(Field field, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper, Class<?> keyClass, Class<?> valueClass) {
249 assert keyMapper != null || valueMapper != null;
250
251 DataType keyType = (keyMapper != null) ?
252 keyMapper.getUserType() :
253 getSimpleType(keyClass, field);
254 DataType valueType = (valueMapper != null) ?
255 valueMapper.getUserType() :
256 getSimpleType(valueClass, field);
257 return DataType.map(keyType, valueType);
258 }
259 }
260
261 static DataType extractType(Field f) {
262 Type type = f.getGenericType();
263
264 if (type instanceof ParameterizedType) {
265 ParameterizedType pt = (ParameterizedType)type;
266 Type raw = pt.getRawType();
267 if (!(raw instanceof Class))
268 throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName()));
269
270 Class<?> klass = (Class<?>)raw;
271 if (List.class.isAssignableFrom(klass)) {
272 return DataType.list(getSimpleType(ReflectionUtils.getParam(pt, 0, f.getName()), f));
273 }
274 if (Set.class.isAssignableFrom(klass)) {
275 return DataType.set(getSimpleType(ReflectionUtils.getParam(pt, 0, f.getName()), f));
276 }
277 if (Map.class.isAssignableFrom(klass)) {
278 return DataType.map(getSimpleType(ReflectionUtils.getParam(pt, 0, f.getName()), f), getSimpleType(ReflectionUtils.getParam(pt, 1, f.getName()), f));
279 }
280 throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName()));
281 }
282
283 if (!(type instanceof Class))
284 throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName()));
285
286 return getSimpleType((Class<?>)type, f);
287 }
288
289 static DataType getSimpleType(Class<?> klass, Field f) {
290 if (ByteBuffer.class.isAssignableFrom(klass))
291 return DataType.blob();
292
293 if (klass == int.class || Integer.class.isAssignableFrom(klass))
294 return DataType.cint();
295 if (klass == long.class || Long.class.isAssignableFrom(klass))
296 return DataType.bigint();
297 if (klass == float.class || Float.class.isAssignableFrom(klass))
298 return DataType.cfloat();
299 if (klass == double.class || Double.class.isAssignableFrom(klass))
300 return DataType.cdouble();
301 if (klass == boolean.class || Boolean.class.isAssignableFrom(klass))
302 return DataType.cboolean();
303
304 if (BigDecimal.class.isAssignableFrom(klass))
305 return DataType.decimal();
306 if (BigInteger.class.isAssignableFrom(klass))
307 return DataType.varint();
308
309 if (String.class.isAssignableFrom(klass))
310 return DataType.text();
311 if (InetAddress.class.isAssignableFrom(klass))
312 return DataType.inet();
313 if (Date.class.isAssignableFrom(klass))
314 return DataType.timestamp();
315 if (UUID.class.isAssignableFrom(klass))
316 return DataType.uuid();
317
318 if (Collection.class.isAssignableFrom(klass))
319 throw new IllegalArgumentException(String.format("Cannot map non-parametrized collection type %s for field %s; Please use a concrete type parameter", klass.getName(), f.getName()));
320
321 throw new IllegalArgumentException(String.format("Cannot map unknown class %s for field %s", klass.getName(), f));
322 }
323
324 private static class ReflectionFactory implements Factory {
325
326 public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
327 return new ReflectionMapper<T>(entityClass, keyspace, table, writeConsistency, readConsistency);
328 }
329
330 @SuppressWarnings({ "unchecked", "rawtypes" })
331 public <T> ColumnMapper<T> createColumnMapper(Class<T> entityClass, Field field, int position, MappingManager mappingManager) {
332 String fieldName = field.getName();
333 try {
334 PropertyDescriptor pd = new PropertyDescriptor(fieldName, field.getDeclaringClass());
335
336 if (field.getType().isEnum()) {
337 return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field));
338 }
339
340 if (field.getType().isAnnotationPresent(UDT.class)) {
341 UDTMapper<?> udtMapper = mappingManager.getUDTMapper(field.getType());
342 return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper);
343 }
344
345 if (field.getGenericType() instanceof ParameterizedType) {
346 ParameterizedType pt = (ParameterizedType) field.getGenericType();
347 Type raw = pt.getRawType();
348 if (!(raw instanceof Class))
349 throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", field, field.getName()));
350
351 Class<?> klass = (Class<?>)raw;
352 Class<?> firstTypeParam = ReflectionUtils.getParam(pt, 0, field.getName());
353 if (List.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
354 UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
355 return (ColumnMapper<T>) new UDTListMapper(field, position, pd, valueMapper);
356 }
357 if (Set.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
358 UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
359 return (ColumnMapper<T>) new UDTSetMapper(field, position, pd, valueMapper);
360 }
361 if (Map.class.isAssignableFrom(klass)) {
362 Class<?> secondTypeParam = ReflectionUtils.getParam(pt, 1, field.getName());
363 UDTMapper<?> keyMapper = firstTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(firstTypeParam) : null;
364 UDTMapper<?> valueMapper = secondTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(secondTypeParam) : null;
365
366 if (keyMapper != null || valueMapper != null) {
367 return (ColumnMapper<T>) new UDTMapMapper(field, position, pd, keyMapper, valueMapper, firstTypeParam, secondTypeParam);
368 }
369 }
370 }
371
372 return new LiteralMapper<T>(field, position, pd);
373
374 } catch (IntrospectionException e) {
375 throw new IllegalArgumentException("Cannot find matching getter and setter for field '" + fieldName + "'");
376 }
377 }
378 }
379}