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:cdr.forms.SwordDepositHandler.java

/**
 * Generates a limited authentication scope for the supplied URL, so that an HTTP client will not send username and
 * passwords to other URLs./*from   www. java  2s  . c o m*/
 * 
 * @param queryURL
 *           the URL for the query.
 * @return an authentication scope tuned to the requested URL.
 * @throws IllegalArgumentException
 *            if <code>queryURL</code> is not a well-formed URL.
 */
public static AuthScope getAuthenticationScope(String queryURL) {
    if (queryURL == null) {
        throw new NullPointerException("Cannot derive authentication scope for null URL");
    }
    try {
        URL url = new URL(queryURL);
        // port defaults to 80 unless the scheme is https
        // or the port is explicitly set in the URL.
        int port = 80;
        if (url.getPort() == -1) {
            if ("https".equals(url.getProtocol())) {
                port = 443;
            }
        } else {
            port = url.getPort();
        }
        return new AuthScope(url.getHost(), port);
    } catch (MalformedURLException mue) {
        throw new IllegalArgumentException("supplied URL <" + queryURL + "> is ill-formed:" + mue.getMessage());
    }
}

From source file:io.fabric8.apiman.ApimanStarter.java

private static URL waitForDependency(URL url, String path, String serviceName, String key, String value,
        String username, String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;/*from w ww .  ja  va 2  s  . com*/
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + path);
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH,
                                ApimanStarter.TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(
                                ApimanStarter.CLIENT_KEYSTORE_PATH,
                                ApimanStarter.CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                    log.info(username + ":" + "*****");
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up. " + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. " + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * Construct a full URL to the specified path given the URL
 * to some other resource in the bundle//from  w w  w .j a  v  a 2s  . c o m
 *
 * @param url
 * @param path
 * @return locaion
 */

private static String[] getBundleLocation(URL url, String path) {
    String protocol = url.getProtocol();
    String host = url.getHost();
    String port = String.valueOf(url.getPort());
    String urlString = protocol + "://" + host + ":" + port + "/" + path;
    return new String[] { urlString, null };
}

From source file:net.ontopia.topicmaps.entry.XMLConfigSource.java

/**
 * INTERNAL://  www  .  j av  a2 s  .  co  m
 */
public static TopicMapRepositoryIF getRepositoryFromClassPath(String resourceName,
        Map<String, String> environ) {

    // look up configuration via classpath
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    URL url = cl.getResource(resourceName);
    if (url == null)
        throw new OntopiaRuntimeException("Could not find resource '" + resourceName + "' on CLASSPATH.");

    // build configuration environment
    if (environ == null)
        environ = new HashMap<String, String>(1);
    if ("file".equals(url.getProtocol())) {
        String file = url.getFile();
        environ.put(CWD, file.substring(0, file.lastIndexOf('/')));
    } else
        environ.put(CWD, ".");

    // read configuration and create the repository instance
    try {
        return createRepository(readSources(new InputSource(url.openStream()), environ));
    } catch (IOException e) {
        throw new OntopiaRuntimeException(e);
    }

}

From source file:edu.umn.cs.spatialHadoop.core.SpatialSite.java

private static String findContainingJar(Class my_class) {
    ClassLoader loader = my_class.getClassLoader();
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    try {//from  ww w .  jav  a2 s .co m
        for (Enumeration<URL> itr = loader.getResources(class_file); itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();
            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.frontcache.core.FCUtils.java

public static HttpHost getHttpHost(URL host) {
    HttpHost httpHost = new HttpHost(host.getHost(), host.getPort(), host.getProtocol());
    return httpHost;
}

From source file:at.gv.egiz.pdfas.web.helper.RemotePDFFetcher.java

public static byte[] fetchPdfFile(String pdfURL) throws PdfAsWebException {
    URL url;
    String[] fetchInfos;//from   ww w  .  j  a v a2s.  co  m
    try {
        fetchInfos = extractSensitiveInformationFromURL(pdfURL);
        url = new URL(fetchInfos[0]);
    } catch (MalformedURLException e) {
        logger.warn("Not a valid URL!", e);
        throw new PdfAsWebException("Not a valid URL!", e);
    } catch (IOException e) {
        logger.warn("Not a valid URL!", e);
        throw new PdfAsWebException("Not a valid URL!", e);
    }
    if (WebConfiguration.isProvidePdfURLinWhitelist(url.toExternalForm())) {
        if (url.getProtocol().equals("http") || url.getProtocol().equals("https")) {
            URLConnection uc = null;
            InputStream is = null;
            try {
                uc = url.openConnection();

                if (fetchInfos.length == 3) {
                    String userpass = fetchInfos[1] + ":" + fetchInfos[2];
                    String basicAuth = "Basic "
                            + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8"));
                    uc.setRequestProperty("Authorization", basicAuth);
                }

                is = uc.getInputStream();
                return StreamUtils.inputStreamToByteArray(is);
            } catch (Exception e) {
                logger.warn("Failed to fetch pdf document!", e);
                throw new PdfAsWebException("Failed to fetch pdf document!", e);
            } finally {
                IOUtils.closeQuietly(is);
            }
        } else {
            throw new PdfAsWebException(
                    "Failed to fetch pdf document protocol " + url.getProtocol() + " is not supported");
        }
    } else {
        throw new PdfAsWebException("Failed to fetch pdf document " + url.toExternalForm() + " is not allowed");
    }
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Returns persistence unit root url//ww  w .ja va  2 s. c  o m
 * 
 * @param url
 *            raw url
 * @return rootUrl rootUrl
 */
private static URL getPersistenceRootUrl(URL url) {
    String f = url.getFile();
    f = parseFilePath(f);

    URL jarUrl = url;
    try {
        if (AllowedProtocol.isJarProtocol(url.getProtocol())) {
            jarUrl = new URL(f);
            if (jarUrl.getProtocol() != null
                    && AllowedProtocol.FILE.name().equals(jarUrl.getProtocol().toUpperCase())
                    && StringUtils.contains(f, " ")) {
                jarUrl = new File(f).toURI().toURL();
            }
        } else if (AllowedProtocol.isValidProtocol(url.getProtocol())) {
            if (StringUtils.contains(f, " ")) {
                jarUrl = new File(f).toURI().toURL();
            } else {
                jarUrl = new File(f).toURL();
            }
        }
    } catch (MalformedURLException mex) {
        log.error("Error during getPersistenceRootUrl(), Caused by: {}.", mex);
        throw new IllegalArgumentException("Invalid jar URL[] provided!" + url);
    }

    return jarUrl;
}

From source file:de.betterform.agent.betty.Betty.java

public static URI toFileCompatibleURI(URL url) throws URISyntaxException {
    if (url == null) {
        return null;
    }//  w w  w  .  j  ava2 s.com

    String string = url.toString();
    if (url.getProtocol().equals("file") && url.getQuery() != null) {
        return new URI(string.substring(0, string.indexOf('?')));
    }

    return new URI(string);
}

From source file:net.antidot.semantic.rdf.rdb2rdf.r2rml.tools.R2RMLToolkit.java

/**
 * The URL-safe version of a string is obtained by an URL encoding to a
 * string value./*from   ww  w  .  j  a v  a 2  s .  c o  m*/
 * 
 * @throws R2RMLDataError
 * @throws MalformedURLException
 */
public static String getURLSafeVersion(String value) throws R2RMLDataError {
    if (value == null)
        return null;
    URL url = null;
    try {
        url = new URL(value);
    } catch (MalformedURLException mue) {
        // This template should be not a url : no encoding
        return value;
    }
    // No exception raised, this template is a valid url : perform
    // percent-encoding
    try {
        java.net.URI uri = new java.net.URI(url.getProtocol(), url.getAuthority(), url.getPath(),
                url.getQuery(), url.getRef());
        String result = uri.toURL().toString();
        // Percent encoding : complete with no supported char in this
        // treatment
        result = result.replaceAll("\\,", "%2C");
        return result;
    } catch (URISyntaxException e) {
        throw new R2RMLDataError("[R2RMLToolkit:getIRISafeVersion] This value " + value
                + " can not be percent-encoded because " + e.getMessage());
    } catch (MalformedURLException e) {
        throw new R2RMLDataError("[R2RMLToolkit:getIRISafeVersion] This value " + value
                + " can not be percent-encoded because " + e.getMessage());
    }
}