DirectoryProductHandler.java

  1. /*
  2.  * DirectoryProductHandler
  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.xml". 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 xml format to a file name
  19.  * "product.xml".
  20.  */
  21. public class DirectoryProductHandler extends ObjectProductHandler {

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

  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 DirectoryProductHandler(final File directory) {
  32.     this.directory = directory;
  33.   }

  34.   /**
  35.    * Extract content when path isn't empty.
  36.    */
  37.   public void onContent(ProductId id, String path, Content content) throws Exception {
  38.     if ("".equals(path)) {
  39.       super.onContent(id, path, content);
  40.     } else {
  41.       // FileContent copy constructor extracts content
  42.       FileContent fc = new FileContent(content, new File(directory, path));
  43.       super.onContent(id, path, new URLContent(fc));
  44.       fc = null;
  45.     }
  46.   }

  47.   /**
  48.    * Store all except product contents to product.xml.
  49.    */
  50.   public void onEndProduct(ProductId id) throws Exception {
  51.     super.onEndProduct(id);

  52.     // save reference to stream, so it can be forced close.
  53.     OutputStream out = null;
  54.     ProductSource source = null;
  55.     ProductHandler handler = null;
  56.     try {
  57.       out = StreamUtils.getOutputStream(new File(directory, PRODUCT_XML_FILENAME));

  58.       // save product attributes as xml
  59.       source = new ObjectProductSource(getProduct());
  60.       handler = new XmlProductHandler(out);
  61.       source.streamTo(handler);
  62.     } finally {
  63.       // close stream
  64.       StreamUtils.closeStream(out);
  65.       if (source != null) {
  66.         source.close();
  67.       }
  68.       if (handler != null) {
  69.         handler.close();
  70.       }
  71.     }
  72.   }

  73. }