Example usage for java.net URL getProtocol

List of usage examples for java.net URL getProtocol

Introduction

In this page you can find the example usage for java.net URL getProtocol.

Prototype

public String getProtocol() 

Source Link

Document

Gets the protocol name of this URL .

Usage

From source file:org.n52.web.common.RequestUtils.java

/**
 * Get the full request {@link URL} including the query parameter
 *
 * @return Request {@link URL} with query parameter
 * @throws IOException/*from  w ww  .  ja v  a 2 s  .  c om*/
 * @throws URISyntaxException
 */
public static String resolveFullRequestUrl() throws IOException, URISyntaxException {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();

    URL url = new URL(request.getRequestURL().toString());

    String scheme = url.getProtocol();
    String userInfo = url.getUserInfo();
    String host = url.getHost();

    int port = url.getPort();

    String path = request.getRequestURI();
    if (path != null && path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }
    String query = request.getQueryString();

    URI uri = new URI(scheme, userInfo, host, port, path, query, null);
    return uri.toString();
}

From source file:SageCollegeProject.guideBox.java

public static String GetEncWebCall(String webcall) {
    try {/*  w w  w. j a  va2  s . co m*/
        URL url = new URL(webcall);
        URI test = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return test.toASCIIString();
    } catch (URISyntaxException | MalformedURLException ex) {
        Logger.getLogger(guideBox.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:com.digitalpebble.storm.crawler.protocol.http.HttpRobotRulesParser.java

/**
 * Compose unique key to store and access robot rules in cache for given URL
 *///w  w  w.j  a v  a  2 s  .  com
protected static String getCacheKey(URL url) {
    String protocol = url.getProtocol().toLowerCase(Locale.ROOT); // normalize
                                                                  // to
                                                                  // lower
                                                                  // case
    String host = url.getHost().toLowerCase(Locale.ROOT); // normalize to
                                                          // lower case
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
    }
    /*
     * Robot rules apply only to host, protocol, and port where robots.txt
     * is hosted (cf. NUTCH-1752). Consequently
     */
    String cacheKey = protocol + ":" + host + ":" + port;
    return cacheKey;
}

From source file:URLUtil.java

/**
 * Method that tries to get a stream (ideally, optimal one) to read from the
 * specified URL. Currently it just means creating a simple file input stream
 * if the URL points to a (local) file, and otherwise relying on URL classes
 * input stream creation method.//from w w w . java 2 s.c o  m
 */
public static InputStream inputStreamFromURL(URL url) throws IOException {
    if ("file".equals(url.getProtocol())) {
        /*
         * As per [WSTX-82], can not do this if the path refers to a network drive
         * on windows. This fixes the problem; might not be needed on all
         * platforms (NFS?), but should not matter a lot: performance penalty of
         * extra wrapping is more relevant when accessing local file system.
         */
        String host = url.getHost();
        if (host == null || host.length() == 0) {
            return new FileInputStream(url.getPath());
        }
    }
    return url.openStream();
}

From source file:org.thoughtcrime.ssl.pinning.util.PinningHelper.java

/**
 * Constructs an HttpsURLConnection that will validate HTTPS connections against a set of
 * specified pins.// w w w .j  ava2s .  c  o m
 *
 * @param pins An array of encoded pins to match a seen certificate
 *             chain against. A pin is a hex-encoded hash of a X.509 certificate's
 *             SubjectPublicKeyInfo. A pin can be generated using the provided pin.py
 *             script: python ./tools/pin.py certificate_file.pem
 *
 */

public static HttpsURLConnection getPinnedHttpsURLConnection(Context context, String[] pins, URL url)
        throws IOException {
    try {
        if (!url.getProtocol().equals("https")) {
            throw new IllegalArgumentException("Attempt to construct pinned non-https connection!");
        }

        TrustManager[] trustManagers = new TrustManager[1];
        trustManagers[0] = new PinningTrustManager(SystemKeyStore.getInstance(context), pins, 0);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);

        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

        return urlConnection;
    } catch (NoSuchAlgorithmException nsae) {
        throw new AssertionError(nsae);
    } catch (KeyManagementException e) {
        throw new AssertionError(e);
    }
}

From source file:com.npower.dl.DownloadFactory.java

/**
 * Extract Server URL: /*from w  ww .jav a 2s .  co m*/
 * http(s)://server:port
 * 
 * @param requestURL
 * @return
 * @throws MalformedURLException
 */
public static String getServerURL(String requestURL) throws MalformedURLException {
    URL url = new URL(requestURL);
    String protocol = url.getProtocol();
    String server = url.getHost();
    int port = url.getPort();
    if (port <= 0) {
        if (protocol.equalsIgnoreCase("https")) {
            port = 443;
        } else {
            port = 80;
        }
    }
    String serverURL = protocol + "://" + server + ":" + port;
    return serverURL;
}

From source file:gov.nih.nci.cabig.ccts.security.SecureURL.java

/**
 * Retrieve the contents from the given URL as a String, assuming the URL's
 * server matches what we expect it to match.
 *///www.  ja va  2  s .  c o  m
public static String retrieve(String url) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("entering retrieve(" + url + ")");
    }
    BufferedReader r = null;
    try {
        URL u = new URL(url);
        if (!u.getProtocol().equals("https")) {
            // IOException may not be the best exception we could throw here
            // since the problem is with the URL argument we were passed,
            // not
            // IO. -awp9
            log.error("retrieve(" + url + ") on an illegal URL since protocol was not https.");
            throw new IOException("only 'https' URLs are valid for this method");
        }

        // JAP: changing to allow validation of Globus-style host names.
        // URLConnection uc = u.openConnection();
        HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
        uc.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                boolean valid = false;
                try {
                    String expectedHostname = hostname.toLowerCase();
                    log.debug("expectedHostname = " + expectedHostname);

                    String subjectDN = session.getPeerCertificateChain()[0].getSubjectDN().getName()
                            .toLowerCase();
                    log.debug("subjectDN = " + subjectDN);
                    String assertedHostname = null;
                    for (String part : subjectDN.split(",")) {
                        String[] nameValue = part.split("=");
                        String name = nameValue[0].toLowerCase().trim();
                        String value = nameValue[1].trim();
                        if (name.equals("cn")) {
                            assertedHostname = value;
                            break;
                        }
                    }
                    if (assertedHostname == null) {
                        log.warn("No common name found in subject distinguished name.");
                        return false;
                    }
                    log.debug("assertedHostname = " + assertedHostname);
                    if (assertedHostname.startsWith("host/")) {
                        expectedHostname = "host/" + expectedHostname;
                        log.debug("detected Globus-style common name, expectedHostname = " + expectedHostname);
                    }
                    valid = assertedHostname.equals(expectedHostname);
                    log.debug("valid = " + valid);
                } catch (Exception ex) {
                    log.warn(ex);
                }
                return valid;
            }

        });

        uc.setRequestProperty("Connection", "close");
        r = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line;
        StringBuffer buf = new StringBuffer();
        while ((line = r.readLine()) != null)
            buf.append(line + "\n");
        return buf.toString();
    } finally {
        try {
            if (r != null)
                r.close();
        } catch (IOException ex) {
            // ignore
        }
    }
}

