GeoserveLayersService.java

  1. package gov.usgs.earthquake.geoserve;

  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.net.MalformedURLException;
  5. import java.net.URL;

  6. import javax.json.Json;
  7. import javax.json.JsonObject;

  8. import gov.usgs.util.StreamUtils;

  9. /**
  10.  * Access layers from the Geoserve Layers service.
  11.  */
  12. public class GeoserveLayersService {

  13.     /** Default URL for GeoServe Layers service. */
  14.     public static final String DEFAULT_GEOSERVE_LAYERS_URL = "https://earthquake.usgs.gov/ws/geoserve/layers.json?type={type}";

  15.     /** Configured URL for GeoServe Layers service. */
  16.     private String endpointUrl;


  17.     /**
  18.      * Create a service using the default URL.
  19.      */
  20.     public GeoserveLayersService() {
  21.         this(DEFAULT_GEOSERVE_LAYERS_URL);
  22.     }

  23.     /**
  24.      * Create a service using a custom URL.
  25.      *
  26.      * @param endpointUrl layers service URL.
  27.      *       Should contain the string <code>{type}</code>,
  28.      *       which is replaced during the #{@link #getLayer(String)}.
  29.      */
  30.     public GeoserveLayersService(final String endpointUrl) {
  31.         this.endpointUrl = endpointUrl;
  32.     }

  33.     /**
  34.      * Get the endpoint URL.
  35.      * @return endpoint URL
  36.      */
  37.     public String getEndpointURL() {
  38.         return this.endpointUrl;
  39.     }

  40.     /**
  41.      * Set the endpoint URL.
  42.      * @param url endpoint URL to set
  43.      */
  44.     public void setEndpointURL(final String url) {
  45.         this.endpointUrl = url;
  46.     }

  47.     /**
  48.      * Fetch and parse a JSON response from the Geoserve layers service.
  49.      * @param type type of response to fetch
  50.      * @return JSONObject response
  51.      * @throws IOException on IO error
  52.      * @throws MalformedURLException Error on URL failure
  53.      */
  54.     public JsonObject getLayer(final String type) throws IOException, MalformedURLException {
  55.         final URL url = new URL(endpointUrl.replace("{type}", type));
  56.         try (InputStream in = StreamUtils.getInputStream(url)) {
  57.             JsonObject json = Json.createReader(in).readObject();
  58.             return json.getJsonObject(type);
  59.         }
  60.     }

  61. }