1 | /** |
2 | * |
3 | * Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com> |
4 | * |
5 | * ==================================================================== |
6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
7 | * you may not use this file except in compliance with the License. |
8 | * You may obtain a copy of the License at |
9 | * |
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
11 | * |
12 | * Unless required by applicable law or agreed to in writing, software |
13 | * distributed under the License is distributed on an "AS IS" BASIS, |
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15 | * See the License for the specific language governing permissions and |
16 | * limitations under the License. |
17 | * ==================================================================== |
18 | */ |
19 | package org.jclouds.rest.config; |
20 | |
21 | import java.util.Map; |
22 | import java.util.concurrent.ConcurrentMap; |
23 | |
24 | import javax.inject.Inject; |
25 | import javax.inject.Singleton; |
26 | |
27 | import org.jclouds.concurrent.internal.SyncProxy; |
28 | import org.jclouds.internal.ClassMethodArgs; |
29 | |
30 | import com.google.common.base.Throwables; |
31 | import com.google.inject.Injector; |
32 | import com.google.inject.Key; |
33 | import com.google.inject.Provider; |
34 | import com.google.inject.TypeLiteral; |
35 | import com.google.inject.name.Names; |
36 | |
37 | /** |
38 | * |
39 | * @author Adrian Cole |
40 | */ |
41 | @Singleton |
42 | public class ClientProvider<S, A> implements Provider<S> { |
43 | @Inject |
44 | Injector injector; |
45 | private final Class<S> syncClientType; |
46 | private final Class<A> asyncClientType; |
47 | private final Map<Class<?>, Class<?>> sync2Async; |
48 | |
49 | @Inject |
50 | ClientProvider(Class<S> syncClientType, Class<A> asyncClientType, |
51 | Map<Class<?>, Class<?>> sync2Async) { |
52 | this.asyncClientType = asyncClientType; |
53 | this.syncClientType = syncClientType; |
54 | this.sync2Async = sync2Async; |
55 | } |
56 | |
57 | @Override |
58 | @Singleton |
59 | public S get() { |
60 | A client = (A) injector.getInstance(Key.get(asyncClientType)); |
61 | ConcurrentMap<ClassMethodArgs, Object> delegateMap = injector.getInstance(Key.get( |
62 | new TypeLiteral<ConcurrentMap<ClassMethodArgs, Object>>() { |
63 | }, Names.named("sync"))); |
64 | try { |
65 | return (S) SyncProxy.proxy(syncClientType, new SyncProxy(syncClientType, client, |
66 | delegateMap, sync2Async)); |
67 | } catch (Exception e) { |
68 | Throwables.propagate(e); |
69 | assert false : "should have propagated"; |
70 | return null; |
71 | } |
72 | } |
73 | } |