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