Elffuss BraidHub

kikocis/java-driver public

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