ce6292c48734909ee357c0de77868dd781764904
[mdsal.git] / binding / mdsal-binding-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / dom / adapter / 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.mdsal.binding.dom.adapter;
10
11 import com.google.common.base.Function;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ImmutableMap;
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.Collection;
22 import java.util.Map.Entry;
23 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
24 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
25 import org.opendaylight.mdsal.dom.api.DOMRpcService;
26 import org.opendaylight.mdsal.dom.spi.RpcRoutingStrategy;
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     private RpcInvocationStrategy createStrategy(final Method method, final RpcDefinition schema) {
68         final RpcRoutingStrategy strategy = RpcRoutingStrategy.from(schema);
69         if (strategy.isContextBasedRouted()) {
70             return new RoutedStrategy(schema.getPath(), method, strategy.getLeaf());
71         }
72         return new NonRoutedStrategy(schema.getPath());
73     }
74
75     RpcService getProxy() {
76         return proxy;
77     }
78
79     @Override
80     @SuppressWarnings("checkstyle:hiddenField")
81     public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
82
83         final RpcInvocationStrategy rpc = rpcNames.get(method);
84         if (rpc != null) {
85             if (method.getParameterTypes().length == 0) {
86                 return rpc.invokeEmpty();
87             }
88             if (args.length != 1) {
89                 throw new IllegalArgumentException("Input must be provided.");
90             }
91             return rpc.invoke((DataObject) args[0]);
92         }
93
94         if (isObjectMethod(method)) {
95             return callObjectMethod(proxy, method, args);
96         }
97         throw new UnsupportedOperationException("Method " + method.toString() + "is unsupported.");
98     }
99
100     private static boolean isObjectMethod(final Method method) {
101         switch (method.getName()) {
102             case "toString":
103                 return method.getReturnType().equals(String.class) && method.getParameterTypes().length == 0;
104             case "hashCode":
105                 return method.getReturnType().equals(int.class) && method.getParameterTypes().length == 0;
106             case "equals":
107                 return method.getReturnType().equals(boolean.class) && method.getParameterTypes().length == 1
108                         && method.getParameterTypes()[0] == Object.class;
109             default:
110                 return false;
111         }
112     }
113
114     private Object callObjectMethod(final Object self, final Method method, final Object[] args) {
115         switch (method.getName()) {
116             case "toString":
117                 return type.getName() + "$Adapter{delegate=" + delegate.toString() + "}";
118             case "hashCode":
119                 return System.identityHashCode(self);
120             case "equals":
121                 return self == args[0];
122             default:
123                 return null;
124         }
125     }
126
127     private abstract class RpcInvocationStrategy {
128
129         private final SchemaPath rpcName;
130
131         protected RpcInvocationStrategy(final SchemaPath path) {
132             rpcName = path;
133         }
134
135         final ListenableFuture<RpcResult<?>> invoke(final DataObject input) {
136             return invoke0(rpcName, serialize(input));
137         }
138
139         abstract NormalizedNode<?, ?> serialize(DataObject input);
140
141         final ListenableFuture<RpcResult<?>> invokeEmpty() {
142             return invoke0(rpcName, null);
143         }
144
145         final SchemaPath getRpcName() {
146             return rpcName;
147         }
148
149         private ListenableFuture<RpcResult<?>> invoke0(final SchemaPath schemaPath, final NormalizedNode<?, ?> input) {
150             final ListenableFuture<DOMRpcResult> result = delegate.invokeRpc(schemaPath, input);
151             if (result instanceof LazyDOMRpcResultFuture) {
152                 return ((LazyDOMRpcResultFuture) result).getBindingFuture();
153             }
154
155             return transformFuture(schemaPath, result, codec.getCodecFactory());
156         }
157
158         private ListenableFuture<RpcResult<?>> transformFuture(final SchemaPath rpc,
159                 final ListenableFuture<DOMRpcResult> domFuture, final BindingNormalizedNodeCodecRegistry resultCodec) {
160             return Futures.transform(domFuture, (Function<DOMRpcResult, RpcResult<?>>) input -> {
161                 final NormalizedNode<?, ?> domData = input.getResult();
162                 final DataObject bindingResult;
163                 if (domData != null) {
164                     final SchemaPath rpcOutput = rpc.createChild(QName.create(rpc.getLastComponent(), "output"));
165                     bindingResult = resultCodec.fromNormalizedNodeRpcData(rpcOutput, (ContainerNode) domData);
166                 } else {
167                     bindingResult = null;
168                 }
169
170                 // DOMRpcResult does not have a notion of success, hence we have to reverse-engineer it by looking
171                 // at reported errors and checking whether they are just warnings.
172                 final Collection<RpcError> errors = input.getErrors();
173                 return RpcResult.class.cast(RpcResultBuilder.status(errors.stream()
174                     .noneMatch(error -> error.getSeverity() == ErrorSeverity.ERROR))
175                     .withResult(bindingResult).withRpcErrors(errors).build());
176             }, MoreExecutors.directExecutor());
177         }
178     }
179
180     private final class NonRoutedStrategy extends RpcInvocationStrategy {
181
182         protected NonRoutedStrategy(final SchemaPath path) {
183             super(path);
184         }
185
186         @Override
187         NormalizedNode<?, ?> serialize(final DataObject input) {
188             return LazySerializedContainerNode.create(getRpcName(), input, codec.getCodecRegistry());
189         }
190
191     }
192
193     private final class RoutedStrategy extends RpcInvocationStrategy {
194
195         private final ContextReferenceExtractor refExtractor;
196         private final NodeIdentifier contextName;
197
198         protected RoutedStrategy(final SchemaPath path, final Method rpcMethod, final QName leafName) {
199             super(path);
200             final Optional<Class<? extends DataContainer>> maybeInputType =
201                     BindingReflections.resolveRpcInputClass(rpcMethod);
202             Preconditions.checkState(maybeInputType.isPresent(), "RPC method %s has no input", rpcMethod.getName());
203             final Class<? extends DataContainer> inputType = maybeInputType.get();
204             refExtractor = ContextReferenceExtractor.from(inputType);
205             this.contextName = new NodeIdentifier(leafName);
206         }
207
208         @Override
209         NormalizedNode<?, ?> serialize(final DataObject input) {
210             final InstanceIdentifier<?> bindingII = refExtractor.extract(input);
211             if (bindingII != null) {
212                 final YangInstanceIdentifier yangII = codec.toYangInstanceIdentifierCached(bindingII);
213                 final LeafNode<?> contextRef = ImmutableNodes.leafNode(contextName, yangII);
214                 return LazySerializedContainerNode.withContextRef(getRpcName(), input, contextRef,
215                         codec.getCodecRegistry());
216             }
217             return LazySerializedContainerNode.create(getRpcName(), input, codec.getCodecRegistry());
218         }
219
220     }
221 }