c0232298245fe95a73ddae1e257208d932731445
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / md / sal / binding / impl / RpcServiceAdapter.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
9 package org.opendaylight.controller.md.sal.binding.impl;
10
11 import com.google.common.base.Function;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Proxy;
21 import java.util.Map.Entry;
22 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
23 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
24 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
25 import org.opendaylight.controller.md.sal.dom.broker.spi.rpc.RpcRoutingStrategy;
26 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
27 import org.opendaylight.yangtools.yang.binding.DataContainer;
28 import org.opendaylight.yangtools.yang.binding.DataObject;
29 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
30 import org.opendaylight.yangtools.yang.binding.RpcService;
31 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.RpcResult;
34 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
41 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
43
44 class RpcServiceAdapter implements InvocationHandler {
45
46     private final ImmutableMap<Method, RpcInvocationStrategy> rpcNames;
47     private final Class<? extends RpcService> type;
48     private final BindingToNormalizedNodeCodec codec;
49     private final DOMRpcService delegate;
50     private final RpcService proxy;
51
52     RpcServiceAdapter(final Class<? extends RpcService> type, final BindingToNormalizedNodeCodec codec,
53             final DOMRpcService domService) {
54         this.type = Preconditions.checkNotNull(type);
55         this.codec = Preconditions.checkNotNull(codec);
56         this.delegate = Preconditions.checkNotNull(domService);
57         final ImmutableMap.Builder<Method, RpcInvocationStrategy> rpcBuilder = ImmutableMap.builder();
58         for (final Entry<Method, RpcDefinition> rpc : codec.getRpcMethodToSchema(type).entrySet()) {
59             rpcBuilder.put(rpc.getKey(), createStrategy(rpc.getKey(), rpc.getValue()));
60         }
61         rpcNames = rpcBuilder.build();
62         proxy = (RpcService) Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, this);
63     }
64
65     private ListenableFuture<RpcResult<?>> invoke0(final SchemaPath schemaPath, final NormalizedNode<?, ?> input) {
66         final CheckedFuture<DOMRpcResult, DOMRpcException> result = delegate.invokeRpc(schemaPath, input);
67         if (result instanceof LazyDOMRpcResultFuture) {
68             return ((LazyDOMRpcResultFuture) result).getBindingFuture();
69         }
70
71         return transformFuture(schemaPath, result, codec.getCodecFactory());
72     }
73
74     private RpcInvocationStrategy createStrategy(final Method method, final RpcDefinition schema) {
75         final RpcRoutingStrategy strategy = RpcRoutingStrategy.from(schema);
76         if (strategy.isContextBasedRouted()) {
77             return new RoutedStrategy(schema.getPath(), method, strategy.getLeaf());
78         }
79         return new NonRoutedStrategy(schema.getPath());
80     }
81
82     RpcService getProxy() {
83         return proxy;
84     }
85
86     @Override
87     public Object invoke(final Object proxyObj, final Method method, final Object[] args) throws Throwable {
88
89         final RpcInvocationStrategy rpc = rpcNames.get(method);
90         if (rpc != null) {
91             if (method.getParameterTypes().length == 0) {
92                 return rpc.invokeEmpty();
93             }
94             if (args.length != 1) {
95                 throw new IllegalArgumentException("Input must be provided.");
96             }
97             return rpc.invoke((DataObject) args[0]);
98         }
99
100         if (isObjectMethod(method)) {
101             return callObjectMethod(proxyObj, method, args);
102         }
103         throw new UnsupportedOperationException("Method " + method.toString() + "is unsupported.");
104     }
105
106     private static boolean isObjectMethod(final Method method) {
107         switch (method.getName()) {
108             case "toString":
109                 return method.getReturnType().equals(String.class) && method.getParameterTypes().length == 0;
110             case "hashCode":
111                 return method.getReturnType().equals(int.class) && method.getParameterTypes().length == 0;
112             case "equals":
113                 return method.getReturnType().equals(boolean.class) && method.getParameterTypes().length == 1 && method
114                         .getParameterTypes()[0] == Object.class;
115             default:
116                 return false;
117         }
118     }
119
120     private Object callObjectMethod(final Object self, final Method method, final Object[] args) {
121         switch (method.getName()) {
122             case "toString":
123                 return type.getName() + "$Adapter{delegate=" + delegate.toString() + "}";
124             case "hashCode":
125                 return System.identityHashCode(self);
126             case "equals":
127                 return self == args[0];
128             default:
129                 return null;
130         }
131     }
132
133     private static ListenableFuture<RpcResult<?>> transformFuture(final SchemaPath rpc,
134             final ListenableFuture<DOMRpcResult> domFuture, final BindingNormalizedNodeSerializer codec) {
135         return Futures.transform(domFuture, (Function<DOMRpcResult, RpcResult<?>>) input -> {
136             final NormalizedNode<?, ?> domData = input.getResult();
137             final DataObject bindingResult;
138             if (domData != null) {
139                 final SchemaPath rpcOutput = rpc.createChild(QName.create(rpc.getLastComponent(), "output"));
140                 bindingResult = codec.fromNormalizedNodeRpcData(rpcOutput, (ContainerNode) domData);
141             } else {
142                 bindingResult = null;
143             }
144             return RpcResult.class.cast(RpcResultBuilder.success(bindingResult).build());
145         }, MoreExecutors.directExecutor());
146     }
147
148     private abstract class RpcInvocationStrategy {
149
150         private final SchemaPath rpcName;
151
152         protected RpcInvocationStrategy(final SchemaPath path) {
153             rpcName = path;
154         }
155
156         final ListenableFuture<RpcResult<?>> invoke(final DataObject input) {
157             return invoke0(rpcName, serialize(input));
158         }
159
160         abstract NormalizedNode<?, ?> serialize(DataObject input);
161
162         final ListenableFuture<RpcResult<?>> invokeEmpty() {
163             return invoke0(rpcName, null);
164         }
165
166         final SchemaPath getRpcName() {
167             return rpcName;
168         }
169     }
170
171     private final class NonRoutedStrategy extends RpcInvocationStrategy {
172
173         protected NonRoutedStrategy(final SchemaPath path) {
174             super(path);
175         }
176
177         @Override
178         NormalizedNode<?, ?> serialize(final DataObject input) {
179             return LazySerializedContainerNode.create(getRpcName(), input, codec.getCodecRegistry());
180         }
181     }
182
183     private final class RoutedStrategy extends RpcInvocationStrategy {
184
185         private final ContextReferenceExtractor refExtractor;
186         private final NodeIdentifier contextName;
187
188         protected RoutedStrategy(final SchemaPath path, final Method rpcMethod, final QName leafName) {
189             super(path);
190             final Class<? extends DataContainer> inputType = BindingReflections.resolveRpcInputClass(rpcMethod).get();
191             refExtractor = ContextReferenceExtractor.from(inputType);
192             this.contextName = new NodeIdentifier(leafName);
193         }
194
195         @Override
196         NormalizedNode<?, ?> serialize(final DataObject input) {
197             final InstanceIdentifier<?> bindingII = refExtractor.extract(input);
198             if (bindingII != null) {
199                 final YangInstanceIdentifier yangII = codec.toYangInstanceIdentifierCached(bindingII);
200                 final LeafNode<?> contextRef = ImmutableNodes.leafNode(contextName, yangII);
201                 return LazySerializedContainerNode.withContextRef(getRpcName(), input, contextRef,
202                         codec.getCodecRegistry());
203             }
204             return LazySerializedContainerNode.create(getRpcName(), input, codec.getCodecRegistry());
205         }
206     }
207 }