Split out YangLibraryVersionResource
[netconf.git] / protocol / restconf-api / src / main / java / org / opendaylight / restconf / api / FormattableBody.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.api;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import java.io.IOException;
15 import java.io.OutputStream;
16 import org.eclipse.jdt.annotation.NonNullByDefault;
17 import org.opendaylight.yangtools.concepts.Immutable;
18
19 /**
20  * A body which is capable of being formatted to an {@link OutputStream} in either JSON or XML format.
21  */
22 @NonNullByDefault
23 public abstract class FormattableBody implements Immutable {
24     private final FormatParameters format;
25
26     protected FormattableBody(final FormatParameters format) {
27         this.format = requireNonNull(format);
28     }
29
30     /**
31      * Write the content of this body as a JSON document.
32      *
33      * @param out output stream
34      * @throws IOException if an IO error occurs.
35      */
36     public final void formatToJSON(final OutputStream out) throws IOException {
37         formatToJSON(requireNonNull(out), format);
38     }
39
40     protected abstract void formatToJSON(OutputStream out, FormatParameters format) throws IOException;
41
42     /**
43      * Write the content of this body as an XML document.
44      *
45      * @param out output stream
46      * @throws IOException if an IO error occurs.
47      */
48     public final void formatToXML(final OutputStream out) throws IOException {
49         formatToXML(requireNonNull(out), format);
50     }
51
52     protected abstract void formatToXML(OutputStream out, FormatParameters format) throws IOException;
53
54     @Override
55     public final String toString() {
56         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
57     }
58
59     protected ToStringHelper addToStringAttributes(final ToStringHelper helper) {
60         return helper.add("prettyPrint", format.prettyPrint().value());
61     }
62 }