001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io.protocols.data;
003
004import java.io.IOException;
005import java.net.URL;
006import java.net.URLConnection;
007import java.net.URLStreamHandler;
008import java.util.Optional;
009
010import org.openstreetmap.josm.tools.Utils;
011
012/**
013 * Protocol handler for {@code data:} URLs.
014 * This class must be named "Handler" and in a package "data" (fixed named convention)!
015 * <p>
016 * See <a href="http://stackoverflow.com/a/9388757/2257172">StackOverflow</a>.
017 * @since 10931
018 */
019public class Handler extends URLStreamHandler {
020
021    @Override
022    protected URLConnection openConnection(URL u) throws IOException {
023        return new DataConnection(u);
024    }
025
026    /**
027     * Installs protocol handler.
028     */
029    public static void install() {
030        String pkgName = Handler.class.getPackage().getName();
031        String pkg = pkgName.substring(0, pkgName.lastIndexOf('.'));
032
033        String protocolHandlers = Utils.getSystemProperty("java.protocol.handler.pkgs");
034        if (protocolHandlers == null || !protocolHandlers.contains(pkg)) {
035            StringBuilder sb = new StringBuilder(Optional.ofNullable(protocolHandlers).orElse(""));
036            if (sb.length() > 0) {
037                sb.append('|');
038            }
039            sb.append(pkg);
040            Utils.updateSystemProperty("java.protocol.handler.pkgs", sb.toString());
041        }
042    }
043}