Add support for registering single-RPC services
[mdsal.git] / binding / mdsal-binding-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / dom / adapter / RpcAdapter.java
1 /*
2  * Copyright (c) 2022 PANTHEON.tech, s.r.o. 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;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.lang.reflect.Method;
13 import org.opendaylight.mdsal.dom.api.DOMRpcService;
14 import org.opendaylight.yangtools.yang.binding.Rpc;
15 import org.opendaylight.yangtools.yang.binding.RpcInput;
16
17 final class RpcAdapter<T extends Rpc<?, ?>> extends AbstractRpcAdapter {
18     private final RpcInvocationStrategy strategy;
19     private final Method invokeMethod;
20
21     RpcAdapter(final AdapterContext adapterContext, final DOMRpcService delegate, final Class<T> type) {
22         super(adapterContext, delegate, type);
23
24         final var serializer = adapterContext.currentSerializer();
25         final var rpcType = serializer.getRuntimeContext().getRpcDefinition(type);
26         if (rpcType == null) {
27             throw new IllegalStateException("Failed to find runtime type for " + type);
28         }
29
30         try {
31             invokeMethod = type.getMethod("invoke", RpcInput.class);
32         } catch (NoSuchMethodException e) {
33             throw new IllegalStateException("Failed to find invoke method in " + type, e);
34         }
35
36         strategy = createStrategy(serializer, rpcType);
37     }
38
39     @Override
40     public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
41         return invokeMethod.equals(method) ? strategy.invoke((RpcInput) requireNonNull(args[0]))
42             : defaultInvoke(proxy, method, args);
43     }
44 }