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