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:com.tc.util.io.ServerURL.java

public InputStream openStream(PwProvider pwProvider) throws IOException {
    URLConnection urlConnection = createSecureConnection(pwProvider);

    try {/* w ww . j a v a2  s . co m*/
        return urlConnection.getInputStream();
    } catch (IOException e) {
        if (urlConnection instanceof HttpURLConnection) {
            int responseCode = ((HttpURLConnection) urlConnection).getResponseCode();
            switch (responseCode) {
            case 401:
                throw new TCAuthenticationException(
                        "Authentication error connecting to " + urlConnection.getURL()
                                + " - invalid credentials (tried user " + securityInfo.getUsername() + ")",
                        e);
            case 403:
                throw new TCAuthorizationException("Authorization error connecting to " + urlConnection.getURL()
                        + " - does the user '" + securityInfo.getUsername() + "' have the required roles?", e);
            default:
            }
        }
        throw e;
    }
}

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

/**
 * Get an InputStream from a URLConnection response, handling compression.
 * /*from   w w w. ja  v a 2 s.  c o m*/
 * <p>
 * This method handles decompressing the response if the encoding is set to
 * {@code gzip} or {@code deflate}.
 * </p>
 * 
 * @param conn
 *        the URLConnection
 * @return the InputStream
 * @throws IOException
 *         if any IO error occurs
 */
protected InputStream getInputStreamFromURLConnection(URLConnection conn) throws IOException {
    String enc = conn.getContentEncoding();
    String type = conn.getContentType();

    if (conn instanceof HttpURLConnection) {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        if (httpConn.getResponseCode() < 200 || httpConn.getResponseCode() > 299) {
            log.info("Non-200 HTTP response from {}: {}", conn.getURL(), httpConn.getResponseCode());
        }
    }

    log.trace("Got content type [{}] encoded as [{}]", type, enc);

    InputStream is = conn.getInputStream();
    if ("gzip".equalsIgnoreCase(enc)) {
        is = new GZIPInputStream(is);
    } else if ("deflate".equalsIgnoreCase("enc")) {
        is = new DeflaterInputStream(is);
    }
    return is;
}

From source file:org.openbel.framework.core.protocol.handler.AbstractProtocolHandler.java

/**
 * Retrieves a resource from the {@code urlc} and save it to
 * {@code downloadLocation}.//from  w ww.  ja  v  a 2  s.  c  om
 * 
 * @param urlc {@link URLConnection}, the url connection
 * @param downloadLocation {@link String}, the location to save the
 * resource content to
 * @throws IOException Thrown if an io error occurred downloading the
 * resource
 * @throws ResourceDownloadError Thrown if there was an I/O error
 * downloading the resource
 */
protected File downloadResource(URLConnection urlc, String downloadLocation) throws ResourceDownloadError {
    if (!urlc.getDoInput()) {
        urlc.setDoInput(true);
    }

    File downloadFile = new File(downloadLocation);
    try {
        File downloaded = File.createTempFile(ProtocolHandlerConstants.BEL_FRAMEWORK_TMP_FILE_PREFIX, null);

        IOUtils.copy(urlc.getInputStream(), new FileOutputStream(downloaded));

        FileUtils.copyFile(downloaded, downloadFile);

        // delete temp file holding download
        if (!downloaded.delete()) {
            downloaded.deleteOnExit();
        }
    } catch (IOException e) {
        final String url = urlc.getURL().toString();
        final String msg = "I/O error";
        throw new ResourceDownloadError(url, msg, e);
    }

    return downloadFile;
}

From source file:org.apache.jmeter.protocol.http.control.CacheManager.java

/**
 * Save the Last-Modified, Etag, and Expires headers if the result is cacheable.
 * Version for Java implementation.//from  w w  w . ja v a 2  s .c  o  m
 * @param conn connection
 * @param res result
 */
public void saveDetails(URLConnection conn, HTTPSampleResult res) {
    if (isCacheable(res) && !hasVaryHeader(conn)) {
        String lastModified = conn.getHeaderField(HTTPConstants.LAST_MODIFIED);
        String expires = conn.getHeaderField(HTTPConstants.EXPIRES);
        String etag = conn.getHeaderField(HTTPConstants.ETAG);
        String url = conn.getURL().toString();
        String cacheControl = conn.getHeaderField(HTTPConstants.CACHE_CONTROL);
        String date = conn.getHeaderField(HTTPConstants.DATE);
        setCache(lastModified, cacheControl, expires, etag, url, date);
    }
}

From source file:net.sf.eclipsecs.core.config.configtypes.RemoteConfigurationType.java

