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:ResourceUtils.java

/**
 * Determine whether the given URL points to a resource in a jar file,
 * that is, has protocol "jar", "zip", "wsjar" or "code-source".
 * <p>"zip" and "wsjar" are used by BEA WebLogic Server and IBM WebSphere, respectively,
 * but can be treated like jar files. The same applies to "code-source" URLs on Oracle
 * OC4J, provided that the path contains a jar separator.
 * @param url the URL to check//from w  w w. j  a v  a2s  .  c  o m
 * @return whether the URL has been identified as a JAR URL
 */
public static boolean isJarURL(URL url) {
    String protocol = url.getProtocol();
    return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_ZIP.equals(protocol)
            || URL_PROTOCOL_WSJAR.equals(protocol)
            || (URL_PROTOCOL_CODE_SOURCE.equals(protocol) && url.getPath().indexOf(JAR_URL_SEPARATOR) != -1));
}

From source file:org.talend.components.elasticsearch.runtime_2_4.ElasticsearchConnection.java

public static RestClient createClient(ElasticsearchDatastoreProperties datastore) throws MalformedURLException {
    String urlStr = datastore.nodes.getValue();
    String[] urls = urlStr.split(",");
    HttpHost[] hosts = new HttpHost[urls.length];
    int i = 0;/*from   w  ww. j a va2  s  .com*/
    for (String address : urls) {
        URL url = new URL("http://" + address);
        hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        i++;
    }
    RestClientBuilder restClientBuilder = RestClient.builder(hosts);
    if (datastore.auth.useAuth.getValue()) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                datastore.auth.userId.getValue(), datastore.auth.password.getValue()));
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {

            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });
    }
    return restClientBuilder.build();
}

From source file:com.esri.geoportal.commons.utils.HttpClientContextBuilder.java

/**
 * Creates client context./*w  ww  . j a  v  a 2s .c  o  m*/
 * @param url url
 * @param cred credentials
 * @return client context
 */
public static HttpClientContext createHttpClientContext(URL url, SimpleCredentials cred) {
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(cred.getUserName(), cred.getPassword()));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);

    return context;
}

From source file:com.cloudera.sqoop.util.Jars.java

/**
 * Return the jar file path that contains a particular class.
 * Method mostly cloned from o.a.h.mapred.JobConf.findContainingJar().
 *//*from   ww  w .  j  a v a2  s.c  o  m*/
public static String getJarPathForClass(Class<? extends Object> classObj) {
    ClassLoader loader = classObj.getClassLoader();
    String classFile = classObj.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration<URL> itr = loader.getResources(classFile); 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());
                }
                // URLDecoder is a misnamed class, since it actually decodes
                // x-www-form-urlencoded MIME type rather than actual
                // URL encoding (which the file path has). Therefore it would
                // decode +s to ' 's which is incorrect (spaces are actually
                // either unencoded or encoded as "%20"). Replace +s first, so
                // that they are kept sacred during the decoding process.
                toReturn = toReturn.replaceAll("\\+", "%2B");
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:eu.artist.methodology.mpt.cheatsheet.Activator.java

public static void createDirs() throws IOException, URISyntaxException {
    final String STATE_LOCATION = Activator.getDefault().getStateLocation().toString();

    System.out.println("Creating dirs in state location ...");
    URL csURL = plugin.getBundle().getEntry("cheatsheets/");
    //csURL = new URL("platform:/plugin/eu.artist.methodology.mpt.cheatsheet/cheatsheets/" + csMap.get(csId));
    URL resolvedcsURL = FileLocator.toFileURL(csURL);
    URI resolvedcsURI = new URI(resolvedcsURL.getProtocol(), resolvedcsURL.getPath(), null);
    File csFile = new File(resolvedcsURI);

    FileUtils.copyDirectory(csFile, new File(STATE_LOCATION));
}

From source file:io.seldon.importer.articles.AttributesImporterUtils.java

public static String getBaseUrl(String url) throws Exception {
    URL aURL = new URL(url);

    String protocol = aURL.getProtocol();
    String host = aURL.getHost();
    String path = aURL.getPath();

    String baseUrl = String.format("%s://%s%s", protocol, host, path);
    return baseUrl;
}

From source file:fr.dutra.confluence2wordpress.util.UrlUtils.java

/**
 * Sanitizes the given URL by escaping the path and query parameters, if necessary.
 * @see "http://stackoverflow.com/questions/724043/http-url-address-encoding-in-java"
 * @param url/*from  w w w .j  a v a  2 s  .c  o m*/
 * @return
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public static String sanitize(String url) throws URISyntaxException, MalformedURLException {
    URL temp = new URL(url);
    URI uri = new URI(temp.getProtocol(), temp.getUserInfo(), temp.getHost(), temp.getPort(), temp.getPath(),
            temp.getQuery(), temp.getRef());
    return uri.toASCIIString();
}

From source file:Urls.java

/** Whether the URL is a file in the local file system. */
public static boolean isLocalFile(java.net.URL url) {
    String scheme = url.getProtocol();
    return "file".equalsIgnoreCase(scheme) && !hasHost(url);
}

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

/**
 * Get the request {@link URL} without the query parameter
 *
 * @return Request {@link URL} without query parameter
 * @throws IOException/*from   ww w .j  av a2 s  .c o m*/
 * @throws URISyntaxException
 */
public static String resolveQueryLessRequestUrl() 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);
    }

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

From source file:URLUtil.java

/**
 * Method that tries to get a stream (ideally, optimal one) to write to the
 * resource specified by given URL. Currently it just means creating a simple
 * file output stream if the URL points to a (local) file, and otherwise
 * relying on URL classes input stream creation method.
 *///w w w  . j av a 2 s . com
public static OutputStream outputStreamFromURL(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.
         */
        String host = url.getHost();
        if (host == null || host.length() == 0) {
            return new FileOutputStream(url.getPath());
        }
    }
    return url.openConnection().getOutputStream();
}