55c76f257ccfa866970dbbd93824770588b1d86f
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / databind / OperationInputBody.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.nb.rfc8040.databind;
9
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.PushbackInputStream;
13 import org.eclipse.jdt.annotation.NonNull;
14 import org.opendaylight.restconf.server.api.OperationsPostPath;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
17 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
18 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
19 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
20 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
21
22 /**
23  * Access to an {code rpc}'s or an {@code action}'s input.
24  */
25 public abstract sealed class OperationInputBody extends AbstractBody
26         permits JsonOperationInputBody, XmlOperationInputBody {
27     OperationInputBody(final InputStream inputStream) {
28         super(inputStream);
29     }
30
31     /**
32      * Stream the {@code input} into a {@link NormalizedNodeStreamWriter}.
33      *
34      * @param path The {@link OperationsPostPath} of the operation invocation
35      * @return The document body, or an empty container node
36      * @throws IOException when an I/O error occurs
37      */
38     public @NonNull ContainerNode toContainerNode(final @NonNull OperationsPostPath path) throws IOException {
39         try (var is = new PushbackInputStream(acquireStream())) {
40             final var firstByte = is.read();
41             if (firstByte == -1) {
42                 return ImmutableNodes.newContainerBuilder()
43                     .withNodeIdentifier(new NodeIdentifier(path.inputQName()))
44                     .build();
45             }
46             is.unread(firstByte);
47
48             final var holder = new NormalizationResultHolder();
49             try (var streamWriter = ImmutableNormalizedNodeStreamWriter.from(holder)) {
50                 streamTo(path, is, streamWriter);
51             }
52             return (ContainerNode) holder.getResult().data();
53         }
54     }
55
56     abstract void streamTo(@NonNull OperationsPostPath path, @NonNull InputStream inputStream,
57         @NonNull NormalizedNodeStreamWriter writer) throws IOException;
58 }