ByteContent.java

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

  5. import gov.usgs.util.StreamUtils;

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

  9. /**
  10.  * Content stored in a byte array.
  11.  */
  12. public class ByteContent extends AbstractContent {

  13.     /** The actual content. */
  14.     private final byte[] content;

  15.     /**
  16.      * Default constructor accepts a byte array.
  17.      *
  18.      * @param content
  19.      *            the actual content. This should not be null.
  20.      */
  21.     public ByteContent(final byte[] content) {
  22.         this.content = content;
  23.         setLength(Long.valueOf(content.length));
  24.     }

  25.     /**
  26.      * Convert any Content into ByteContent.
  27.      *
  28.      * Any content is read from the InputStream into a new underlying byte
  29.      * array.
  30.      *
  31.      * @param content
  32.      *            existing content to read.
  33.      * @throws IOException
  34.      *             when errors occur reading content.
  35.      */
  36.     public ByteContent(final Content content) throws IOException {
  37.         super(content);
  38.         this.content = StreamUtils.readStream(content.getInputStream());
  39.         setLength(Long.valueOf(this.content.length));
  40.     }

  41.     /**
  42.      * @return a ByteArrayInputStream for the wrapped content.
  43.      */
  44.     public InputStream getInputStream() throws IOException {
  45.         return new ByteArrayInputStream(content);
  46.     }

  47.     /**
  48.      * @return the wrapped byte array.
  49.      */
  50.     public byte[] getByteArray() {
  51.         return content;
  52.     }

  53.     /**
  54.      * Free any resources associated with this content.
  55.      */
  56.     public void close() {
  57.         // nothing to free
  58.     }
  59. }