Elffuss BraidHub

kikocis/java-driver public

9b39ff6a48bf · 2.4 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.PreparedStatement;
19import com.google.common.util.concurrent.Futures;
20import com.google.common.util.concurrent.ListenableFuture;
21
22import java.lang.reflect.Proxy;
23import java.util.ArrayList;
24import java.util.List;
25
26class AccessorMapper<T> {
27
28 final Class<T> daoClass;
29 final List<MethodMapper> methods;
30 private final Class<T>[] proxyClasses;
31 private final AccessorInvocationHandler<T> handler;
32
33 @SuppressWarnings({"unchecked", "rawtypes"})
34 AccessorMapper(Class<T> daoClass, List<MethodMapper> methods) {
35 this.daoClass = daoClass;
36 this.methods = methods;
37 this.proxyClasses = (Class<T>[]) new Class[]{daoClass};
38 this.handler = new AccessorInvocationHandler<T>(this);
39 }
40
41 @SuppressWarnings("unchecked")
42 T createProxy() {
43 try {
44 return (T) Proxy.newProxyInstance(daoClass.getClassLoader(), proxyClasses, handler);
45 } catch (Exception e) {
46 throw new RuntimeException("Cannot create instance for Accessor interface " + daoClass.getName());
47 }
48 }
49
50 void prepare(MappingManager manager) {
51 List<ListenableFuture<PreparedStatement>> statements = new ArrayList<ListenableFuture<PreparedStatement>>(methods.size());
52
53 for (MethodMapper method : methods)
54 statements.add(manager.getSession().prepareAsync(method.queryString));
55
56 try {
57 List<PreparedStatement> preparedStatements = Futures.allAsList(statements).get();
58 for (int i = 0; i < methods.size(); i++)
59 methods.get(i).prepare(manager, preparedStatements.get(i));
60 } catch (Exception e) {
61 throw new RuntimeException("Error preparing queries for accessor " + daoClass.getSimpleName(), e);
62 }
63 }
64
65}