Eliminate NormalizedNodePayload
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / spi / RpcImplementation.java
1 /*
2  * Copyright (c) 2023 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.restconf.server.spi;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.MoreObjects;
13 import java.net.URI;
14 import org.eclipse.jdt.annotation.NonNullByDefault;
15 import org.eclipse.jdt.annotation.Nullable;
16 import org.opendaylight.restconf.common.errors.RestconfFuture;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
21
22 /**
23  * An implementation of a YANG-defined RPC.
24  */
25 @NonNullByDefault
26 public abstract class RpcImplementation {
27     private final QName qname;
28
29     protected RpcImplementation(final QName qname) {
30         this.qname = requireNonNull(qname);
31     }
32
33     /**
34      * Return the RPC name, as defined by {@code rpc} statement's argument.
35      *
36      * @return The RPC name
37      */
38     public final QName qname() {
39         return qname;
40     }
41
42     /**
43      * Asynchronously invoke this implementation. Implementations are expected to report all results via the returned
44      * future, e.g. not throw exceptions.
45      *
46      * @param restconfURI Request URI trimmed to the root RESTCONF endpoint, resolved {@code {+restconf}} resource name
47      * @param input RPC input
48      * @return Future RPC output
49      */
50     public abstract RestconfFuture<ContainerNode> invoke(URI restconfURI, OperationInput input);
51
52     @Override
53     public final String toString() {
54         return MoreObjects.toStringHelper(this).add("qname", qname).toString();
55     }
56
57     protected static final <T> @Nullable T leaf(final ContainerNode parent, final NodeIdentifier arg,
58             final Class<T> type) {
59         final var child = parent.childByArg(arg);
60         if (child instanceof LeafNode<?> leafNode) {
61             final var body = leafNode.body();
62             try {
63                 return type.cast(body);
64             } catch (ClassCastException e) {
65                 throw new IllegalArgumentException("Bad child " + child.prettyTree(), e);
66             }
67         }
68         return null;
69     }
70 }