Separate logic of get root path
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / databind / JsonOperationInputBody.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 com.google.gson.JsonParseException;
11 import com.google.gson.stream.JsonReader;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.InputStreamReader;
15 import java.nio.charset.StandardCharsets;
16 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
17 import org.opendaylight.restconf.server.api.OperationsPostPath;
18 import org.opendaylight.yangtools.yang.common.ErrorTag;
19 import org.opendaylight.yangtools.yang.common.ErrorType;
20 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
21 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 public final class JsonOperationInputBody extends OperationInputBody {
26     private static final Logger LOG = LoggerFactory.getLogger(JsonOperationInputBody.class);
27
28     public JsonOperationInputBody(final InputStream inputStream) {
29         super(inputStream);
30     }
31
32     @Override
33     void streamTo(final OperationsPostPath path, final InputStream inputStream, final NormalizedNodeStreamWriter writer)
34             throws IOException {
35         try {
36             JsonParserStream.create(writer, path.databind().jsonCodecs(), path.operation())
37                 .parse(new JsonReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)));
38         } catch (JsonParseException e) {
39             LOG.debug("Error parsing JSON input", e);
40             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
41                     ErrorTag.MALFORMED_MESSAGE, e);
42         }
43     }
44 }