1 | /** |
2 | * Licensed to jclouds, Inc. (jclouds) under one or more |
3 | * contributor license agreements. See the NOTICE file |
4 | * distributed with this work for additional information |
5 | * regarding copyright ownership. jclouds licenses this file |
6 | * to you under the Apache License, Version 2.0 (the |
7 | * "License"); you may not use this file except in compliance |
8 | * with the License. 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, |
13 | * software distributed under the License is distributed on an |
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
15 | * KIND, either express or implied. See the License for the |
16 | * specific language governing permissions and limitations |
17 | * under the License. |
18 | */ |
19 | package org.jclouds.rest.config; |
20 | |
21 | import java.util.Map; |
22 | |
23 | import javax.inject.Inject; |
24 | import javax.inject.Singleton; |
25 | |
26 | import org.jclouds.concurrent.internal.SyncProxy; |
27 | import org.jclouds.internal.ClassMethodArgs; |
28 | |
29 | import com.google.common.base.Throwables; |
30 | import com.google.common.cache.Cache; |
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 | * ClientProvider makes the primary interface for the provider context. ex. {@code |
39 | * context.getProviderSpecificContext().getApi()} is created by ClientProvider, which is a singleton |
40 | * |
41 | * @author Adrian Cole |
42 | */ |
43 | @Singleton |
44 | public class ClientProvider<S, A> implements Provider<S> { |
45 | @Inject |
46 | Injector injector; |
47 | private final Class<S> syncClientType; |
48 | private final Class<A> asyncClientType; |
49 | private final Map<Class<?>, Class<?>> sync2Async; |
50 | |
51 | @Inject |
52 | ClientProvider(Class<S> syncClientType, Class<A> asyncClientType, Map<Class<?>, Class<?>> sync2Async) { |
53 | this.asyncClientType = asyncClientType; |
54 | this.syncClientType = syncClientType; |
55 | this.sync2Async = sync2Async; |
56 | } |
57 | |
58 | @Override |
59 | @Singleton |
60 | public S get() { |
61 | A client = (A) injector.getInstance(Key.get(asyncClientType)); |
62 | Cache<ClassMethodArgs, Object> delegateMap = injector.getInstance(Key.get( |
63 | new TypeLiteral<Cache<ClassMethodArgs, Object>>() { |
64 | }, Names.named("sync"))); |
65 | try { |
66 | return (S) SyncProxy.proxy(syncClientType, client, delegateMap, sync2Async, |
67 | injector.getInstance(Key.get(new TypeLiteral<Map<String, Long>>() { |
68 | }, Names.named("TIMEOUTS")))); |
69 | } catch (Exception e) { |
70 | Throwables.propagate(e); |
71 | assert false : "should have propagated"; |
72 | return null; |
73 | } |
74 | } |
75 | } |