Move BindingReflections to mdsal-binding-spec-util
[mdsal.git] / binding / mdsal-binding-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / dom / adapter / invoke / AbstractMappedRpcInvoker.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.dom.adapter.invoke;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.ImmutableMap.Builder;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import java.lang.reflect.Method;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import javax.annotation.Nonnull;
19 import javax.annotation.Nullable;
20 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
21 import org.opendaylight.yangtools.yang.binding.DataObject;
22 import org.opendaylight.yangtools.yang.binding.RpcService;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.common.RpcResult;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 abstract class AbstractMappedRpcInvoker<T> extends RpcServiceInvoker {
29     private static final Logger LOG = LoggerFactory.getLogger(AbstractMappedRpcInvoker.class);
30
31     @VisibleForTesting
32     final Map<T, RpcMethodInvoker> map;
33
34     protected AbstractMappedRpcInvoker(final Map<T, Method> map) {
35         final Builder<T, RpcMethodInvoker> b = ImmutableMap.builder();
36
37         for (Entry<T, Method> e : map.entrySet()) {
38             if (BindingReflections.isRpcMethod(e.getValue())) {
39                 b.put(e.getKey(), RpcMethodInvoker.from(e.getValue()));
40             } else {
41                 LOG.debug("Method {} is not an RPC method, ignoring it", e.getValue());
42             }
43         }
44
45         this.map = b.build();
46     }
47
48     protected abstract T qnameToKey(QName qname);
49
50     @Override
51     public final ListenableFuture<RpcResult<?>> invokeRpc(@Nonnull final RpcService impl, @Nonnull final QName rpcName,
52             @Nullable final DataObject input) {
53         Preconditions.checkNotNull(impl, "Implementation must be supplied");
54
55         RpcMethodInvoker invoker = map.get(qnameToKey(rpcName));
56         Preconditions.checkArgument(invoker != null, "Supplied RPC is not valid for implementation %s", impl);
57         return invoker.invokeOn(impl, input);
58     }
59 }