DataURLConnection.java

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

  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.URL;
  6. import java.net.URLConnection;
  7. import java.util.Base64;

  8. /**
  9.  * URLConnection for data protocol URLs.
  10.  */
  11. public class DataURLConnection extends URLConnection {

  12.   private byte[] data;
  13.   private String type;

  14.   /**
  15.    * @param url URL
  16.    * @throws Exception if error occurs
  17.    */
  18.   public DataURLConnection(final URL url) throws Exception {
  19.     super(url);

  20.     // "data:[<mediatype>][;base64],<data>"
  21.     // path is everything after "data:"
  22.     final String path = url.getPath();
  23.     final int base64 = path.indexOf(";base64");
  24.     final int comma = path.indexOf(",");

  25.     type = path.substring(0, base64 >= 0 ? base64 : comma);
  26.     if ("".equals(type)) {
  27.       type = null;
  28.     }
  29.     data = path.substring(comma + 1).getBytes("UTF8");
  30.     if (base64 >= 0) {
  31.       data = Base64.getDecoder().decode(data);
  32.     }
  33.   }

  34.   @Override
  35.   public int getContentLength() {
  36.     return data.length;
  37.   }

  38.   @Override
  39.   public String getContentType() {
  40.     return type;
  41.   }

  42.   @Override
  43.   public void connect() throws IOException {
  44.     // no connection needed
  45.   }

  46.   @Override
  47.   public InputStream getInputStream() throws IOException {
  48.     return new ByteArrayInputStream(data);
  49.   }

  50. }