From source file:com.janrain.oauth2.OAuth2.java

/**
 * @param redirectUri the redirect_uri (per OAuth2) to validate; may be null, which is permitted/valid
 *
 * @throws ValidationException if the supplied redirectUri fails the OAuth2 prescribed checks
 *//* w  ww .j  a v a  2  s.c  o  m*/
public static void validateRedirectUri(String redirectUri, @Nullable String expected)
        throws ValidationException {
    if (StringUtils.isNotEmpty(redirectUri)) {
        try {
            URL url = new URL(redirectUri);
            if (StringUtils.isEmpty(url.getProtocol())) {
                throw new ValidationException(OAUTH2_TOKEN_INVALID_REQUEST,
                        "redirect_uri is not absolute: " + redirectUri);
            }
            if (StringUtils.isNotEmpty(url.getRef())) {
                throw new ValidationException(OAUTH2_TOKEN_INVALID_REQUEST,
                        "redirect_uri MUST not contain a fragment: " + redirectUri);
            }
            if (StringUtils.isNotEmpty(expected) && !redirectUri.equals(expected)) {
                throw new ValidationException(OAUTH2_TOKEN_INVALID_GRANT,
                        "Redirect URI mismatch, expected: " + expected);
            }
        } catch (MalformedURLException e) {
            throw new ValidationException(OAUTH2_TOKEN_INVALID_REQUEST,
                    "Invalid redirect_uri: " + e.getMessage());
        }
    }
}

From source file:com.digitalpebble.stormcrawler.protocol.HttpRobotRulesParser.java

/**
 * Compose unique key to store and access robot rules in cache for given URL
 *///from w  ww .  ja v  a  2 s .  c  o  m
protected static String getCacheKey(URL url) {
    String protocol = url.getProtocol().toLowerCase(Locale.ROOT);
    String host = url.getHost().toLowerCase(Locale.ROOT);

    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
    }
    /*
     * Robot rules apply only to host, protocol, and port where robots.txt
     * is hosted (cf. NUTCH-1752). Consequently
     */
    String cacheKey = protocol + ":" + host + ":" + port;
    return cacheKey;
}

From source file:com.asakusafw.shafu.core.net.ShafuNetwork.java

/**
 * Processes a content on the target URL.
 * @param url the target URL/*from  w  ww.ja v  a  2s.c o m*/
 * @param processor the content processor
 * @param <T> the processing result type
 * @return the process result
 * @throws IOException if failed to process the content
 */
public static <T> T processContent(URL url, IContentProcessor<? extends T> processor) throws IOException {
    String protocol = url.getProtocol();
    if (protocol != null && HTTP_SCHEMES.contains(protocol)) {
        return processHttpContent(url, processor);
    }
    InputStream input;
    try {
        input = url.openStream();
    } catch (IOException e) {
        throw new IOException(MessageFormat.format(Messages.ShafuNetwork_failedToOpenContent, url), e);
    }
    try {
        return processor.process(input);
    } finally {
        input.close();
    }
}