001package com.streamconverter.util;
002
003import java.io.IOException;
004import java.io.OutputStream;
005
006/**
007 * 出力ストリームのデータサイズを測定するラッパークラス
008 *
009 * <p>このクラスは、OutputStreamをラップして書き込んだバイト数を自動的に計測します。 自動ログ出力機能でパフォーマンス測定に使用されます。
010 */
011public class MeasuredOutputStream extends OutputStream {
012  private final OutputStream delegate;
013  private long bytesWritten;
014  private boolean closed;
015
016  /**
017   * コンストラクタ
018   *
019   * @param delegateStream ラップ対象のOutputStream
020   */
021  public MeasuredOutputStream(final OutputStream delegateStream) {
022    super();
023    this.delegate =
024        java.util.Objects.requireNonNull(delegateStream, "delegate OutputStream cannot be null");
025  }
026
027  @Override
028  public void write(final int value) throws IOException {
029    if (closed) {
030      throw new IOException("Stream is closed");
031    }
032
033    delegate.write(value);
034    bytesWritten++;
035  }
036
037  @Override
038  public void write(final byte[] buffer) throws IOException {
039    if (closed) {
040      throw new IOException("Stream is closed");
041    }
042
043    delegate.write(buffer);
044    bytesWritten += buffer.length;
045  }
046
047  @Override
048  public void write(final byte[] buffer, final int offset, final int length) throws IOException {
049    if (closed) {
050      throw new IOException("Stream is closed");
051    }
052
053    delegate.write(buffer, offset, length);
054    bytesWritten += length;
055  }
056
057  @Override
058  public void flush() throws IOException {
059    if (!closed) {
060      delegate.flush();
061    }
062  }
063
064  @Override
065  public void close() throws IOException {
066    if (!closed) {
067      closed = true;
068      delegate.close();
069    }
070  }
071
072  /**
073   * 現在までに書き込んだバイト数を取得
074   *
075   * @return 書き込んだバイト数
076   */
077  public long getBytesWritten() {
078    return bytesWritten;
079  }
080
081  /**
082   * ストリームがクローズされているかどうかを確認
083   *
084   * @return クローズされている場合true
085   */
086  public boolean isClosed() {
087    return closed;
088  }
089}