JsonProduct.java

  1. package gov.usgs.earthquake.product.io;

  2. import gov.usgs.earthquake.product.AbstractContent;
  3. import gov.usgs.earthquake.product.Content;
  4. import gov.usgs.earthquake.product.Product;
  5. import gov.usgs.earthquake.product.ProductId;
  6. import gov.usgs.earthquake.product.URLContent;
  7. import gov.usgs.util.CryptoUtils.Version;
  8. import gov.usgs.util.protocolhandlers.data.Handler;
  9. import gov.usgs.util.StreamUtils;
  10. import gov.usgs.util.XmlUtils;

  11. import java.math.BigDecimal;
  12. import java.net.URI;
  13. import java.net.URL;
  14. import java.util.ArrayList;
  15. import java.util.Base64;
  16. import java.util.Date;
  17. import java.util.HashMap;
  18. import java.util.List;
  19. import java.util.Map;
  20. import javax.json.Json;
  21. import javax.json.JsonArray;
  22. import javax.json.JsonArrayBuilder;
  23. import javax.json.JsonObject;
  24. import javax.json.JsonObjectBuilder;
  25. import javax.json.JsonValue;

  26. public class JsonProduct {

  27.   static {
  28.     // make sure data protocol handler registered
  29.     Handler.register();
  30.   }

  31.   /**
  32.    * Convert product object to json.
  33.    *
  34.    * @param product a product
  35.    * @return a json object
  36.    * @throws Exception if error occurs
  37.    */
  38.   public JsonObject getJsonObject(final Product product) throws Exception {
  39.     JsonObjectBuilder json = Json.createObjectBuilder();

  40.     json.add("contents", getContentsJson(product.getContents()));
  41.     JsonObjectBuilder geometry = getGeometryJson(product);
  42.     if (geometry == null) {
  43.       json.addNull("geometry");
  44.     } else {
  45.       json.add("geometry", geometry);
  46.     }
  47.     final ProductId id = product.getId();
  48.     json.add("id", getIdJson(id));
  49.     json.add("links", getLinksJson(product.getLinks()));
  50.     json.add("properties", getPropertiesJson(product.getProperties()));
  51.     if (product.getSignature() == null) {
  52.       json.addNull("signature");
  53.     } else {
  54.       json.add("signature", product.getSignature());
  55.     }
  56.     json.add("signatureVersion", product.getSignatureVersion().toString());
  57.     json.add("status", product.getStatus());
  58.     json.add("type", "Feature");
  59.     return json.build();
  60.   }

  61.   /**
  62.    * Convert json object to product.
  63.    * @param json a json object
  64.    * @return a product
  65.    * @throws Exception if error occurs
  66.    */
  67.   public Product getProduct(final JsonObject json) throws Exception {
  68.     Product product = new Product(getId(json.getJsonObject("id")));
  69.     product.setContents(getContents(json.getJsonArray("contents")));
  70.     product.setLinks(getLinks(json.getJsonArray("links")));
  71.     product.setProperties(getProperties(json.getJsonObject("properties")));
  72.     product.setStatus(json.getString("status"));
  73.     try {
  74.       product.setSignature(json.getString("signature"));
  75.     } catch (Exception e) {
  76.       product.setSignature(null);
  77.     }
  78.     product.setSignatureVersion(Version.fromString(json.getString("signatureVersion")));
  79.     product.setTrackerURL(new URL("data:,"));
  80.     return product;
  81.   }

  82.   /**
  83.    * Convert contents map to json.
  84.    *
  85.    * @param contents contents map
  86.    * @return JSOnArrayBuilder
  87.    * @throws Exception if error occurs
  88.    */
  89.   public JsonArrayBuilder getContentsJson(final Map<String, Content> contents) throws Exception {
  90.     final JsonArrayBuilder builder = Json.createArrayBuilder();
  91.     for (final String path : contents.keySet()) {
  92.       final Content content = contents.get(path);
  93.       final JsonObjectBuilder jsonContent =
  94.           Json.createObjectBuilder()
  95.               .add("length", content.getLength())
  96.               .add("modified", XmlUtils.formatDate(content.getLastModified()))
  97.               .add("path", path)
  98.               .add("sha256", content.getSha256())
  99.               .add("type", content.getContentType());
  100.       if (content instanceof URLContent) {
  101.         jsonContent.add("url", ((URLContent) content).getURL().toString());
  102.       } else if ("".equals(path)) {
  103.         jsonContent.add(
  104.             "url",
  105.             "data:"
  106.                 + content.getContentType()
  107.                 + ";base64,"
  108.                 + Base64.getEncoder()
  109.                     .encodeToString(StreamUtils.readStream(content.getInputStream())));
  110.       } else {
  111.         // no url, will throw parse error
  112.         // this is used to get upload urls, and returned object includes urls...
  113.         jsonContent.addNull("url");
  114.       }
  115.       builder.add(jsonContent);
  116.     }
  117.     return builder;
  118.   }

  119.   /**
  120.    * Convert contents json to map.
  121.    *
  122.    * @param json JsonArray
  123.    * @return Contents map
  124.    * @throws Exception if error occurs
  125.    */
  126.   public Map<String, Content> getContents(final JsonArray json) throws Exception {
  127.     Map<String, Content> contents = new HashMap<String, Content>();
  128.     for (JsonValue value : json) {
  129.       JsonObject object = value.asJsonObject();
  130.       Long length = object.getJsonNumber("length").longValue();
  131.       Date modified = XmlUtils.getDate(object.getString("modified"));
  132.       String path = object.getString("path");
  133.       String sha256 = object.getString("sha256");
  134.       String type = object.getString("type");
  135.       String url = object.getString("url");

  136.       AbstractContent content = new URLContent(new URL(url));
  137.       content.setContentType(type);
  138.       content.setLastModified(modified);
  139.       content.setLength(length);
  140.       content.setSha256(sha256);
  141.       contents.put(path, content);
  142.     }
  143.     return contents;
  144.   }

  145.   /**
  146.    * Create json geometry from product properties.
  147.    *
  148.    * @param product a product
  149.    * @return JSON geometry via JsonObjectBuilder
  150.    * @throws Exception if error occurs
  151.    */
  152.   public JsonObjectBuilder getGeometryJson(final Product product) throws Exception {
  153.     final BigDecimal latitude = product.getLatitude();
  154.     final BigDecimal longitude = product.getLongitude();
  155.     final BigDecimal depth = product.getDepth();
  156.     if (latitude != null || longitude != null || depth != null) {
  157.       final JsonArrayBuilder coordinates = Json.createArrayBuilder();
  158.       if (latitude != null) {
  159.         coordinates.add(latitude);
  160.       } else {
  161.         coordinates.addNull();
  162.       }
  163.       if (longitude != null) {
  164.         coordinates.add(longitude);
  165.       } else {
  166.         coordinates.addNull();
  167.       }
  168.       if (depth != null) {
  169.         coordinates.add(depth);
  170.       } else {
  171.         coordinates.addNull();
  172.       }
  173.       return Json.createObjectBuilder()
  174.           .add("type", "Point")
  175.           .add("coordinates", coordinates);
  176.     }
  177.     return null;
  178.   }

  179.   /**
  180.    * Convert json id to ProductId object.
  181.    *
  182.    * @param json A JsonObject ID
  183.    * @return a productId
  184.    * @throws Exception if error occurs
  185.    */
  186.   public ProductId getId(final JsonObject json) throws Exception {
  187.     final String code = json.getString("code");
  188.     final String source = json.getString("source");
  189.     final String type = json.getString("type");
  190.     final Date updateTime = XmlUtils.getDate(json.getString("updateTime"));
  191.     return new ProductId(source, type, code, updateTime);
  192.   }

  193.   /**
  194.    * Convert ProductId to json object.
  195.    * @param id A ProductId
  196.    * @return JsonObjectBuilder
  197.    * @throws Exception if error occurs
  198.    */
  199.   public JsonObjectBuilder getIdJson(final ProductId id) throws Exception {
  200.     return Json.createObjectBuilder()
  201.         .add("code", id.getCode())
  202.         .add("source", id.getSource())
  203.         .add("type", id.getType())
  204.         .add("updateTime", XmlUtils.formatDate(id.getUpdateTime()));
  205.   }

  206.   /**
  207.    * Convert json links to map.
  208.    * @param json a Jsonarray
  209.    * @return a Map of links
  210.    * @throws Exception if error occurs
  211.    */
  212.   public Map<String, List<URI>> getLinks(final JsonArray json) throws Exception {
  213.     final Map<String, List<URI>> links = new HashMap<String, List<URI>>();
  214.     for (final JsonValue value : json) {
  215.       final JsonObject link = value.asJsonObject();
  216.       final String relation = link.getString("relation");
  217.       final URI uri = new URI(link.getString("uri"));
  218.       List<URI> relationLinks = links.get(relation);
  219.       if (relationLinks == null) {
  220.         relationLinks = new ArrayList<URI>();
  221.         links.put(relation, relationLinks);
  222.       }
  223.       relationLinks.add(uri);
  224.     }
  225.     return links;
  226.   }

  227.   /**
  228.    * Convert links map to json.
  229.    *
  230.    * @param links map
  231.    * @return JsonArray of JsonArrayBuilder
  232.    * @throws Exception if error occurs
  233.    */
  234.   public JsonArrayBuilder getLinksJson(final Map<String, List<URI>> links) throws Exception {
  235.     final JsonArrayBuilder builder = Json.createArrayBuilder();
  236.     for (final String relation : links.keySet()) {
  237.       final List<URI> relationLinks = links.get(relation);
  238.       for (final URI uri : relationLinks) {
  239.         builder.add(
  240.             Json.createObjectBuilder().add("relation", relation).add("uri", uri.toString()));
  241.       }
  242.     }
  243.     return builder;
  244.   }

  245.   /**
  246.    * Convert properties json to map.
  247.    * @param json JsonObject properties
  248.    * @return A map
  249.    * @throws Exception if error occurs
  250.    */
  251.   public Map<String, String> getProperties(final JsonObject json) throws Exception {
  252.     final Map<String, String> properties = new HashMap<String, String>();
  253.     for (final String name : json.keySet()) {
  254.       properties.put(name, json.getString(name));
  255.     }
  256.     return properties;
  257.   }

  258.   /**
  259.    * Convert properties map to json.
  260.    *
  261.    * @param properties Map of properties
  262.    * @return JsonObjectBuilder
  263.    * @throws Exception if error occurs
  264.    */
  265.   public JsonObjectBuilder getPropertiesJson(final Map<String, String> properties)
  266.       throws Exception {
  267.     final JsonObjectBuilder builder = Json.createObjectBuilder();
  268.     for (final String name : properties.keySet()) {
  269.       builder.add(name, properties.get(name));
  270.     }
  271.     return builder;
  272.   }
  273. }