Example usage for java.net URLConnection getURL

List of usage examples for java.net URLConnection getURL

Introduction

In this page you can find the example usage for java.net URLConnection getURL.

Prototype

public URL getURL() 

Source Link

Document

Returns the value of this URLConnection 's URL field.

Usage

From source file:hudson.cli.CLI.java

/**
 * If the server advertises CLI endpoint, returns its location.
 * @deprecated Specific to {@link Mode#REMOTING}.
 *///from w  w  w .j  ava  2  s . com
@Deprecated
protected CliPort getCliTcpPort(URL url) throws IOException {
    if (url.getHost() == null || url.getHost().length() == 0) {
        throw new IOException("Invalid URL: " + url);
    }
    URLConnection head = url.openConnection();
    try {
        head.connect();
    } catch (IOException e) {
        throw (IOException) new IOException("Failed to connect to " + url).initCause(e);
    }

    String h = head.getHeaderField("X-Jenkins-CLI-Host");
    if (h == null)
        h = head.getURL().getHost();
    String p1 = head.getHeaderField("X-Jenkins-CLI-Port");
    if (p1 == null)
        p1 = head.getHeaderField("X-Hudson-CLI-Port"); // backward compatibility
    String p2 = head.getHeaderField("X-Jenkins-CLI2-Port");

    String identity = head.getHeaderField("X-Instance-Identity");

    flushURLConnection(head);
    if (p1 == null && p2 == null) {
        verifyJenkinsConnection(head);

        throw new IOException("No X-Jenkins-CLI2-Port among " + head.getHeaderFields().keySet());
    }

    if (p2 != null)
        return new CliPort(new InetSocketAddress(h, Integer.parseInt(p2)), identity, 2);
    else
        return new CliPort(new InetSocketAddress(h, Integer.parseInt(p1)), identity, 1);
}

From source file:com.github.wolf480pl.mias4j.util.AbstractTransformingClassLoader.java

protected CodeSource getCodeSourceAndDefinePackage(URLConnection resourceConn, String resourceName,
        String className) {//from  www.jav  a  2 s . c o  m
    URL codeSourceURL = null;
    CodeSigner[] signers = null;
    Manifest man = null;

    if (resourceConn instanceof JarURLConnection) {
        codeSourceURL = ((JarURLConnection) resourceConn).getJarFileURL();
        try {
            man = ((JarURLConnection) resourceConn).getManifest();
        } catch (IOException e) {
            LOG.warn("Couldn't get jar manifest", e);
        }
        try {
            signers = ((JarURLConnection) resourceConn).getJarEntry().getCodeSigners();
        } catch (IOException e) {
            LOG.warn("Couldn't get jar signers", e);
        }
    }

    boolean guessedCodeSource = false;
    if (codeSourceURL == null) {
        codeSourceURL = guessCodeSourceURL(resourceName, resourceConn.getURL());
        guessedCodeSource = true;
    }
    CodeSource cs = new CodeSource(codeSourceURL, signers);

    // If we guess wrong code source URL, we don't want to accidentally seal a package with that URL.
    definePackageIfNotExists(className, man, guessedCodeSource ? null : codeSourceURL);

    // TODO: Do we really want to assign codesource permissions and protection domain based on a guessed CodeSource?
    return cs;
}

From source file:InstallJars.java

public void installZip(URLConnection conn, String target, boolean doExpand, boolean doRun) throws IOException {
    // doRun not used on htis type
    if (doExpand) {
        String ctype = conn.getContentType();
        if (!ctype.equals("application/zip")) {
            throw new IllegalArgumentException("Unkexpected content type - " + ctype);
        }//  w  w w  .j  a  va  2s  . com
        println("Expanding ZIP file to " + target + " from " + conn.getURL().toExternalForm());
        ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream(conn.getInputStream(), BLOCK_SIZE * BLOCK_COUNT));
        int count = 0;
        prepDirs(target, true);
        try {
            for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
                copyEntry(target, zis, ze);
                // zis.closeEntry();
                count++;
            }
        } finally {
            try {
                zis.close();
            } catch (IOException ioe) {
            }
        }
        println("Installed " + count + " files/directories");
    } else {
        print("Installing ZIP file " + target + " from " + conn.getURL().toExternalForm());
        copyStream(conn, target);
        println();
    }
}

From source file:InstallJars.java

