JsonDirectoryProductHandler.java
/*
* JsonDirectoryProductHandler
*/
package gov.usgs.earthquake.product.io;
import gov.usgs.earthquake.product.Content;
import gov.usgs.earthquake.product.FileContent;
import gov.usgs.earthquake.product.ProductId;
import gov.usgs.earthquake.product.URLContent;
import gov.usgs.util.StreamUtils;
import java.io.File;
import java.io.OutputStream;
/**
* Store a product to a Directory.
*
* Product attributes are stored to a file named "product.json". All
* ProductOutput methods are passed to an ObjectProductOutput object, except
* files with non-empty paths. Files are stored in the directory, and all other
* product attributes are stored using the product json format to a file name
* "product.json".
*/
public class JsonDirectoryProductHandler extends DirectoryProductHandler {
/** The file where product attributes are stored. */
public static final String PRODUCT_JSON_FILENAME = "product.json";
/** Directory where product contents are stored. */
private File directory;
/**
* Construct a new DirectoryProductHandler object.
*
* @param directory where product contents will be stored.
*/
public JsonDirectoryProductHandler(final File directory) {
super(directory);
}
/**
* Store all except product contents to product.json.
*/
public void onEndProduct(ProductId id) throws Exception {
super.onEndProduct(id);
// save reference to stream, so it can be forced close.
OutputStream out = null;
ProductSource source = null;
ProductHandler handler = null;
try {
out = StreamUtils.getOutputStream(new File(directory, PRODUCT_JSON_FILENAME));
// save product attributes as json
source = new ObjectProductSource(getProduct());
handler = new JsonProductHandler(out);
source.streamTo(handler);
} finally {
// close stream
StreamUtils.closeStream(out);
if (source != null) {
source.close();
}
if (handler != null) {
handler.close();
}
}
}
}