| 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 | */ |
| 16 | package com.datastax.driver.mapping; |
| 17 | |
| 18 | import com.datastax.driver.core.*; |
| 19 | import com.google.common.collect.Sets; |
| 20 | import com.google.common.reflect.TypeToken; |
| 21 | import com.google.common.util.concurrent.Futures; |
| 22 | import com.google.common.util.concurrent.ListenableFuture; |
| 23 | |
| 24 | import java.lang.reflect.Method; |
| 25 | import java.lang.reflect.ParameterizedType; |
| 26 | import java.lang.reflect.Type; |
| 27 | import java.util.Set; |
| 28 | |
| 29 | class MethodMapper { |
| 30 | |
| 31 | final Method method; |
| 32 | final String queryString; |
| 33 | private final ParamMapper[] paramMappers; |
| 34 | |
| 35 | private final ConsistencyLevel consistency; |
| 36 | private final int fetchSize; |
| 37 | private final boolean tracing; |
| 38 | private final Boolean idempotent; |
| 39 | |
| 40 | private Session session; |
| 41 | private PreparedStatement statement; |
| 42 | |
| 43 | private boolean returnStatement; |
| 44 | private Mapper<?> returnMapper; |
| 45 | private boolean mapOne; |
| 46 | private boolean async; |
| 47 | |
| 48 | MethodMapper(Method method, String queryString, ParamMapper[] paramMappers, ConsistencyLevel consistency, int fetchSize, boolean enableTracing, Boolean idempotent) { |
| 49 | this.method = method; |
| 50 | this.queryString = queryString; |
| 51 | this.paramMappers = paramMappers; |
| 52 | this.consistency = consistency; |
| 53 | this.fetchSize = fetchSize; |
| 54 | this.tracing = enableTracing; |
| 55 | this.idempotent = idempotent; |
| 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 = manager.mapper((Class<?>) type); |
| 134 | } catch (Exception e) { |
| 135 | throw new RuntimeException("Cannot map return to class " + fullReturnType, e); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | Object invoke(Object[] args) { |
| 140 | |
| 141 | BoundStatement bs = statement.bind(); |
| 142 | |
| 143 | for (int i = 0; i < args.length; i++) { |
| 144 | paramMappers[i].setValue(bs, args[i]); |
| 145 | } |
| 146 | |
| 147 | if (consistency != null) |
| 148 | bs.setConsistencyLevel(consistency); |
| 149 | if (fetchSize > 0) |
| 150 | bs.setFetchSize(fetchSize); |
| 151 | if (tracing) |
| 152 | bs.enableTracing(); |
| 153 | if (idempotent != null) |
| 154 | bs.setIdempotent(idempotent); |
| 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 | 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 | } |