| 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 java.lang.reflect.Method; |
| 19 | import java.lang.reflect.ParameterizedType; |
| 20 | import java.lang.reflect.Type; |
| 21 | import java.nio.ByteBuffer; |
| 22 | |
| 23 | import com.google.common.util.concurrent.Futures; |
| 24 | import com.google.common.util.concurrent.ListenableFuture; |
| 25 | |
| 26 | import com.datastax.driver.core.*; |
| 27 | |
| 28 | // TODO: we probably should make that an abstract class and move some bit in a "ReflexionMethodMapper" |
| 29 | // subclass for consistency with the rest, but we can see to that later |
| 30 | class MethodMapper { |
| 31 | |
| 32 | public final Method method; |
| 33 | public final String queryString; |
| 34 | public final ParamMapper[] paramMappers; |
| 35 | |
| 36 | private final ConsistencyLevel consistency; |
| 37 | private final int fetchSize; |
| 38 | private final boolean tracing; |
| 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) { |
| 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 | } |
| 56 | |
| 57 | public void prepare(MappingManager manager, PreparedStatement ps) { |
| 58 | this.session = manager.getSession(); |
| 59 | this.statement = ps; |
| 60 | |
| 61 | if (method.isVarArgs()) |
| 62 | throw new IllegalArgumentException(String.format("Invalid varargs method %s in @Accessor interface")); |
| 63 | if (ps.getVariables().size() != method.getParameterTypes().length) |
| 64 | throw new IllegalArgumentException(String.format("The number of arguments for method %s (%d) does not match the number of bind parameters in the @Query (%d)", |
| 65 | method.getName(), method.getParameterTypes().length, ps.getVariables().size())); |
| 66 | |
| 67 | // TODO: we should also validate the types of the parameters... |
| 68 | |
| 69 | Class<?> returnType = method.getReturnType(); |
| 70 | if (Void.TYPE.isAssignableFrom(returnType) || ResultSet.class.isAssignableFrom(returnType)) |
| 71 | return; |
| 72 | |
| 73 | if (Statement.class.isAssignableFrom(returnType)) { |
| 74 | returnStatement = true; |
| 75 | return; |
| 76 | } |
| 77 | |
| 78 | if (ResultSetFuture.class.isAssignableFrom(returnType)) { |
| 79 | this.async = true; |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | if (ListenableFuture.class.isAssignableFrom(returnType)) { |
| 84 | this.async = true; |
| 85 | Type k = ((ParameterizedType)method.getGenericReturnType()).getActualTypeArguments()[0]; |
| 86 | if (k instanceof Class && ResultSet.class.isAssignableFrom((Class<?>)k)) |
| 87 | return; |
| 88 | |
| 89 | mapType(manager, returnType, k); |
| 90 | } else { |
| 91 | mapType(manager, returnType, method.getGenericReturnType()); |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | @SuppressWarnings("rawtypes") |
| 96 | private void mapType(MappingManager manager, Class<?> fullReturnType, Type type) { |
| 97 | |
| 98 | if (type instanceof ParameterizedType) { |
| 99 | ParameterizedType pt = (ParameterizedType)type; |
| 100 | Type raw = pt.getRawType(); |
| 101 | if (raw instanceof Class && Result.class.isAssignableFrom((Class)raw)) { |
| 102 | type = pt.getActualTypeArguments()[0]; |
| 103 | } else { |
| 104 | mapOne = true; |
| 105 | } |
| 106 | } else { |
| 107 | mapOne = true; |
| 108 | } |
| 109 | |
| 110 | if (!(type instanceof Class)) |
| 111 | throw new RuntimeException(String.format("Cannot map return of method %s to unsupported type %s", method, type)); |
| 112 | |
| 113 | try { |
| 114 | this.returnMapper = (Mapper<?>)manager.mapper((Class<?>)type); |
| 115 | } catch (Exception e) { |
| 116 | throw new RuntimeException("Cannot map return to class " + fullReturnType, e); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | public Object invoke(Object[] args) { |
| 121 | |
| 122 | BoundStatement bs = statement.bind(); |
| 123 | |
| 124 | ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum(); |
| 125 | for (int i = 0; i < args.length; i++) { |
| 126 | paramMappers[i].setValue(bs, args[i], protocolVersion); |
| 127 | } |
| 128 | |
| 129 | if (consistency != null) |
| 130 | bs.setConsistencyLevel(consistency); |
| 131 | if (fetchSize > 0) |
| 132 | bs.setFetchSize(fetchSize); |
| 133 | if (tracing) |
| 134 | bs.enableTracing(); |
| 135 | |
| 136 | if (returnStatement) |
| 137 | return bs; |
| 138 | |
| 139 | if (async) { |
| 140 | ListenableFuture<ResultSet> future = session.executeAsync(bs); |
| 141 | if (returnMapper == null) |
| 142 | return future; |
| 143 | |
| 144 | return mapOne |
| 145 | ? Futures.transform(future, returnMapper.mapOneFunctionWithoutAliases) |
| 146 | : Futures.transform(future, returnMapper.mapAllFunctionWithoutAliases); |
| 147 | } else { |
| 148 | ResultSet rs = session.execute(bs); |
| 149 | if (returnMapper == null) |
| 150 | return rs; |
| 151 | |
| 152 | Result<?> result = returnMapper.map(rs); |
| 153 | return mapOne ? result.one() : result; |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | static class ParamMapper { |
| 158 | // We'll only set one of the other. If paramName is null, then paramIdx is used. |
| 159 | private final String paramName; |
| 160 | private final int paramIdx; |
| 161 | private final DataType dataType; |
| 162 | |
| 163 | public ParamMapper(String paramName, int paramIdx, DataType dataType) { |
| 164 | this.paramName = paramName; |
| 165 | this.paramIdx = paramIdx; |
| 166 | this.dataType = dataType; |
| 167 | } |
| 168 | |
| 169 | public ParamMapper(String paramName, int paramIdx) { |
| 170 | this(paramName, paramIdx, null); |
| 171 | } |
| 172 | |
| 173 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 174 | ByteBuffer serializedArg = (dataType == null) |
| 175 | ? DataType.serializeValue(arg, protocolVersion) |
| 176 | : dataType.serialize(arg, protocolVersion); |
| 177 | if (paramName == null) { |
| 178 | if (arg == null) |
| 179 | boundStatement.setToNull(paramIdx); |
| 180 | else |
| 181 | boundStatement.setBytesUnsafe(paramIdx, serializedArg); |
| 182 | } else { |
| 183 | if (arg == null) |
| 184 | boundStatement.setToNull(paramName); |
| 185 | else |
| 186 | boundStatement.setBytesUnsafe(paramName, serializedArg); |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | static class UDTParamMapper<V> extends ParamMapper { |
| 192 | private final UDTMapper<V> udtMapper; |
| 193 | |
| 194 | UDTParamMapper(String paramName, int paramIdx, UDTMapper<V> udtMapper) { |
| 195 | super(paramName, paramIdx); |
| 196 | this.udtMapper = udtMapper; |
| 197 | } |
| 198 | |
| 199 | @Override |
| 200 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 201 | @SuppressWarnings("unchecked") |
| 202 | V entity = (V) arg; |
| 203 | UDTValue udtArg = arg != null ? udtMapper.toUDT(entity) : null; |
| 204 | super.setValue(boundStatement, udtArg, protocolVersion); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | /** |
| 209 | * Maps a nested collection which has a mapped UDT somewhere in the hierarchy. |
| 210 | */ |
| 211 | static class NestedUDTParamMapper extends ParamMapper { |
| 212 | private final InferredCQLType inferredCQLType; |
| 213 | |
| 214 | NestedUDTParamMapper(String paramName, int paramIdx, InferredCQLType inferredCQLType) { |
| 215 | super(paramName, paramIdx); |
| 216 | this.inferredCQLType = inferredCQLType; |
| 217 | } |
| 218 | |
| 219 | @Override |
| 220 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 221 | super.setValue(boundStatement, |
| 222 | UDTMapper.convertEntitiesToUDTs(arg, inferredCQLType), |
| 223 | protocolVersion); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | static class EnumParamMapper extends ParamMapper { |
| 228 | |
| 229 | private final EnumType enumType; |
| 230 | |
| 231 | public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) { |
| 232 | super(paramName, paramIdx); |
| 233 | this.enumType = enumType; |
| 234 | } |
| 235 | |
| 236 | @Override |
| 237 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 238 | super.setValue(boundStatement, convert(arg), protocolVersion); |
| 239 | } |
| 240 | |
| 241 | @SuppressWarnings("rawtypes") |
| 242 | private Object convert(Object arg) { |
| 243 | if(arg == null) |
| 244 | return arg; |
| 245 | |
| 246 | switch (enumType) { |
| 247 | case STRING: |
| 248 | return arg.toString(); |
| 249 | case ORDINAL: |
| 250 | return ((Enum) arg).ordinal(); |
| 251 | } |
| 252 | throw new AssertionError(); |
| 253 | } |
| 254 | } |
| 255 | } |