JsonProductSource.java

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

  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;

  7. import javax.json.Json;
  8. import javax.json.JsonReader;

  9. import gov.usgs.util.StreamUtils;

  10. import gov.usgs.earthquake.product.Product;


  11. /**
  12.  * Load a product from an InputStream containing Json.
  13.  */
  14. public class JsonProductSource implements ProductSource {

  15.   /** The input stream where Json is read. */
  16.   private InputStream in;

  17.   /**
  18.    * Create a new JsonProductSource.
  19.    *
  20.    * @param in
  21.    *            the input stream where Json is read.
  22.    */
  23.   public JsonProductSource(final InputStream in) {
  24.     this.in = in;
  25.   }

  26.   /**
  27.    * Begin reading the input stream, sending events to out.
  28.    *
  29.    * @param out
  30.    *            the receiving ProductOutput.
  31.    */
  32.   public synchronized void streamTo(ProductHandler out) throws Exception {
  33.     final Product product;
  34.     try (final JsonReader reader = Json.createReader(new InputStreamReader(in))) {
  35.       product = new JsonProduct().getProduct(reader.readObject());
  36.     }
  37.     final ObjectProductSource source = new ObjectProductSource(product);
  38.     source.streamTo(out);
  39.   }

  40.   /**
  41.    * Free any resources associated with this handler.
  42.    */
  43.   @Override
  44.   public void close() {
  45.     StreamUtils.closeStream(in);
  46.   }

  47. }