InputStreamContent.java

  1. /*
  2.  * InputStreamContent
  3.  */
  4. package gov.usgs.earthquake.product;

  5. import java.io.ByteArrayInputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;

  8. import gov.usgs.util.StreamUtils;

  9. /**
  10.  * Content within an InputStream.
  11.  */
  12. public class InputStreamContent extends AbstractContent {

  13.     /** The actual content. */
  14.     private InputStream content;

  15.     /**
  16.      * Create a new InputStream content.
  17.      *
  18.      * @param content
  19.      *            the content.
  20.      */
  21.     public InputStreamContent(final InputStream content) {
  22.         this.content = content;
  23.     }

  24.     /**
  25.      * Create an InputStreamContent from another Content.
  26.      *
  27.      * @param content
  28.      *            the content to duplicate.
  29.      * @throws IOException
  30.      *            if IO error occurs
  31.      */
  32.     public InputStreamContent(final Content content) throws IOException {
  33.         super(content);
  34.         this.content = content.getInputStream();
  35.     }

  36.     /**
  37.      * @return InputStream to content.
  38.      */
  39.     public InputStream getInputStream() throws IOException {
  40.         return content;
  41.     }

  42.     /**
  43.      * InputStream can only be read once.
  44.      *
  45.      * <p>If sha256 is null, read and convert to in memory stream.
  46.      */
  47.     public String getSha256() throws Exception {
  48.         String sha256 = super.getSha256(false);
  49.         if (sha256 == null) {
  50.             // convert stream into byte array to read multiple times
  51.             final byte[] contentBytes;
  52.             try (final InputStream in = getInputStream()) {
  53.                 contentBytes = StreamUtils.readStream(in);
  54.             }
  55.             // generate sha256 from byte stream
  56.             this.content = new ByteArrayInputStream(contentBytes);
  57.             sha256 = super.getSha256();
  58.             // set byte stream for next reader
  59.             this.content = new ByteArrayInputStream(contentBytes);
  60.         }
  61.         return sha256;
  62.     }

  63.     /**
  64.      * Free any resources associated with this content.
  65.      */
  66.     public void close() {
  67.         StreamUtils.closeStream(content);
  68.         content = null;
  69.     }
  70. }