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.   /** Directory where product contents are stored. */
  25.   private File directory;

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

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

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

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

  60. }