Elffuss BraidHub

kikocis/java-driver public

175563ced093 · 9.7 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 (arg != null) {
171 if (paramName == null)
172 boundStatement.setBytesUnsafe(paramIdx, DataType.serializeValue(arg, protocolVersion));
173 else
174 boundStatement.setBytesUnsafe(paramName, DataType.serializeValue(arg, protocolVersion));
175 }
176 }
177 }
178
179 static class UDTParamMapper<V> extends ParamMapper {
180 private final UDTMapper<V> udtMapper;
181
182 UDTParamMapper(String paramName, int paramIdx, UDTMapper<V> udtMapper) {
183 super(paramName, paramIdx);
184 this.udtMapper = udtMapper;
185 }
186
187 @Override
188 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
189 @SuppressWarnings("unchecked")
190 V entity = (V) arg;
191 super.setValue(boundStatement, udtMapper.toUDT(entity), protocolVersion);
192 }
193 }
194
195 static class UDTListParamMapper<V> extends ParamMapper {
196 private final UDTMapper<V> valueMapper;
197
198 UDTListParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) {
199 super(paramName, paramIdx);
200 this.valueMapper = valueMapper;
201 }
202
203 @Override
204 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
205 @SuppressWarnings("unchecked")
206 List<V> entities = (List<V>) arg;
207 super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion);
208 }
209 }
210
211 static class UDTSetParamMapper<V> extends ParamMapper {
212 private final UDTMapper<V> valueMapper;
213
214 UDTSetParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) {
215 super(paramName, paramIdx);
216 this.valueMapper = valueMapper;
217 }
218
219 @Override
220 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
221 @SuppressWarnings("unchecked")
222 Set<V> entities = (Set<V>) arg;
223 super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion);
224 }
225 }
226
227 static class UDTMapParamMapper<K, V> extends ParamMapper {
228 private final UDTMapper<K> keyMapper;
229 private final UDTMapper<V> valueMapper;
230
231 UDTMapParamMapper(String paramName, int paramIdx, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper) {
232 super(paramName, paramIdx);
233 this.keyMapper = keyMapper;
234 this.valueMapper = valueMapper;
235 }
236
237 @Override
238 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
239 @SuppressWarnings("unchecked")
240 Map<K, V> entities = (Map<K, V>) arg;
241 super.setValue(boundStatement, UDTMapper.toUDTValues(entities, keyMapper, valueMapper), protocolVersion);
242 }
243 }
244
245 static class EnumParamMapper extends ParamMapper {
246
247 private final EnumType enumType;
248
249 public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) {
250 super(paramName, paramIdx);
251 this.enumType = enumType;
252 }
253
254 @Override
255 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
256 super.setValue(boundStatement, convert(arg), protocolVersion);
257 }
258
259 @SuppressWarnings("rawtypes")
260 private Object convert(Object arg) {
261 switch (enumType) {
262 case STRING:
263 return arg.toString();
264 case ORDINAL:
265 return ((Enum) arg).ordinal();
266 }
267 throw new AssertionError();
268 }
269 }
270}