JsonNotification.java

  1. package gov.usgs.earthquake.aws;

  2. import java.net.MalformedURLException;
  3. import java.net.URL;
  4. import java.nio.charset.StandardCharsets;
  5. import java.time.Instant;
  6. import java.util.Base64;
  7. import java.util.Date;

  8. import javax.json.JsonObject;

  9. import gov.usgs.earthquake.distribution.URLNotification;
  10. import gov.usgs.earthquake.product.Product;
  11. import gov.usgs.earthquake.product.io.JsonProduct;
  12. import gov.usgs.util.protocolhandlers.data.Handler;

  13. /**
  14.  * Json formatted notification.
  15.  *
  16.  * Stores stores product content in URLNotification as a data URL.
  17.  */
  18. public class JsonNotification extends URLNotification {

  19.   /** Empty URL for product tracker. */
  20.   public static final URL EMPTY_URL;
  21.   static {
  22.     try {
  23.       // make sure data protocol handler is registered
  24.       Handler.register();
  25.       EMPTY_URL = new URL("data:,");
  26.     } catch (MalformedURLException mue) {
  27.       throw new RuntimeException("failed to parse empty url");
  28.     }
  29.   }

  30.   /** When notification was created. */
  31.   public final Instant created;
  32.   /** Product attached to notification. */
  33.   public final Product product;

  34.   /**
  35.    * Parse a Json formatted Notification.
  36.    *
  37.    * @param json
  38.    * @throws Exception
  39.    */
  40.   JsonNotification(final JsonObject json) throws Exception {
  41.     this(
  42.         Instant.parse(json.getString("created")),
  43.         new JsonProduct().getProduct(json.getJsonObject("product")));
  44.   }

  45.   /**
  46.    * Create a JsonNotification from an existing Product.
  47.    */
  48.   JsonNotification(final Instant created, final Product product) throws Exception {
  49.     this(created, product, new Date(Instant.now().plusSeconds(7 * 86400).toEpochMilli()));
  50.   }

  51.   /**
  52.    * Create a JsonNotification with an expiration date.
  53.    */
  54.   JsonNotification(final Instant created, final Product product, final Date expiration)
  55.       throws Exception {
  56.     super(
  57.         product.getId(),
  58.         // expiration date
  59.         expiration,
  60.         // no tracker
  61.         EMPTY_URL,
  62.         // store product as data url
  63.         new URL("data:;base64," +
  64.             new String(Base64.getEncoder().encode(
  65.                 new JsonProduct().getJsonObject((product))
  66.                     .toString().getBytes(StandardCharsets.UTF_8)))));
  67.     this.created = created;
  68.     this.product = product;
  69.   }

  70. }