| 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 static com.google.common.base.Preconditions.checkState; |
| 22 | |
| 23 | import java.util.Map; |
| 24 | import java.util.concurrent.ConcurrentMap; |
| 25 | |
| 26 | import javax.inject.Inject; |
| 27 | import javax.inject.Named; |
| 28 | |
| 29 | import org.jclouds.concurrent.internal.SyncProxy; |
| 30 | import org.jclouds.internal.ClassMethodArgs; |
| 31 | |
| 32 | import com.google.common.base.Function; |
| 33 | import com.google.common.base.Throwables; |
| 34 | import com.google.inject.Provider; |
| 35 | |
| 36 | /** |
| 37 | * |
| 38 | * @author Adrian Cole |
| 39 | */ |
| 40 | public class CreateClientForCaller implements Function<ClassMethodArgs, Object> { |
| 41 | private final ConcurrentMap<ClassMethodArgs, Object> asyncMap; |
| 42 | private final Provider<ConcurrentMap<ClassMethodArgs, Object>> delegateMap; |
| 43 | Map<Class<?>, Class<?>> sync2Async; |
| 44 | |
| 45 | @Inject |
| 46 | CreateClientForCaller(@Named("async") ConcurrentMap<ClassMethodArgs, Object> asyncMap, |
| 47 | @Named("sync") Provider<ConcurrentMap<ClassMethodArgs, Object>> delegateMap) { |
| 48 | this.asyncMap = asyncMap; |
| 49 | this.delegateMap = delegateMap; |
| 50 | } |
| 51 | |
| 52 | public Object apply(ClassMethodArgs from) { |
| 53 | Class<?> syncClass = from.getMethod().getReturnType(); |
| 54 | Class<?> asyncClass = sync2Async.get(syncClass); |
| 55 | checkState(asyncClass != null, "configuration error, sync class " + syncClass |
| 56 | + " not mapped to an async class"); |
| 57 | Object asyncClient = asyncMap.get(from); |
| 58 | checkState(asyncClient != null, "configuration error, sync client for " + from + " not found"); |
| 59 | try { |
| 60 | return SyncProxy.proxy(syncClass, new SyncProxy(syncClass, asyncClient, delegateMap.get(), |
| 61 | sync2Async)); |
| 62 | } catch (Exception e) { |
| 63 | Throwables.propagate(e); |
| 64 | assert false : "should have propagated"; |
| 65 | return null; |
| 66 | } |
| 67 | |
| 68 | } |
| 69 | } |