001package io.avaje.json.stream;
002
003import java.io.Closeable;
004import java.io.IOException;
005import java.io.OutputStream;
006
007/**
008 * Output that can be aware of server content chunking.
009 * <p>
010 * We can use an implementation of JsonOutput such that it can make use of
011 * the underlying buffer used by avaje-jsonb, using {@link #writeLast(byte[], int, int)}
012 * to know if the content is complete (and typically can be written directly as fixed
013 * content) or if the content is still being written (and potentially written by an
014 * http server as chunked content).
015 * <p>
016 * Typically, for HTTP servers that can send output using fixed length or chunked.
017 */
018public interface JsonOutput extends Closeable {
019
020  /**
021   * Create as a simple wrapper for OutputStream.
022   */
023  static JsonOutput ofStream(OutputStream outputStream) {
024    return new DJsonOutput(outputStream);
025  }
026
027  /**
028   * @deprecated migrate to {@link #ofStream(OutputStream)}.
029   */
030  @Deprecated
031  static JsonOutput of(OutputStream outputStream) {
032    return new DJsonOutput(outputStream);
033  }
034
035  /**
036   * Write the content to the underlying output stream.
037   */
038  void write(byte[] content, int offset, int length) throws IOException;
039
040  /**
041   * Write the last content to the underlying output stream.
042   * <p>
043   * Given that this is known to be the last content written an implementation can make
044   * use of this to optimise for sending as fixed length content.
045   */
046  default void writeLast(byte[] content, int offset, int length) throws IOException {
047    write(content, offset, length);
048  }
049
050  /**
051   * Flush the underlying OutputStream.
052   */
053  void flush() throws IOException;
054
055  /**
056   * Return the underlying OutputStream.
057   * <p>
058   * This is used for Jsonb adapters (Jackson) that can't support writeLast() semantics.
059   */
060  OutputStream unwrapOutputStream();
061}