Eliminate NormalizedNodePayload
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / spi / FormattableBodySupport.java
1 /*
2  * Copyright (c) 2024 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 com.google.gson.stream.JsonWriter;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.io.OutputStreamWriter;
14 import java.nio.charset.StandardCharsets;
15 import javanet.staxutils.IndentingXMLStreamWriter;
16 import javax.xml.stream.FactoryConfigurationError;
17 import javax.xml.stream.XMLOutputFactory;
18 import javax.xml.stream.XMLStreamException;
19 import javax.xml.stream.XMLStreamWriter;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.opendaylight.restconf.api.FormattableBody;
22 import org.opendaylight.restconf.api.query.PrettyPrintParam;
23 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
24
25 /**
26  * Various methods supporting {@link FormattableBody}.
27  */
28 @NonNullByDefault
29 public final class FormattableBodySupport {
30     private static final XMLOutputFactory XML_FACTORY = XMLOutputFactory.newFactory();
31     private static final String PRETTY_PRINT_INDENT = "  ";
32
33     private FormattableBodySupport() {
34         // Hidden on purpose
35     }
36
37     public static JsonWriter createJsonWriter(final OutputStream out, final PrettyPrintParam prettyPrint) {
38         final var ret = JsonWriterFactory.createJsonWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
39         ret.setIndent(prettyPrint.value() ? PRETTY_PRINT_INDENT : "");
40         return ret;
41     }
42
43     public static XMLStreamWriter createXmlWriter(final OutputStream out, final PrettyPrintParam prettyPrint)
44             throws IOException {
45         final var xmlWriter = createXmlWriter(out);
46         return prettyPrint.value() ? new IndentingXMLStreamWriter(xmlWriter) : xmlWriter;
47     }
48
49     private static XMLStreamWriter createXmlWriter(final OutputStream out) throws IOException {
50         try {
51             return XML_FACTORY.createXMLStreamWriter(out, StandardCharsets.UTF_8.name());
52         } catch (XMLStreamException | FactoryConfigurationError e) {
53             throw new IOException(e);
54         }
55     }
56 }