001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package sop;
006
007import java.io.ByteArrayInputStream;
008import java.io.ByteArrayOutputStream;
009import java.io.IOException;
010import java.io.InputStream;
011import java.io.OutputStream;
012
013public abstract class Ready {
014
015    /**
016     * Write the data to the provided output stream.
017     *
018     * @param outputStream output stream
019     * @throws IOException in case of an IO error
020     */
021    public abstract void writeTo(OutputStream outputStream) throws IOException;
022
023    /**
024     * Return the data as a byte array by writing it to a {@link ByteArrayOutputStream} first and then returning
025     * the array.
026     *
027     * @return data as byte array
028     * @throws IOException in case of an IO error
029     */
030    public byte[] getBytes() throws IOException {
031        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
032        writeTo(bytes);
033        return bytes.toByteArray();
034    }
035
036    /**
037     * Return an input stream containing the data.
038     *
039     * @return input stream
040     * @throws IOException in case of an IO error
041     */
042    public InputStream getInputStream() throws IOException {
043        return new ByteArrayInputStream(getBytes());
044    }
045}