public void installGZip(URLConnection conn, String target, boolean doExpand, boolean doRun) throws IOException {
    // doRun not used on htis type
    if (doExpand) {
        String ctype = conn.getContentType();
        if (!ctype.equals("application/x-tar")) {
            throw new IllegalArgumentException("Unkexpected content type - " + ctype);
        }//from   w w  w .ja  va  2 s  . c o  m
        print("Expanding GZIP file to " + target + " from " + conn.getURL().toExternalForm());
        prepDirs(target, false);
        GZIPInputStream zis = new GZIPInputStream(
                new BufferedInputStream(conn.getInputStream(), BLOCK_SIZE * BLOCK_COUNT));
        try {
            // BufferedOutputStream os = new BufferedOutputStream(new
            // FileOutputStream(target), BLOCK_SIZE * BLOCK_COUNT);
            // try {
            // byte[] buf = new byte[bufferSize];
            // for (int size = zis.read(buf, 0, buf.length), count = 0;
            // size >= 0;
            // size = zis.read(buf, 0, buf.length), count++) {
            // //if (count % 4 == 0) print(".");
            // os.write(buf, 0, size);
            // }
            // }
            // finally {
            // try { os.flush(); os.close(); } catch (IOException ioe) {}
            // }
            pumpGZip(target, zis);
        } finally {
            try {
                zis.close();
            } catch (IOException ioe) {
            }
        }
        println();
    } else {
        print("Installing GZIP file " + target + " from " + conn.getURL().toExternalForm());
        copyStream(conn, target);
        println();
    }
}

From source file:com.chiorichan.updater.Download.java

protected InputStream getConnectionInputStream(final URLConnection urlconnection) throws DownloadException {
    final AtomicReference<InputStream> is = new AtomicReference<InputStream>();

    for (int j = 0; j < 3 && is.get() == null; j++) {
        StreamThread stream = new StreamThread(urlconnection, is);
        stream.start();//  w w  w . j  a v a2  s.c  om
        int iterationCount = 0;
        while (is.get() == null && iterationCount++ < 5)
            try {
                stream.join(1000L);
            } catch (InterruptedException ignore) {
            }

        if (stream.permDenied.get())
            throw new DownloadDeniedException("Permission denied!");

        if (is.get() != null)
            break;
        try {
            stream.interrupt();
            stream.join();
        } catch (InterruptedException ignore) {
        }
    }

    if (is.get() == null)
        throw new DownloadException("Unable to download file from " + urlconnection.getURL());
    return new BufferedInputStream(is.get());
}

From source file:com.hp.hpl.jena.grddl.impl.GRDDL.java

private Source xsltStreamSource(String url) throws TransformerException {
    try {//from   w  ww .java  2  s .co  m
        URL urlx = new URL(url);
        URLConnection conn = urlx.openConnection();
        conn.setRequestProperty("accept",
                "application/xslt+xml; q=1.0, " + "text/xsl; q=0.8, " + "application/xsl; q=0.8, "
                        + "application/xml; q=0.7, " + "text/xml; q=0.6, " + "application/xsl+xml; q=0.8, "
                        + "*/*; q=0.1");
        return new StreamSource(conn.getInputStream(), conn.getURL().toString());
    } catch (IOException e) {
        throw new TransformerException(e);
    }
}

From source file:com.romeikat.datamessie.core.base.service.download.AbstractDownloader.java

protected Charset getCharset(final URLConnection urlConnection) {
    Charset charset = null;//from  w ww  .j av  a 2  s. c  o  m
    // Prio 1: content encoding specified in header
    String encoding = urlConnection.getContentEncoding();
    // Prio 2: charset specified within content type (specified in header)
    if (encoding == null) {
        final String contentType = urlConnection.getHeaderField("Content-Type");
        if (contentType != null) {
            for (final String metaTagParameter : contentType.replace(" ", "").split(";")) {
                if (metaTagParameter.startsWith("charset=")) {
                    encoding = metaTagParameter.split("=", 2)[1];
                    break;
                }
            }
        }
    }
    // Prio 3: default charset
    if (encoding == null) {
        return Charset.defaultCharset();
    }
    // Create charset
    try {
        charset = Charset.forName(encoding);
    } catch (final Exception ex) {
        LOG.warn("Unsupported encoding " + encoding + " by " + urlConnection.getURL().toExternalForm(), ex);
    }
    // Fallback
    if (charset == null) {
        charset = Charset.defaultCharset();
    }
    // Done
    return charset;
}

From source file:net.technicpack.launchercore.mirror.download.Download.java

