001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package sop;
006
007import java.io.ByteArrayOutputStream;
008import java.io.IOException;
009import java.io.OutputStream;
010
011import sop.exception.SOPGPException;
012
013public abstract class ReadyWithResult<T> {
014
015    /**
016     * Write the data e.g. decrypted plaintext to the provided output stream and return the result of the
017     * processing operation.
018     *
019     * @param outputStream output stream
020     * @return result, eg. signatures
021     *
022     * @throws IOException in case of an IO error
023     * @throws SOPGPException.NoSignature if there are no valid signatures found
024     */
025    public abstract T writeTo(OutputStream outputStream) throws IOException, SOPGPException.NoSignature;
026
027    /**
028     * Return the data as a {@link ByteArrayAndResult}.
029     * Calling {@link ByteArrayAndResult#getBytes()} will give you access to the data as byte array, while
030     * {@link ByteArrayAndResult#getResult()} will grant access to the appended result.
031     *
032     * @return byte array and result
033     * @throws IOException in case of an IO error
034     * @throws SOPGPException.NoSignature if there are no valid signatures found
035     */
036    public ByteArrayAndResult<T> toByteArrayAndResult() throws IOException, SOPGPException.NoSignature {
037        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
038        T result = writeTo(bytes);
039        return new ByteArrayAndResult<>(bytes.toByteArray(), result);
040    }
041}