2 * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.restconf.api;
10 import static java.util.Objects.requireNonNull;
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;
20 * A body which is capable of being formatted to an {@link OutputStream} in either JSON or XML format.
23 public abstract class FormattableBody implements Immutable {
24 private final FormatParameters format;
26 protected FormattableBody(final FormatParameters format) {
27 this.format = requireNonNull(format);
31 * Write the content of this body as a JSON document.
33 * @param out output stream
34 * @throws IOException if an IO error occurs.
36 public final void formatToJSON(final OutputStream out) throws IOException {
37 formatToJSON(requireNonNull(out), format);
40 protected abstract void formatToJSON(OutputStream out, FormatParameters format) throws IOException;
43 * Write the content of this body as an XML document.
45 * @param out output stream
46 * @throws IOException if an IO error occurs.
48 public final void formatToXML(final OutputStream out) throws IOException {
49 formatToXML(requireNonNull(out), format);
52 protected abstract void formatToXML(OutputStream out, FormatParameters format) throws IOException;
55 public final String toString() {
56 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
59 protected ToStringHelper addToStringAttributes(final ToStringHelper helper) {
60 return helper.add("prettyPrint", format.prettyPrint().value());