| 1 | /* |
| 2 | * Copyright (C) 2012-2014 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.util.List; |
| 22 | import java.util.Map; |
| 23 | import java.util.Set; |
| 24 | |
| 25 | import com.google.common.util.concurrent.Futures; |
| 26 | import com.google.common.util.concurrent.ListenableFuture; |
| 27 | |
| 28 | import 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 |
| 32 | class 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 | if (method.isVarArgs()) |
| 64 | throw new IllegalArgumentException(String.format("Invalid varargs method %s in @Accessor interface")); |
| 65 | if (ps.getVariables().size() != method.getParameterTypes().length) |
| 66 | 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)", |
| 67 | method.getName(), method.getParameterTypes().length, ps.getVariables().size())); |
| 68 | |
| 69 | // TODO: we should also validate the types of the parameters... |
| 70 | |
| 71 | Class<?> returnType = method.getReturnType(); |
| 72 | if (Void.class.isAssignableFrom(returnType) || ResultSet.class.isAssignableFrom(returnType)) |
| 73 | return; |
| 74 | |
| 75 | if (Statement.class.isAssignableFrom(returnType)) { |
| 76 | returnStatement = true; |
| 77 | return; |
| 78 | } |
| 79 | |
| 80 | if (ResultSetFuture.class.isAssignableFrom(returnType)) { |
| 81 | this.async = true; |
| 82 | return; |
| 83 | } |
| 84 | |
| 85 | if (ListenableFuture.class.isAssignableFrom(returnType)) { |
| 86 | this.async = true; |
| 87 | Type k = ((ParameterizedType)method.getGenericReturnType()).getActualTypeArguments()[0]; |
| 88 | if (k instanceof Class && ResultSet.class.isAssignableFrom((Class<?>)k)) |
| 89 | return; |
| 90 | |
| 91 | mapType(manager, returnType, k); |
| 92 | } else { |
| 93 | mapType(manager, returnType, method.getGenericReturnType()); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | @SuppressWarnings("rawtypes") |
| 98 | private void mapType(MappingManager manager, Class<?> fullReturnType, Type type) { |
| 99 | |
| 100 | if (type instanceof ParameterizedType) { |
| 101 | ParameterizedType pt = (ParameterizedType)type; |
| 102 | Type raw = pt.getRawType(); |
| 103 | if (raw instanceof Class && Result.class.isAssignableFrom((Class)raw)) { |
| 104 | type = pt.getActualTypeArguments()[0]; |
| 105 | } else { |
| 106 | mapOne = true; |
| 107 | } |
| 108 | } else { |
| 109 | mapOne = true; |
| 110 | } |
| 111 | |
| 112 | if (!(type instanceof Class)) |
| 113 | throw new RuntimeException(String.format("Cannot map return of method %s to unsupported type %s", method, type)); |
| 114 | |
| 115 | try { |
| 116 | this.returnMapper = (Mapper<?>)manager.mapper((Class<?>)type); |
| 117 | } catch (Exception e) { |
| 118 | throw new RuntimeException("Cannot map return to class " + fullReturnType, e); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | public Object invoke(Object[] args) { |
| 123 | |
| 124 | BoundStatement bs = statement.bind(); |
| 125 | |
| 126 | ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum(); |
| 127 | for (int i = 0; i < args.length; i++) { |
| 128 | paramMappers[i].setValue(bs, args[i], protocolVersion); |
| 129 | } |
| 130 | |
| 131 | if (consistency != null) |
| 132 | bs.setConsistencyLevel(consistency); |
| 133 | if (fetchSize > 0) |
| 134 | bs.setFetchSize(fetchSize); |
| 135 | if (tracing) |
| 136 | bs.enableTracing(); |
| 137 | |
| 138 | if (returnStatement) |
| 139 | return bs; |
| 140 | |
| 141 | if (async) { |
| 142 | ListenableFuture<ResultSet> future = session.executeAsync(bs); |
| 143 | if (returnMapper == null) |
| 144 | return future; |
| 145 | |
| 146 | return mapOne |
| 147 | ? Futures.transform(future, returnMapper.mapOneFunction) |
| 148 | : Futures.transform(future, returnMapper.mapAllFunction); |
| 149 | } else { |
| 150 | ResultSet rs = session.execute(bs); |
| 151 | if (returnMapper == null) |
| 152 | return rs; |
| 153 | |
| 154 | Result<?> result = returnMapper.map(rs); |
| 155 | return mapOne ? result.one() : result; |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | static class ParamMapper { |
| 160 | // We'll only set one of the other. If paramName is null, then paramIdx is used. |
| 161 | private final String paramName; |
| 162 | private final int paramIdx; |
| 163 | |
| 164 | public ParamMapper(String paramName, int paramIdx) { |
| 165 | this.paramName = paramName; |
| 166 | this.paramIdx = paramIdx; |
| 167 | } |
| 168 | |
| 169 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 170 | if (paramName == null) { |
| 171 | if (arg == null) |
| 172 | boundStatement.setToNull(paramIdx); |
| 173 | else |
| 174 | boundStatement.setBytesUnsafe(paramIdx, DataType.serializeValue(arg, protocolVersion)); |
| 175 | } else { |
| 176 | if (arg == null) |
| 177 | boundStatement.setToNull(paramName); |
| 178 | else |
| 179 | boundStatement.setBytesUnsafe(paramName, DataType.serializeValue(arg, protocolVersion)); |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | static class UDTParamMapper<V> extends ParamMapper { |
| 185 | private final UDTMapper<V> udtMapper; |
| 186 | |
| 187 | UDTParamMapper(String paramName, int paramIdx, UDTMapper<V> udtMapper) { |
| 188 | super(paramName, paramIdx); |
| 189 | this.udtMapper = udtMapper; |
| 190 | } |
| 191 | |
| 192 | @Override |
| 193 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 194 | @SuppressWarnings("unchecked") |
| 195 | V entity = (V) arg; |
| 196 | super.setValue(boundStatement, udtMapper.toUDT(entity), protocolVersion); |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | static class UDTListParamMapper<V> extends ParamMapper { |
| 201 | private final UDTMapper<V> valueMapper; |
| 202 | |
| 203 | UDTListParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) { |
| 204 | super(paramName, paramIdx); |
| 205 | this.valueMapper = valueMapper; |
| 206 | } |
| 207 | |
| 208 | @Override |
| 209 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 210 | @SuppressWarnings("unchecked") |
| 211 | List<V> entities = (List<V>) arg; |
| 212 | super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | static class UDTSetParamMapper<V> extends ParamMapper { |
| 217 | private final UDTMapper<V> valueMapper; |
| 218 | |
| 219 | UDTSetParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) { |
| 220 | super(paramName, paramIdx); |
| 221 | this.valueMapper = valueMapper; |
| 222 | } |
| 223 | |
| 224 | @Override |
| 225 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 226 | @SuppressWarnings("unchecked") |
| 227 | Set<V> entities = (Set<V>) arg; |
| 228 | super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | static class UDTMapParamMapper<K, V> extends ParamMapper { |
| 233 | private final UDTMapper<K> keyMapper; |
| 234 | private final UDTMapper<V> valueMapper; |
| 235 | |
| 236 | UDTMapParamMapper(String paramName, int paramIdx, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper) { |
| 237 | super(paramName, paramIdx); |
| 238 | this.keyMapper = keyMapper; |
| 239 | this.valueMapper = valueMapper; |
| 240 | } |
| 241 | |
| 242 | @Override |
| 243 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 244 | @SuppressWarnings("unchecked") |
| 245 | Map<K, V> entities = (Map<K, V>) arg; |
| 246 | super.setValue(boundStatement, UDTMapper.toUDTValues(entities, keyMapper, valueMapper), protocolVersion); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | static class EnumParamMapper extends ParamMapper { |
| 251 | |
| 252 | private final EnumType enumType; |
| 253 | |
| 254 | public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) { |
| 255 | super(paramName, paramIdx); |
| 256 | this.enumType = enumType; |
| 257 | } |
| 258 | |
| 259 | @Override |
| 260 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 261 | super.setValue(boundStatement, convert(arg), protocolVersion); |
| 262 | } |
| 263 | |
| 264 | @SuppressWarnings("rawtypes") |
| 265 | private Object convert(Object arg) { |
| 266 | switch (enumType) { |
| 267 | case STRING: |
| 268 | return arg.toString(); |
| 269 | case ORDINAL: |
| 270 | return ((Enum) arg).ordinal(); |
| 271 | } |
| 272 | throw new AssertionError(); |
| 273 | } |
| 274 | } |
| 275 | } |