protected InputStream getConnectionInputStream(final URLConnection urlconnection) throws DownloadException {
    final AtomicReference<InputStream> is = new AtomicReference<InputStream>();

    for (int j = 0; (j < 3) && (is.get() == null); j++) {
        StreamThread stream = new StreamThread(urlconnection, is);
        stream.start();//from  w  ww.  j  av  a  2 s . co  m
        int iterationCount = 0;
        while ((is.get() == null) && (iterationCount++ < 5)) {
            try {
                stream.join(1000L);
            } catch (InterruptedException ignore) {
            }
        }

        if (stream.permDenied.get()) {
            throw new PermissionDeniedException("Permission denied!");
        }

        if (is.get() != null) {
            break;
        }
        try {
            stream.interrupt();
            stream.join();
        } catch (InterruptedException ignore) {
        }
    }

    if (is.get() == null) {
        throw new DownloadException("Unable to download file from " + urlconnection.getURL());
    }
    return new BufferedInputStream(is.get());
}

From source file:org.dataconservancy.dcs.access.http.SeadDatastreamServlet.java

private void getFile(SeadFile file, OutputStream destination) {

    String filePath = null;/*w ww .  j  av  a2s.  c o m*/
    if (file.getPrimaryLocation().getType() != null && file.getPrimaryLocation().getType().length() > 0
            && file.getPrimaryLocation().getLocation() != null
            && file.getPrimaryLocation().getLocation().length() > 0
            && file.getPrimaryLocation().getName() != null
            && file.getPrimaryLocation().getName().length() > 0) {
        if ((file.getPrimaryLocation().getName()
                .equalsIgnoreCase(ArchiveEnum.Archive.IU_SCHOLARWORKS.getArchive()))
                || (file.getPrimaryLocation().getName()
                        .equalsIgnoreCase(ArchiveEnum.Archive.UIUC_IDEALS.getArchive()))) {
            URLConnection connection = null;
            try {
                String location = file.getPrimaryLocation().getLocation();
                location = location.replace("http://maple.dlib.indiana.edu:8245/",
                        "https://scholarworks.iu.edu/");
                connection = new URL(location).openConnection();
                connection.setDoOutput(true);
                final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
                    }

                    @Override
                    public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                } };
                if (connection.getURL().getProtocol().equalsIgnoreCase("https")) {
                    final SSLContext sslContext = SSLContext.getInstance("SSL");
                    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                    ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
                }
                IOUtils.copy(connection.getInputStream(), destination);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            } catch (KeyManagementException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            return;
        } else if (file.getPrimaryLocation().getType()
                .equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText())
                && file.getPrimaryLocation().getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) {
            filePath = file.getPrimaryLocation().getLocation();

            String[] pathArr = filePath.split("/");

            try {
                sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(),
                        config.getSdamount());
                sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')), pathArr[pathArr.length - 1],
                        destination);
                sftp.disConnectSession();
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (SftpException e) {
                e.printStackTrace();
            }
        }
    } else {
        if (file.getSecondaryDataLocations() != null && file.getSecondaryDataLocations().size() > 0) {
            for (SeadDataLocation dataLocation : file.getSecondaryDataLocations()) {
                if (dataLocation.getType().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText())
                        && dataLocation.getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) {
                    filePath = dataLocation.getLocation();

                    String[] pathArr = filePath.split("/");

                    try {
                        sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(),
                                config.getSdamount());
                        sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')),
                                pathArr[pathArr.length - 1], destination);
                        sftp.disConnectSession();
                    } catch (JSchException e) {
                        e.printStackTrace();
                    } catch (SftpException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return;
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Get a SAX InputSource from a URLConnection's InputStream.
 * /*  w w  w  .ja  v a2  s .  co m*/
 * <p>
 * This method handles {@code gzip} and {@code deflate} decoding
 * automatically, if the {@code contentType} is reported as such.
 * </p>
 * 
 * @param conn
 *        the URLConnection
 * @return the InputSource
 * @throws IOException
 *         if any IO error occurs
 */
protected InputSource getInputSourceFromURLConnection(URLConnection conn) throws IOException {
    Reader resp = null;
    try {
        resp = getUnicodeReaderFromURLConnection(conn);

        // for now we are reading entire response into memory... might want
        // to save to a temporary file if response very large, but we assume
        // for now the responses will be fairly small
        String respXml = FileCopyUtils.copyToString(resp);

        log.trace("Got response XML from URL [{}]:\n{}", conn.getURL(), respXml);
        if (respXml.length() < 1) {
            // no data in response... can't be valid so throw IOException
            throw new IOException("Empty response from [" + conn.getURL() + "]");
        }
        return new InputSource(new StringReader(respXml));
    } finally {
        if (resp != null) {
            try {
                resp.close();
            } catch (IOException e) {
                // ignore me
            }
        }
    }
}