| 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.util.concurrent.Futures; |
| 21 | import com.google.common.util.concurrent.ListenableFuture; |
| 22 | |
| 23 | import java.lang.reflect.Method; |
| 24 | import java.lang.reflect.ParameterizedType; |
| 25 | import java.lang.reflect.Type; |
| 26 | import java.nio.ByteBuffer; |
| 27 | import 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 |
| 31 | class 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().getProtocolVersionEnum(); |
| 144 | for (int i = 0; i < args.length; i++) { |
| 145 | paramMappers[i].setValue(bs, args[i], protocolVersion); |
| 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 of the other. If paramName is null, then paramIdx is used. |
| 178 | private final String paramName; |
| 179 | private final int paramIdx; |
| 180 | private final DataType dataType; |
| 181 | |
| 182 | public ParamMapper(String paramName, int paramIdx, DataType dataType) { |
| 183 | this.paramName = paramName; |
| 184 | this.paramIdx = paramIdx; |
| 185 | this.dataType = dataType; |
| 186 | } |
| 187 | |
| 188 | public ParamMapper(String paramName, int paramIdx) { |
| 189 | this(paramName, paramIdx, null); |
| 190 | } |
| 191 | |
| 192 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 193 | ByteBuffer serializedArg = (dataType == null) |
| 194 | ? DataType.serializeValue(arg, protocolVersion) |
| 195 | : dataType.serialize(arg, protocolVersion); |
| 196 | if (paramName == null) { |
| 197 | if (arg == null) |
| 198 | boundStatement.setToNull(paramIdx); |
| 199 | else |
| 200 | boundStatement.setBytesUnsafe(paramIdx, serializedArg); |
| 201 | } else { |
| 202 | if (arg == null) |
| 203 | boundStatement.setToNull(paramName); |
| 204 | else |
| 205 | boundStatement.setBytesUnsafe(paramName, serializedArg); |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | static class UDTParamMapper<V> extends ParamMapper { |
| 211 | private final UDTMapper<V> udtMapper; |
| 212 | |
| 213 | UDTParamMapper(String paramName, int paramIdx, UDTMapper<V> udtMapper) { |
| 214 | super(paramName, paramIdx); |
| 215 | this.udtMapper = udtMapper; |
| 216 | } |
| 217 | |
| 218 | @Override |
| 219 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 220 | @SuppressWarnings("unchecked") |
| 221 | V entity = (V) arg; |
| 222 | UDTValue udtArg = arg != null ? udtMapper.toUDT(entity) : null; |
| 223 | super.setValue(boundStatement, udtArg, protocolVersion); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /** |
| 228 | * Maps a nested collection which has a mapped UDT somewhere in the hierarchy. |
| 229 | */ |
| 230 | static class NestedUDTParamMapper extends ParamMapper { |
| 231 | private final InferredCQLType inferredCQLType; |
| 232 | |
| 233 | NestedUDTParamMapper(String paramName, int paramIdx, InferredCQLType inferredCQLType) { |
| 234 | super(paramName, paramIdx); |
| 235 | this.inferredCQLType = inferredCQLType; |
| 236 | } |
| 237 | |
| 238 | @Override |
| 239 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 240 | super.setValue(boundStatement, |
| 241 | UDTMapper.convertEntitiesToUDTs(arg, inferredCQLType), |
| 242 | protocolVersion); |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | static class EnumParamMapper extends ParamMapper { |
| 247 | |
| 248 | private final EnumType enumType; |
| 249 | |
| 250 | public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) { |
| 251 | super(paramName, paramIdx); |
| 252 | this.enumType = enumType; |
| 253 | } |
| 254 | |
| 255 | @Override |
| 256 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 257 | super.setValue(boundStatement, convert(arg), protocolVersion); |
| 258 | } |
| 259 | |
| 260 | @SuppressWarnings("rawtypes") |
| 261 | private Object convert(Object arg) { |
| 262 | if (arg == null) |
| 263 | return arg; |
| 264 | |
| 265 | switch (enumType) { |
| 266 | case STRING: |
| 267 | return arg.toString(); |
| 268 | case ORDINAL: |
| 269 | return ((Enum) arg).ordinal(); |
| 270 | } |
| 271 | throw new AssertionError(); |
| 272 | } |
| 273 | } |
| 274 | } |