@Override
protected byte[] getBytesFromURLConnection(URLConnection connection) throws IOException {

    byte[] configurationFileData = null;
    InputStream in = null;//from  w w  w  .j a  v  a  2s .c  om
    try {

        // set timeouts - bug 2941010
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);

        if (connection instanceof HttpURLConnection) {

            if (!sFailedWith401URLs.contains(connection.getURL().toString())) {

                HttpURLConnection httpConn = (HttpURLConnection) connection;
                httpConn.setInstanceFollowRedirects(true);
                httpConn.connect();
                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    try {
                        RemoteConfigAuthenticator.removeCachedAuthInfo(connection.getURL());
                    } catch (CheckstylePluginException e) {
                        CheckstyleLog.log(e);
                    }

                    // add to 401ed URLs
                    sFailedWith401URLs.add(connection.getURL().toString());
                    throw new IOException(Messages.RemoteConfigurationType_msgUnAuthorized);
                }
            } else {
                // don't retry since we just get another 401
                throw new IOException(Messages.RemoteConfigurationType_msgUnAuthorized);
            }
        }

        in = connection.getInputStream();
        configurationFileData = IOUtils.toByteArray(in);
    } finally {
        IOUtils.closeQuietly(in);

    }
    return configurationFileData;
}

From source file:ubic.gemma.image.aba.AllenBrainAtlasServiceImpl.java

private void showHeader(URLConnection url) {

    this.infoOut.println("");
    this.infoOut.println("URL              : " + url.getURL().toString());
    this.infoOut.println("Content-Type     : " + url.getContentType());
    this.infoOut.println("Content-Length   : " + url.getContentLength());
    if (url.getContentEncoding() != null)
        this.infoOut.println("Content-Encoding : " + url.getContentEncoding());
}

From source file:InstallJars.java

public void installJar(URLConnection conn, String target, boolean doExpand, boolean doRun) throws IOException {
    if (doExpand) {
        println("Expanding JAR file " + target + " from " + conn.getURL().toExternalForm());
        // *** may need to specialize for JAR format ***
        ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream(conn.getInputStream(), BLOCK_SIZE * BLOCK_COUNT));
        int count = 0;
        prepDirs(target, true);/*ww w.ja  v  a  2 s . c o m*/
        try {
            while (zis.available() > 0) {
                ZipEntry ze = zis.getNextEntry();
                copyEntry(target, zis, ze);
                count++;
            }
        } finally {
            try {
                zis.close();
            } catch (IOException ioe) {
            }
        }
        println("Installed " + count + " files/directories");
    } else {
        print("Installing JAR file " + target + " from " + conn.getURL().toExternalForm());
        copyStream(conn, target);
        println();
        if (doRun) {
            runTarget(target, true);
        }
    }
}

From source file:InstallJars.java

public void installClass(URLConnection conn, String target, boolean doExpand, boolean doRun)
        throws IOException {
    // doExpand not used on htis type
    print("Installing class file " + target + " from " + conn.getURL().toExternalForm());
    copyStream(conn, target);/*from ww  w .j av a2 s. co  m*/
    println();
    if (doRun) {
        runTarget(target, false);
    }
}

From source file:org.clapper.curn.FeedDownloadThread.java

/**
 * Get the input stream for a URL. Handles compressed data.
 *
 * @param conn the <tt>URLConnection</tt> to process
 *
 * @return the <tt>InputStream</tt>
 *
 * @throws IOException I/O error// www  .  j  a v  a 2  s.  co m
 */
private InputStream getURLInputStream(final URLConnection conn) throws IOException {
    InputStream is = conn.getInputStream();
    String ce = conn.getHeaderField("content-encoding");

    if (ce != null) {
        String urlString = conn.getURL().toString();

        log.debug("URL \"" + urlString + "\" -> Content-Encoding: " + ce);
        if (ce.indexOf("gzip") != -1) {
            log.debug("URL \"" + urlString + "\" is compressed. Using GZIPInputStream.");
            is = new GZIPInputStream(is);
        }
    }

    return is;
}

From source file:com.tc.util.io.ServerURL.java

private static void tweakSecureConnectionSettings(URLConnection urlConnection) {
    HttpsURLConnection sslUrlConnection;

    try {//from w w w. j a  v a 2  s .c o  m
        sslUrlConnection = (HttpsURLConnection) urlConnection;
    } catch (ClassCastException e) {
        throw new IllegalStateException("Unable to cast " + urlConnection
                + " to javax.net.ssl.HttpsURLConnection. "
                + "Options tc.ssl.trustAllCerts and tc.ssl.disableHostnameVerifier are causing this issue.", e);
    }

    if (DISABLE_HOSTNAME_VERIFIER) {
        // don't verify hostname
        sslUrlConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }

    TrustManager[] trustManagers = null;
    if (TRUST_ALL_CERTS) {
        // trust all certs
        trustManagers = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
                //
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
                //
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
    }

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
        sslUrlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Exception e) {
        throw new RuntimeException("unable to create SSL connection from " + urlConnection.getURL(), e);
    }
}