Use more modern QNameModule methods in restconf-nb
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / transactions / YinCharSource.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.rests.transactions;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.io.CharSource;
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15 import java.io.OutputStream;
16 import java.io.Reader;
17 import java.io.StringReader;
18 import java.nio.charset.StandardCharsets;
19 import javax.xml.stream.XMLStreamException;
20 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
21 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
22 import org.opendaylight.yangtools.yang.model.export.YinExportUtils;
23
24 abstract sealed class YinCharSource extends CharSource {
25     static final class OfModule extends YinCharSource {
26         private final ModuleEffectiveStatement module;
27
28         OfModule(final ModuleEffectiveStatement module) {
29             this.module = requireNonNull(module);
30         }
31
32         @Override
33         void writeTo(final OutputStream out) throws XMLStreamException {
34             YinExportUtils.writeModuleAsYinText(module, out);
35         }
36     }
37
38     static final class OfSubmodule extends YinCharSource {
39         private final ModuleEffectiveStatement module;
40         private final SubmoduleEffectiveStatement submodule;
41
42         OfSubmodule(final ModuleEffectiveStatement module, final SubmoduleEffectiveStatement submodule) {
43             this.module = requireNonNull(module);
44             this.submodule = requireNonNull(submodule);
45         }
46
47         @Override
48         void writeTo(final OutputStream out) throws XMLStreamException {
49             YinExportUtils.writeSubmoduleAsYinText(module, submodule, out);
50         }
51     }
52
53     @Override
54     public final Reader openStream() throws IOException {
55         final var bos = new ByteArrayOutputStream();
56         try {
57             writeTo(bos);
58         } catch (XMLStreamException e) {
59             throw new IOException("Failed to export source", e);
60         }
61         return new StringReader(new String(bos.toByteArray(), StandardCharsets.UTF_8));
62     }
63
64     abstract void writeTo(OutputStream out) throws XMLStreamException;
65 }