Elffuss BraidHub

kikocis/java-driver public

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