Elffuss BraidHub

kikocis/java-driver public

89b1172e93b0 · 8.2 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.*;
19import com.google.common.collect.Sets;
20import com.google.common.reflect.TypeToken;
21import com.google.common.util.concurrent.Futures;
22import com.google.common.util.concurrent.ListenableFuture;
23
24import java.lang.reflect.Method;
25import java.lang.reflect.ParameterizedType;
26import java.lang.reflect.Type;
27import java.util.Set;
28
29// TODO: we probably should make that an abstract class and move some bit in a "ReflexionMethodMapper"
30// subclass for consistency with the rest, but we can see to that later
31class MethodMapper {
32
33 public final Method method;
34 public final String queryString;
35 public final ParamMapper[] paramMappers;
36
37 private final ConsistencyLevel consistency;
38 private final int fetchSize;
39 private final boolean tracing;
40 private final Boolean idempotent;
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, Boolean idempotent) {
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 this.idempotent = idempotent;
58 }
59
60 public void prepare(MappingManager manager, PreparedStatement ps) {
61 this.session = manager.getSession();
62 this.statement = ps;
63
64 validateParameters();
65
66 Class<?> returnType = method.getReturnType();
67 if (Void.TYPE.isAssignableFrom(returnType) || ResultSet.class.isAssignableFrom(returnType))
68 return;
69
70 if (Statement.class.isAssignableFrom(returnType)) {
71 returnStatement = true;
72 return;
73 }
74
75 if (ResultSetFuture.class.isAssignableFrom(returnType)) {
76 this.async = true;
77 return;
78 }
79
80 if (ListenableFuture.class.isAssignableFrom(returnType)) {
81 this.async = true;
82 Type k = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];
83 if (k instanceof Class && ResultSet.class.isAssignableFrom((Class<?>) k))
84 return;
85
86 mapType(manager, returnType, k);
87 } else {
88 mapType(manager, returnType, method.getGenericReturnType());
89 }
90 }
91
92 // Checks the method parameters against the query's bind variables
93 private void validateParameters() {
94 if (method.isVarArgs())
95 throw new IllegalArgumentException(String.format("Invalid varargs method %s in @Accessor interface", method.getName()));
96
97 ColumnDefinitions variables = statement.getVariables();
98 Set<String> names = Sets.newHashSet();
99 for (ColumnDefinitions.Definition variable : variables) {
100 names.add(variable.getName());
101 }
102
103 if (method.getParameterTypes().length < names.size())
104 throw new IllegalArgumentException(String.format("Not enough arguments for method %s, "
105 + "found %d but it should be at least the number of unique bind parameter names in the @Query (%d)",
106 method.getName(), method.getParameterTypes().length, names.size()));
107
108 if (method.getParameterTypes().length > variables.size())
109 throw new IllegalArgumentException(String.format("Too many arguments for method %s, "
110 + "found %d but it should be at most the number of bind parameters in the @Query (%d)",
111 method.getName(), method.getParameterTypes().length, variables.size()));
112
113 // TODO could go further, e.g. check that the types match, inspect @Param annotations to check that all names are bound...
114 }
115
116 @SuppressWarnings("rawtypes")
117 private void mapType(MappingManager manager, Class<?> fullReturnType, Type type) {
118
119 if (type instanceof ParameterizedType) {
120 ParameterizedType pt = (ParameterizedType) type;
121 Type raw = pt.getRawType();
122 if (raw instanceof Class && Result.class.isAssignableFrom((Class) raw)) {
123 type = pt.getActualTypeArguments()[0];
124 } else {
125 mapOne = true;
126 }
127 } else {
128 mapOne = true;
129 }
130
131 if (!(type instanceof Class))
132 throw new RuntimeException(String.format("Cannot map return of method %s to unsupported type %s", method, type));
133
134 try {
135 this.returnMapper = (Mapper<?>) manager.mapper((Class<?>) type);
136 } catch (Exception e) {
137 throw new RuntimeException("Cannot map return to class " + fullReturnType, e);
138 }
139 }
140
141 public Object invoke(Object[] args) {
142
143 BoundStatement bs = statement.bind();
144
145 ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
146 for (int i = 0; i < args.length; i++) {
147 paramMappers[i].setValue(bs, args[i]);
148 }
149
150 if (consistency != null)
151 bs.setConsistencyLevel(consistency);
152 if (fetchSize > 0)
153 bs.setFetchSize(fetchSize);
154 if (tracing)
155 bs.enableTracing();
156 if (idempotent != null)
157 bs.setIdempotent(idempotent);
158
159 if (returnStatement)
160 return bs;
161
162 if (async) {
163 ListenableFuture<ResultSet> future = session.executeAsync(bs);
164 if (returnMapper == null)
165 return future;
166
167 return mapOne
168 ? Futures.transform(future, returnMapper.mapOneFunctionWithoutAliases)
169 : Futures.transform(future, returnMapper.mapAllFunctionWithoutAliases);
170 } else {
171 ResultSet rs = session.execute(bs);
172 if (returnMapper == null)
173 return rs;
174
175 Result<?> result = returnMapper.map(rs);
176 return mapOne ? result.one() : result;
177 }
178 }
179
180 static class ParamMapper {
181 // We'll only set one or the other. If paramName is null, then paramIdx is used.
182 private final String paramName;
183 private final int paramIdx;
184 private final TypeToken<Object> paramType;
185 private final TypeCodec<Object> codec;
186
187 @SuppressWarnings("unchecked")
188 public ParamMapper(String paramName, int paramIdx, TypeToken<?> paramType, Class<? extends TypeCodec<?>> codecClass) {
189 this.paramName = paramName;
190 this.paramIdx = paramIdx;
191 this.paramType = (TypeToken<Object>) paramType;
192 try {
193 this.codec = (codecClass == null) ? null : (TypeCodec<Object>) codecClass.newInstance();
194 } catch (Exception e) {
195 throw new IllegalArgumentException(String.format(
196 "Cannot create instance of codec %s for parameter %s",
197 codecClass, (paramName == null) ? paramIdx : paramName
198 ), e);
199 }
200 }
201
202 void setValue(BoundStatement boundStatement, Object arg) {
203 if (paramName == null) {
204 if (codec == null)
205 boundStatement.set(paramIdx, arg, paramType);
206 else
207 boundStatement.set(paramIdx, arg, codec);
208 } else {
209 if (codec == null)
210 boundStatement.set(paramName, arg, paramType);
211 else
212 boundStatement.set(paramName, arg, codec);
213 }
214 }
215 }
216
217}