Elffuss BraidHub

kikocis/java-driver public

5cc80eb128f8 · 10.0 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.lang.reflect.Method;
19import java.lang.reflect.ParameterizedType;
20import java.lang.reflect.Type;
21import java.util.List;
22import java.util.Map;
23import java.util.Set;
24
25import com.google.common.util.concurrent.Futures;
26import com.google.common.util.concurrent.ListenableFuture;
27
28import com.datastax.driver.core.*;
29
30// TODO: we probably should make that an abstract class and move some bit in a "ReflexionMethodMapper"
31// subclass for consistency with the rest, but we can see to that later
32class MethodMapper {
33
34 public final Method method;
35 public final String queryString;
36 public final ParamMapper[] paramMappers;
37
38 private final ConsistencyLevel consistency;
39 private final int fetchSize;
40 private final boolean tracing;
41
42 private Session session;
43 private PreparedStatement statement;
44
45 private boolean returnStatement;
46 private Mapper<?> returnMapper;
47 private boolean mapOne;
48 private boolean async;
49
50 MethodMapper(Method method, String queryString, ParamMapper[] paramMappers, ConsistencyLevel consistency, int fetchSize, boolean enableTracing) {
51 this.method = method;
52 this.queryString = queryString;
53 this.paramMappers = paramMappers;
54 this.consistency = consistency;
55 this.fetchSize = fetchSize;
56 this.tracing = enableTracing;
57 }
58
59 public void prepare(MappingManager manager, PreparedStatement ps) {
60 this.session = manager.getSession();
61 this.statement = ps;
62
63 if (method.isVarArgs())
64 throw new IllegalArgumentException(String.format("Invalid varargs method %s in @Accessor interface"));
65 if (ps.getVariables().size() != method.getParameterTypes().length)
66 throw new IllegalArgumentException(String.format("The number of arguments for method %s (%d) does not match the number of bind parameters in the @Query (%d)",
67 method.getName(), method.getParameterTypes().length, ps.getVariables().size()));
68
69 // TODO: we should also validate the types of the parameters...
70
71 Class<?> returnType = method.getReturnType();
72 if (Void.class.isAssignableFrom(returnType) || ResultSet.class.isAssignableFrom(returnType))
73 return;
74
75 if (Statement.class.isAssignableFrom(returnType)) {
76 returnStatement = true;
77 return;
78 }
79
80 if (ResultSetFuture.class.isAssignableFrom(returnType)) {
81 this.async = true;
82 return;
83 }
84
85 if (ListenableFuture.class.isAssignableFrom(returnType)) {
86 this.async = true;
87 Type k = ((ParameterizedType)method.getGenericReturnType()).getActualTypeArguments()[0];
88 if (k instanceof Class && ResultSet.class.isAssignableFrom((Class<?>)k))
89 return;
90
91 mapType(manager, returnType, k);
92 } else {
93 mapType(manager, returnType, method.getGenericReturnType());
94 }
95 }
96
97 @SuppressWarnings("rawtypes")
98 private void mapType(MappingManager manager, Class<?> fullReturnType, Type type) {
99
100 if (type instanceof ParameterizedType) {
101 ParameterizedType pt = (ParameterizedType)type;
102 Type raw = pt.getRawType();
103 if (raw instanceof Class && Result.class.isAssignableFrom((Class)raw)) {
104 type = pt.getActualTypeArguments()[0];
105 } else {
106 mapOne = true;
107 }
108 } else {
109 mapOne = true;
110 }
111
112 if (!(type instanceof Class))
113 throw new RuntimeException(String.format("Cannot map return of method %s to unsupported type %s", method, type));
114
115 try {
116 this.returnMapper = (Mapper<?>)manager.mapper((Class<?>)type);
117 } catch (Exception e) {
118 throw new RuntimeException("Cannot map return to class " + fullReturnType, e);
119 }
120 }
121
122 public Object invoke(Object[] args) {
123
124 BoundStatement bs = statement.bind();
125
126 ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
127 for (int i = 0; i < args.length; i++) {
128 paramMappers[i].setValue(bs, args[i], protocolVersion);
129 }
130
131 if (consistency != null)
132 bs.setConsistencyLevel(consistency);
133 if (fetchSize > 0)
134 bs.setFetchSize(fetchSize);
135 if (tracing)
136 bs.enableTracing();
137
138 if (returnStatement)
139 return bs;
140
141 if (async) {
142 ListenableFuture<ResultSet> future = session.executeAsync(bs);
143 if (returnMapper == null)
144 return future;
145
146 return mapOne
147 ? Futures.transform(future, returnMapper.mapOneFunction)
148 : Futures.transform(future, returnMapper.mapAllFunction);
149 } else {
150 ResultSet rs = session.execute(bs);
151 if (returnMapper == null)
152 return rs;
153
154 Result<?> result = returnMapper.map(rs);
155 return mapOne ? result.one() : result;
156 }
157 }
158
159 static class ParamMapper {
160 // We'll only set one of the other. If paramName is null, then paramIdx is used.
161 private final String paramName;
162 private final int paramIdx;
163
164 public ParamMapper(String paramName, int paramIdx) {
165 this.paramName = paramName;
166 this.paramIdx = paramIdx;
167 }
168
169 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
170 if (paramName == null) {
171 if (arg == null)
172 boundStatement.setToNull(paramIdx);
173 else
174 boundStatement.setBytesUnsafe(paramIdx, DataType.serializeValue(arg, protocolVersion));
175 } else {
176 if (arg == null)
177 boundStatement.setToNull(paramName);
178 else
179 boundStatement.setBytesUnsafe(paramName, DataType.serializeValue(arg, protocolVersion));
180 }
181 }
182 }
183
184 static class UDTParamMapper<V> extends ParamMapper {
185 private final UDTMapper<V> udtMapper;
186
187 UDTParamMapper(String paramName, int paramIdx, UDTMapper<V> udtMapper) {
188 super(paramName, paramIdx);
189 this.udtMapper = udtMapper;
190 }
191
192 @Override
193 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
194 @SuppressWarnings("unchecked")
195 V entity = (V) arg;
196 UDTValue udtArg = arg != null ? udtMapper.toUDT(entity) : null;
197 super.setValue(boundStatement, udtArg, protocolVersion);
198 }
199 }
200
201 static class UDTListParamMapper<V> extends ParamMapper {
202 private final UDTMapper<V> valueMapper;
203
204 UDTListParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) {
205 super(paramName, paramIdx);
206 this.valueMapper = valueMapper;
207 }
208
209 @Override
210 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
211 @SuppressWarnings("unchecked")
212 List<V> entities = (List<V>) arg;
213 super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion);
214 }
215 }
216
217 static class UDTSetParamMapper<V> extends ParamMapper {
218 private final UDTMapper<V> valueMapper;
219
220 UDTSetParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) {
221 super(paramName, paramIdx);
222 this.valueMapper = valueMapper;
223 }
224
225 @Override
226 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
227 @SuppressWarnings("unchecked")
228 Set<V> entities = (Set<V>) arg;
229 super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion);
230 }
231 }
232
233 static class UDTMapParamMapper<K, V> extends ParamMapper {
234 private final UDTMapper<K> keyMapper;
235 private final UDTMapper<V> valueMapper;
236
237 UDTMapParamMapper(String paramName, int paramIdx, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper) {
238 super(paramName, paramIdx);
239 this.keyMapper = keyMapper;
240 this.valueMapper = valueMapper;
241 }
242
243 @Override
244 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
245 @SuppressWarnings("unchecked")
246 Map<K, V> entities = (Map<K, V>) arg;
247 super.setValue(boundStatement, UDTMapper.toUDTValues(entities, keyMapper, valueMapper), protocolVersion);
248 }
249 }
250
251 static class EnumParamMapper extends ParamMapper {
252
253 private final EnumType enumType;
254
255 public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) {
256 super(paramName, paramIdx);
257 this.enumType = enumType;
258 }
259
260 @Override
261 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
262 super.setValue(boundStatement, convert(arg), protocolVersion);
263 }
264
265 @SuppressWarnings("rawtypes")
266 private Object convert(Object arg) {
267 if(arg == null)
268 return arg;
269
270 switch (enumType) {
271 case STRING:
272 return arg.toString();
273 case ORDINAL:
274 return ((Enum) arg).ordinal();
275 }
276 throw new AssertionError();
277 }
278 }
279}