Elffuss BraidHub

kikocis/java-driver public

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