JsonDirectoryProductHandler.java

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

  5. import gov.usgs.earthquake.product.Content;
  6. import gov.usgs.earthquake.product.FileContent;
  7. import gov.usgs.earthquake.product.ProductId;
  8. import gov.usgs.earthquake.product.URLContent;
  9. import gov.usgs.util.StreamUtils;

  10. import java.io.File;
  11. import java.io.OutputStream;

  12. /**
  13.  * Store a product to a Directory.
  14.  *
  15.  * Product attributes are stored to a file named "product.json". All
  16.  * ProductOutput methods are passed to an ObjectProductOutput object, except
  17.  * files with non-empty paths. Files are stored in the directory, and all other
  18.  * product attributes are stored using the product json format to a file name
  19.  * "product.json".
  20.  */
  21. public class JsonDirectoryProductHandler extends DirectoryProductHandler {

  22.   /** The file where product attributes are stored. */
  23.   public static final String PRODUCT_JSON_FILENAME = "product.json";

  24.   /**
  25.    * Construct a new DirectoryProductHandler object.
  26.    *
  27.    * @param directory where product contents will be stored.
  28.    */
  29.   public JsonDirectoryProductHandler(final File directory) {
  30.     super(directory);

  31.   }

  32.   /**
  33.    * Store all except product contents to product.json.
  34.    */
  35.   public void onEndProduct(ProductId id) throws Exception {
  36.     super.onEndProduct(id);

  37.     // save reference to stream, so it can be forced close.
  38.     OutputStream out = null;
  39.     ProductSource source = null;
  40.     ProductHandler handler = null;
  41.     try {
  42.       out = StreamUtils.getOutputStream(new File(directory, PRODUCT_JSON_FILENAME));

  43.       // save product attributes as json
  44.       source = new ObjectProductSource(getProduct());
  45.       handler = new JsonProductHandler(out);
  46.       source.streamTo(handler);
  47.     } finally {
  48.       // close stream
  49.       StreamUtils.closeStream(out);
  50.       if (source != null) {
  51.         source.close();
  52.       }
  53.       if (handler != null) {
  54.         handler.close();
  55.       }
  56.     }
  57.   }

  58. }