Elffuss BraidHub

kikocis/java-driver public

547223707403 · 9.9 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 java.lang.reflect.Method;
19import java.lang.reflect.ParameterizedType;
20import java.lang.reflect.Type;
21import java.nio.ByteBuffer;
22import java.util.Set;
23
24import com.google.common.collect.Sets;
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 validateParameters();
64
65 Class<?> returnType = method.getReturnType();
66 if (Void.TYPE.isAssignableFrom(returnType) || ResultSet.class.isAssignableFrom(returnType))
67 return;
68
69 if (Statement.class.isAssignableFrom(returnType)) {
70 returnStatement = true;
71 return;
72 }
73
74 if (ResultSetFuture.class.isAssignableFrom(returnType)) {
75 this.async = true;
76 return;
77 }
78
79 if (ListenableFuture.class.isAssignableFrom(returnType)) {
80 this.async = true;
81 Type k = ((ParameterizedType)method.getGenericReturnType()).getActualTypeArguments()[0];
82 if (k instanceof Class && ResultSet.class.isAssignableFrom((Class<?>)k))
83 return;
84
85 mapType(manager, returnType, k);
86 } else {
87 mapType(manager, returnType, method.getGenericReturnType());
88 }
89 }
90
91 // Checks the method parameters against the query's bind variables
92 private void validateParameters() {
93 if (method.isVarArgs())
94 throw new IllegalArgumentException(String.format("Invalid varargs method %s in @Accessor interface", method.getName()));
95
96 ColumnDefinitions variables = statement.getVariables();
97 Set<String> names = Sets.newHashSet();
98 for (ColumnDefinitions.Definition variable : variables) {
99 names.add(variable.getName());
100 }
101
102 if (method.getParameterTypes().length < names.size())
103 throw new IllegalArgumentException(String.format("Not enough arguments for method %s, "
104 + "found %d but it should be at least the number of unique bind parameter names in the @Query (%d)",
105 method.getName(), method.getParameterTypes().length, names.size()));
106
107 if (method.getParameterTypes().length > variables.size())
108 throw new IllegalArgumentException(String.format("Too many arguments for method %s, "
109 + "found %d but it should be at most the number of bind parameters in the @Query (%d)",
110 method.getName(), method.getParameterTypes().length, variables.size()));
111
112 // TODO could go further, e.g. check that the types match, inspect @Param annotations to check that all names are bound...
113 }
114
115 @SuppressWarnings("rawtypes")
116 private void mapType(MappingManager manager, Class<?> fullReturnType, Type type) {
117
118 if (type instanceof ParameterizedType) {
119 ParameterizedType pt = (ParameterizedType)type;
120 Type raw = pt.getRawType();
121 if (raw instanceof Class && Result.class.isAssignableFrom((Class)raw)) {
122 type = pt.getActualTypeArguments()[0];
123 } else {
124 mapOne = true;
125 }
126 } else {
127 mapOne = true;
128 }
129
130 if (!(type instanceof Class))
131 throw new RuntimeException(String.format("Cannot map return of method %s to unsupported type %s", method, type));
132
133 try {
134 this.returnMapper = (Mapper<?>)manager.mapper((Class<?>)type);
135 } catch (Exception e) {
136 throw new RuntimeException("Cannot map return to class " + fullReturnType, e);
137 }
138 }
139
140 public Object invoke(Object[] args) {
141
142 BoundStatement bs = statement.bind();
143
144 ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
145 for (int i = 0; i < args.length; i++) {
146 paramMappers[i].setValue(bs, args[i], protocolVersion);
147 }
148
149 if (consistency != null)
150 bs.setConsistencyLevel(consistency);
151 if (fetchSize > 0)
152 bs.setFetchSize(fetchSize);
153 if (tracing)
154 bs.enableTracing();
155
156 if (returnStatement)
157 return bs;
158
159 if (async) {
160 ListenableFuture<ResultSet> future = session.executeAsync(bs);
161 if (returnMapper == null)
162 return future;
163
164 return mapOne
165 ? Futures.transform(future, returnMapper.mapOneFunctionWithoutAliases)
166 : Futures.transform(future, returnMapper.mapAllFunctionWithoutAliases);
167 } else {
168 ResultSet rs = session.execute(bs);
169 if (returnMapper == null)
170 return rs;
171
172 Result<?> result = returnMapper.map(rs);
173 return mapOne ? result.one() : result;
174 }
175 }
176
177 static class ParamMapper {
178 // We'll only set one of the other. If paramName is null, then paramIdx is used.
179 private final String paramName;
180 private final int paramIdx;
181 private final DataType dataType;
182
183 public ParamMapper(String paramName, int paramIdx, DataType dataType) {
184 this.paramName = paramName;
185 this.paramIdx = paramIdx;
186 this.dataType = dataType;
187 }
188
189 public ParamMapper(String paramName, int paramIdx) {
190 this(paramName, paramIdx, null);
191 }
192
193 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
194 ByteBuffer serializedArg = (dataType == null)
195 ? DataType.serializeValue(arg, protocolVersion)
196 : dataType.serialize(arg, protocolVersion);
197 if (paramName == null) {
198 if (arg == null)
199 boundStatement.setToNull(paramIdx);
200 else
201 boundStatement.setBytesUnsafe(paramIdx, serializedArg);
202 } else {
203 if (arg == null)
204 boundStatement.setToNull(paramName);
205 else
206 boundStatement.setBytesUnsafe(paramName, serializedArg);
207 }
208 }
209 }
210
211 static class UDTParamMapper<V> extends ParamMapper {
212 private final UDTMapper<V> udtMapper;
213
214 UDTParamMapper(String paramName, int paramIdx, UDTMapper<V> udtMapper) {
215 super(paramName, paramIdx);
216 this.udtMapper = udtMapper;
217 }
218
219 @Override
220 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
221 @SuppressWarnings("unchecked")
222 V entity = (V) arg;
223 UDTValue udtArg = arg != null ? udtMapper.toUDT(entity) : null;
224 super.setValue(boundStatement, udtArg, protocolVersion);
225 }
226 }
227
228 /**
229 * Maps a nested collection which has a mapped UDT somewhere in the hierarchy.
230 */
231 static class NestedUDTParamMapper extends ParamMapper {
232 private final InferredCQLType inferredCQLType;
233
234 NestedUDTParamMapper(String paramName, int paramIdx, InferredCQLType inferredCQLType) {
235 super(paramName, paramIdx);
236 this.inferredCQLType = inferredCQLType;
237 }
238
239 @Override
240 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
241 super.setValue(boundStatement,
242 UDTMapper.convertEntitiesToUDTs(arg, inferredCQLType),
243 protocolVersion);
244 }
245 }
246
247 static class EnumParamMapper extends ParamMapper {
248
249 private final EnumType enumType;
250
251 public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) {
252 super(paramName, paramIdx);
253 this.enumType = enumType;
254 }
255
256 @Override
257 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
258 super.setValue(boundStatement, convert(arg), protocolVersion);
259 }
260
261 @SuppressWarnings("rawtypes")
262 private Object convert(Object arg) {
263 if(arg == null)
264 return arg;
265
266 switch (enumType) {
267 case STRING:
268 return arg.toString();
269 case ORDINAL:
270 return ((Enum) arg).ordinal();
271 }
272 throw new AssertionError();
273 }
274 }
275}