Handler.java

  1. package gov.usgs.util.protocolhandlers.data;

  2. import java.io.IOException;
  3. import java.net.URL;
  4. import java.net.URLConnection;
  5. import java.net.URLStreamHandler;

  6. /**
  7.  * Data URLs handler.
  8.  *
  9.  * "data:[<mediatype>][;base64],<data>"
  10.  */
  11. public class Handler extends URLStreamHandler {

  12.   /** property for protocol handlers */
  13.   public static final String PROTOCOL_HANDLERS_PROPERTY = "java.protocol.handler.pkgs";

  14.   /**
  15.    * Register data protocol handler
  16.    */
  17.   public static void register() {
  18.     final String packageName = Handler.class.getPackage().getName().replace(".data", "");
  19.     final String protocolHandlers = System.getProperty(PROTOCOL_HANDLERS_PROPERTY);
  20.     if (protocolHandlers == null || protocolHandlers.indexOf("gov.usgs.util.protocolhandlers") == -1) {
  21.       System.setProperty(
  22.           PROTOCOL_HANDLERS_PROPERTY,
  23.           protocolHandlers == null ? packageName : protocolHandlers + "|" + packageName);
  24.     }
  25.   }


  26.   @Override
  27.   protected URLConnection openConnection(URL url) throws IOException {
  28.     try {
  29.       return new DataURLConnection(url);
  30.     } catch (Exception e) {
  31.       throw new IOException(e);
  32.     }
  33.   }

  34.   @Override
  35.   protected void parseURL(final URL url, final String spec, final int start, final int end) throws SecurityException {
  36.     int colon = spec.indexOf(":");

  37.     final String protocol = "data";
  38.     final String host = null;
  39.     final int port = 80;
  40.     final String authority = null;
  41.     final String userInfo = null;
  42.     final String path = spec.substring(colon + 1, end);
  43.     final String query = null;
  44.     final String ref = null;

  45.     setURL(url, protocol, host, port, authority, userInfo, path, query, ref);
  46.   }

  47.   @Override
  48.   protected String toExternalForm(final URL url) {
  49.     return url.getProtocol() + ":" + url.getPath();
  50.   }
  51. }