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