Move getRpcMethodToSchema()
[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 package org.opendaylight.mdsal.binding.dom.adapter;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.ImmutableBiMap;
13 import com.google.common.collect.ImmutableMap;
14 import java.lang.reflect.InvocationHandler;
15 import java.lang.reflect.Method;
16 import java.lang.reflect.Proxy;
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.mdsal.binding.runtime.api.RpcRuntimeType;
21 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
22 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
23 import org.opendaylight.mdsal.dom.api.DOMRpcService;
24 import org.opendaylight.yangtools.yang.binding.DataObject;
25 import org.opendaylight.yangtools.yang.binding.RpcService;
26 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
27
28 class RpcServiceAdapter implements InvocationHandler {
29     private final ImmutableMap<Method, RpcInvocationStrategy> rpcNames;
30     private final @NonNull Class<? extends RpcService> type;
31     private final @NonNull AdapterContext adapterContext;
32     private final @NonNull DOMRpcService delegate;
33     private final @NonNull RpcService facade;
34
35     RpcServiceAdapter(final Class<? extends RpcService> type, final AdapterContext adapterContext,
36             final DOMRpcService domService) {
37         this.type = requireNonNull(type);
38         this.adapterContext = requireNonNull(adapterContext);
39         delegate = requireNonNull(domService);
40         facade = (RpcService) Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, this);
41
42         final var methods = getRpcMethodToSchema(adapterContext.currentSerializer(), type);
43         final var rpcBuilder = ImmutableMap.<Method, RpcInvocationStrategy>builderWithExpectedSize(methods.size());
44         for (var entry : methods.entrySet()) {
45             final var method = entry.getKey();
46             rpcBuilder.put(method, RpcInvocationStrategy.of(this, method, entry.getValue()));
47         }
48         rpcNames = rpcBuilder.build();
49     }
50
51     final @NonNull CurrentAdapterSerializer currentSerializer() {
52         return adapterContext.currentSerializer();
53     }
54
55     final @NonNull DOMRpcService delegate() {
56         return delegate;
57     }
58
59     final @NonNull RpcService facade() {
60         return facade;
61     }
62
63     @Override
64     public Object invoke(final Object proxy, final Method method, final Object[] args) {
65         final var strategy = rpcNames.get(method);
66         if (strategy != null) {
67             if (args.length != 1) {
68                 throw new IllegalArgumentException("Input must be provided.");
69             }
70             return strategy.invoke((DataObject) requireNonNull(args[0]));
71         }
72
73         switch (method.getName()) {
74             case "toString":
75                 if (method.getReturnType().equals(String.class) && method.getParameterCount() == 0) {
76                     return type.getName() + "$Adapter{delegate=" + delegate.toString() + "}";
77                 }
78                 break;
79             case "hashCode":
80                 if (method.getReturnType().equals(int.class) && method.getParameterCount() == 0) {
81                     return System.identityHashCode(proxy);
82                 }
83                 break;
84             case "equals":
85                 if (method.getReturnType().equals(boolean.class) && method.getParameterCount() == 1
86                         && method.getParameterTypes()[0] == Object.class) {
87                     return proxy == args[0];
88                 }
89                 break;
90             default:
91                 break;
92         }
93
94         throw new UnsupportedOperationException("Method " + method.toString() + "is unsupported.");
95     }
96
97     // FIXME: This should be probably part of BindingRuntimeContext and RpcServices perhaps should have their own
98     //        RuntimeType
99     private static ImmutableBiMap<Method, RpcRuntimeType> getRpcMethodToSchema(
100             final CurrentAdapterSerializer serializer, final Class<? extends RpcService> key) {
101         final var runtimeContext = serializer.getRuntimeContext();
102         final var types = runtimeContext.getTypes();
103         final var qnameModule = BindingReflections.getQNameModule(key);
104
105         // We are dancing a bit here to reconstruct things a RpcServiceRuntimeType could easily hold
106         final var module = runtimeContext.getEffectiveModelContext().findModuleStatement(qnameModule)
107             .orElseThrow(() -> new IllegalStateException("No module found for " + qnameModule + " service " + key));
108         return module.streamEffectiveSubstatements(RpcEffectiveStatement.class)
109             .map(rpc -> {
110                 final var rpcName = rpc.argument();
111                 final var inputClz = runtimeContext.getRpcInput(rpcName);
112                 final var methodName = BindingMapping.getRpcMethodName(rpcName);
113
114                 final Method method;
115                 try {
116                     method = key.getMethod(methodName, inputClz);
117                 } catch (NoSuchMethodException e) {
118                     throw new IllegalStateException("Cannot find RPC method for " + rpc, e);
119                 }
120
121                 final var type = types.schemaTreeChild(rpcName);
122                 if (!(type instanceof RpcRuntimeType rpcType)) {
123                     throw new IllegalStateException("Unexpected run-time type " + type + " for " + rpcName);
124                 }
125                 return Map.entry(method, rpcType);
126             })
127             .collect(ImmutableBiMap.toImmutableBiMap(Entry::getKey, Entry::getValue));
128     }
129 }