Elffuss BraidHub

kikocis/java-driver public

b4554bb54c38 · 8.0 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.util.Set;
22
23import com.google.common.collect.Sets;
24import com.google.common.reflect.TypeToken;
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().getProtocolVersion();
145 for (int i = 0; i < args.length; i++) {
146 paramMappers[i].setValue(bs, args[i]);
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 or the other. If paramName is null, then paramIdx is used.
179 private final String paramName;
180 private final int paramIdx;
181 private final TypeToken<Object> paramType;
182 private final TypeCodec<Object> codec;
183
184 @SuppressWarnings("unchecked")
185 public ParamMapper(String paramName, int paramIdx, TypeToken<?> paramType, Class<? extends TypeCodec<?>> codecClass) {
186 this.paramName = paramName;
187 this.paramIdx = paramIdx;
188 this.paramType = (TypeToken<Object>)paramType;
189 try {
190 this.codec = (codecClass == null) ? null : (TypeCodec<Object>)codecClass.newInstance();
191 } catch (Exception e) {
192 throw new IllegalArgumentException(String.format(
193 "Cannot create instance of codec %s for parameter %s",
194 codecClass, (paramName == null) ? paramIdx : paramName
195 ), e);
196 }
197 }
198
199 void setValue(BoundStatement boundStatement, Object arg) {
200 if (paramName == null) {
201 if (codec == null)
202 boundStatement.set(paramIdx, arg, paramType);
203 else
204 boundStatement.set(paramIdx, arg, codec);
205 } else {
206 if (codec == null)
207 boundStatement.set(paramName, arg, paramType);
208 else
209 boundStatement.set(paramName, arg, codec);
210 }
211 }
212 }
213
214}