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