Elffuss BraidHub

kikocis/java-driver public

37c05c45453b · 9.6 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 public Object getValue(T entity) {
74 try {
75 return 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 public 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 @SuppressWarnings("rawtypes")
115 @Override
116 public Object getValue(T entity) {
117 Object value = super.getValue(entity);
118 switch (enumType) {
119 case STRING:
120 return (value == null) ? null : value.toString();
121 case ORDINAL:
122 return (value == null) ? null : ((Enum) value).ordinal();
123 }
124 throw new AssertionError();
125 }
126
127 @Override
128 public void setValue(Object entity, Object value) {
129 Object converted = null;
130 switch (enumType) {
131 case STRING:
132 converted = fromString.get(value.toString().toLowerCase());
133 break;
134 case ORDINAL:
135 converted = javaType.getEnumConstants()[(Integer) value];
136 break;
137 }
138 super.setValue(entity, converted);
139 }
140 }
141
142 private static class UDTColumnMapper<T, U> extends LiteralMapper<T> {
143 private final UDTMapper<U> udtMapper;
144
145 private UDTColumnMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<U> udtMapper, AtomicInteger columnCounter) {
146 super(field, udtMapper.getUserType(), position, pd, columnCounter);
147 this.udtMapper = udtMapper;
148 }
149
150 @Override
151 public Object getValue(T entity) {
152 @SuppressWarnings("unchecked")
153 U udtEntity = (U) super.getValue(entity);
154 return udtEntity == null ? null : udtMapper.toUDT(udtEntity);
155 }
156
157 @Override
158 public void setValue(Object entity, Object value) {
159 assert value instanceof UDTValue;
160 UDTValue udtValue = (UDTValue) value;
161 assert udtValue.getType().equals(udtMapper.getUserType());
162
163 super.setValue(entity, udtMapper.toEntity((udtValue)));
164 }
165 }
166
167 private static class NestedUDTMapper<T> extends LiteralMapper<T> {
168 private final InferredCQLType inferredCQLType;
169
170 public NestedUDTMapper(Field field, int position, PropertyDescriptor pd, InferredCQLType inferredCQLType, AtomicInteger columnCounter) {
171 super(field, inferredCQLType.dataType, position, pd, columnCounter);
172 this.inferredCQLType = inferredCQLType;
173 }
174
175 @Override
176 @SuppressWarnings("unchecked")
177 public Object getValue(T entity) {
178 Object valueWithEntities = super.getValue(entity);
179 return (T) UDTMapper.convertEntitiesToUDTs(valueWithEntities, inferredCQLType);
180 }
181
182 @Override
183 public void setValue(Object entity, Object valueWithUDTValues) {
184 super.setValue(entity, UDTMapper.convertUDTsToEntities(valueWithUDTValues, inferredCQLType));
185 }
186 }
187
188 static DataType extractSimpleType(Field f) {
189 Type type = f.getGenericType();
190
191 assert !(type instanceof ParameterizedType);
192
193 if (!(type instanceof Class))
194 throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName()));
195
196 return TypeMappings.getSimpleType((Class<?>) type, f.getName());
197 }
198
199 private static class ReflectionFactory implements Factory {
200
201 @Override
202 public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
203 return new ReflectionMapper<T>(entityClass, keyspace, table, writeConsistency, readConsistency);
204 }
205
206 @SuppressWarnings({"unchecked", "rawtypes"})
207 @Override
208 public <T> ColumnMapper<T> createColumnMapper(Class<T> entityClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter) {
209 String fieldName = field.getName();
210 try {
211 PropertyDescriptor pd = new PropertyDescriptor(fieldName, field.getDeclaringClass());
212
213 if (field.getType().isEnum()) {
214 return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field), columnCounter);
215 }
216
217 if (TypeMappings.isMappedUDT(field.getType())) {
218 UDTMapper<?> udtMapper = mappingManager.getUDTMapper(field.getType());
219 return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper, columnCounter);
220 }
221
222 if (field.getGenericType() instanceof ParameterizedType) {
223 InferredCQLType inferredCQLType = InferredCQLType.from(field, mappingManager);
224 if (inferredCQLType.containsMappedUDT) {
225 // We need a specialized mapper to convert UDT instances in the hierarchy.
226 return (ColumnMapper<T>) new NestedUDTMapper(field, position, pd, inferredCQLType, columnCounter);
227 } else {
228 // The default codecs will know how to handle the extracted datatype.
229 return new LiteralMapper<T>(field, inferredCQLType.dataType, position, pd, columnCounter);
230 }
231 }
232
233 return new LiteralMapper<T>(field, position, pd, columnCounter);
234
235 } catch (IntrospectionException e) {
236 throw new IllegalArgumentException("Cannot find matching getter and setter for field '" + fieldName + "'");
237 }
238 }
239 }
240}