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

/**
 * Converts each of an array of <code>URL</code> to a <code>File</code>.
 * <p/>//www. j  a v  a  2 s .c  om
 * Returns an array of the same size as the input.
 * If the input is {@code null}, an empty array is returned.
 * If the input contains {@code null}, the output array contains {@code null} at the same
 * index.
 * <p/>
 * This method will decode the URL.
 * Syntax such as <code>file:///my%20docs/file.txt</code> will be
 * correctly decoded to <code>/my docs/file.txt</code>.
 *
 * @param urls the file URLs to convert, {@code null} returns empty array
 * @return a non-{@code null} array of Files matching the input, with a {@code null} item
 * if there was a {@code null} at that index in the input array
 * @throws IllegalArgumentException if any file is not a URL file
 * @throws IllegalArgumentException if any file is incorrectly encoded
 * @since 1.1
 */
public static File[] toFiles(URL[] urls) {
    if (urls == null || urls.length == 0) {
        return EMPTY_FILE_ARRAY;
    }
    File[] files = new File[urls.length];
    for (int i = 0; i < urls.length; i++) {
        URL url = urls[i];
        if (url != null) {
            if (url.getProtocol().equals("file") == false) {
                throw new IllegalArgumentException("URL could not be converted to a File: " + url);
            }
            files[i] = toFile(url);
        }
    }
    return files;
}

From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java

/**
 * ?post??/*from www.j a  v a2s  .  c o  m*/
 * 
 * @param url
 * @return
 */
public static HttpPost getPostMethod(String url) {

    URI uri = null;
    try {
        URL _url = new URL(url);
        uri = new URI(_url.getProtocol(), _url.getHost(), _url.getPath(), _url.getQuery(), null);

    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HttpPost pmethod = new HttpPost(uri); // ??
    pmethod.addHeader("Connection", "keep-alive");
    pmethod.addHeader("Accept", "*/*");
    pmethod.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    pmethod.addHeader("Host", "mp.weixin.qq.com");
    pmethod.addHeader("X-Requested-With", "XMLHttpRequest");
    pmethod.addHeader("Cache-Control", "max-age=0");
    pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
    return pmethod;
}

From source file:com.sldeditor.ui.detail.config.symboltype.externalgraphic.RelativePath.java

/**
 * Checks if is local file.//  w  w  w.  ja va 2 s.  com
 *
 * @param url the url
 * @return true, if is local file
 */
public static boolean isLocalFile(URL url) {
    if (url == null) {
        return false;
    }
    String scheme = url.getProtocol();
    return "file".equalsIgnoreCase(scheme) && !hasHost(url);
}

From source file:com.asual.summer.core.util.ResourceUtils.java

/**
  * Tries to convert the specified URL to a file object. If this fails,
  * <b>null</b> is returned.
  *//  w ww  .  ja  va  2  s  .c  om
  * @param url the URL
  * @return the resulting file object
  */
@SuppressWarnings("deprecation")
public static File fileFromURL(URL url) {
    if (PROTOCOL_FILE.equals(url.getProtocol())) {
        return new File(URLDecoder.decode(url.getPath()));
    } else {
        return null;
    }
}

From source file:Urls.java

/** Whether the URL refers to a resource in the local file system. */
public static boolean isLocal(java.net.URL url) {
    if (isLocalFile(url)) {
        return true;
    }//from  w  w w . j a va2 s.c  o m
    String protocol = url.getProtocol();
    if ("jar".equalsIgnoreCase(protocol)) {
        String path = url.getPath();
        int emIdx = path.lastIndexOf('!');
        String subUrlString = emIdx == -1 ? path : path.substring(0, emIdx);
        try {
            URL subUrl = new URL(subUrlString);
            return isLocal(subUrl);
        } catch (java.net.MalformedURLException mfu) {
            return false;
        }
    } else {
        return false;
    }
}

From source file:org.apache.gobblin.utils.HttpUtils.java

public static String createApacheHttpClientLimiterKey(Config config) {
    try {//from  w  ww . java2 s  .com
        String urlTemplate = config.getString(HttpConstants.URL_TEMPLATE);
        URL url = new URL(urlTemplate);
        String key = url.getProtocol() + "/" + url.getHost();
        if (url.getPort() > 0) {
            key = key + "/" + url.getPort();
        }
        log.info("Get limiter key [" + key + "]");
        return key;
    } catch (MalformedURLException e) {
        throw new IllegalStateException("Cannot get limiter key.", e);
    }
}

From source file:com.singular.utils.FileUtils.java

/**
 * Taken from apache hadoop project.//  ww  w .  j  av  a2 s . c  o  m
 * Apache 2.0 license.
 *
 * @param className
 * @return
 */
public static String findContainingJar(Class className) {
    ClassLoader loader = className.getClassLoader();
    String classFile = className.getName().replaceAll("\\.", "/") + ".class";

    try {
        for (Enumeration 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());
                }
                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:de.jwi.ftp.FTPUploader.java

public static String upload(URL url, List files) {
    String rcs = "";

    if (!"ftp".equals(url.getProtocol())) {
        return "not ftp protocol";
    }//from ww  w. ja  v  a 2s .  co m

    String host = url.getHost();
    String userInfo = url.getUserInfo();
    String path = url.getPath();
    String user = null;
    String pass = null;

    int p;
    if ((userInfo != null) && ((p = userInfo.indexOf(':')) > -1)) {
        user = userInfo.substring(0, p);
        pass = userInfo.substring(p + 1);
    } else {
        user = userInfo;
    }

    FTPClient ftp = new FTPClient();

    try {
        int reply;
        ftp.connect(host);

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return "connection refused";
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        return "could not connect to " + host;
    }

    try {
        if (!ftp.login(user, pass)) {
            ftp.logout();
            return "failed to login";
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        ftp.enterLocalPassiveMode();

        rcs = uploadFiles(ftp, path, files);

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        return "connection closed";
    } catch (IOException e) {
        return e.getMessage();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    return rcs;
}

From source file:ml.shifu.guagua.hadoop.util.HDPUtils.java

/**
 * Find a real file that contains file name in class path.
 * /*from   w  ww  .j a  v  a 2s.c  o  m*/
 * @param file
 *            name
 * @return real file name
 */
public static String findContainingFile(String fileName) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {
        Enumeration<URL> itr = null;
        // Try to find the class in registered jars
        if (loader instanceof URLClassLoader) {
            itr = ((URLClassLoader) loader).findResources(fileName);
        }
        // Try system classloader if not URLClassLoader or no resources found in URLClassLoader
        if (itr == null || !itr.hasMoreElements()) {
            itr = loader.getResources(fileName);
        }
        for (; itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();
            if ("file".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:ml.shifu.guagua.hadoop.util.HDPUtils.java

@SuppressWarnings("rawtypes")
public static String findContainingJar(Class my_class) {
    ClassLoader loader = my_class.getClassLoader();
    if (loader == null) {
        loader = Thread.currentThread().getContextClassLoader();
    }//from  w ww.  j  av a  2 s  .c  om
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    try {
        Enumeration<URL> itr = null;
        // Try to find the class in registered jars
        if (loader instanceof URLClassLoader) {
            itr = ((URLClassLoader) loader).findResources(class_file);
        }
        // Try system classloader if not URLClassLoader or no resources found in URLClassLoader
        if (itr == null || !itr.hasMoreElements()) {
            itr = loader.getResources(class_file);
        }
        for (; 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;
}