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