001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io.protocols.data;
003
004import java.io.ByteArrayInputStream;
005import java.io.IOException;
006import java.io.InputStream;
007import java.net.URL;
008import java.net.URLConnection;
009import java.util.Base64;
010
011import org.openstreetmap.josm.tools.bugreport.BugReport;
012
013/**
014 * Connection for "data:" protocol allowing to read inlined base64 images.
015 * <p>
016 * See <a href="http://stackoverflow.com/a/9388757/2257172">StackOverflow</a>.
017 * @since 10931
018 */
019public class DataConnection extends URLConnection {
020
021    /**
022     * Constructs a new {@code DataConnection}.
023     * @param u data url
024     */
025    public DataConnection(URL u) {
026        super(u);
027    }
028
029    @Override
030    public void connect() throws IOException {
031        connected = true;
032    }
033
034    @Override
035    public InputStream getInputStream() throws IOException {
036        try {
037            return new ByteArrayInputStream(Base64.getDecoder().decode(url.toString().replaceFirst("^.*;base64,", "")));
038        } catch (IllegalArgumentException e) {
039            throw BugReport.intercept(e).put("url", url);
040        }
041    }
042}