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:com.portol.common.utils.Util.java

/**
 * Returns true if the URL points to a file on the local device
 *
 * @param url The URL to test/*from   w w w .j  a  va  2s  .c om*/
 */
public static boolean isUrlLocalFile(URL url) {
    return url.getProtocol().equals("file");
}

From source file:wuit.crawler.searcher.Crawler.java

public static void getUrlInfo(DSCrawlerUrl info) {
    try {/* www . j a  v a  2s .co  m*/
        URL _url = new URL(info.url);
        info.dns = _url.getHost() + "";
        info.path = _url.getPath();
        info.file = _url.getProtocol();
        if (!info.url.equals("") && info.url != null) {
            InetAddress a = InetAddress.getByName(_url.getHost());
            if (a != null)
                info.IP = a.getHostAddress();
        }
    } catch (Exception e) {
        System.out.println(" crawler   " + e.getMessage());
    }
}

From source file:org.openflamingo.uploader.util.ResourceUtils.java

/**
 *  ?  ? ? {@link java.io.File} ./* w w w . ja v  a 2  s .  co  m*/
 *
 * @param resourceUrl ? 
 * @param description ?  ?  (; ?  )
 * @return ?? {@link java.io.File} ?
 * @throws java.io.FileNotFoundException ?? ?   
 */
@SuppressWarnings({ "deprecation" })
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
    if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
        throw new FileNotFoundException(description
                + "?  ?  . ? ? ?    : "
                + resourceUrl);
    }
    return new File(URLDecoder.decode(resourceUrl.getFile()));
}

From source file:io.cloudine.rhq.plugins.worker.ResourceUtils.java

/**
 *  ?  ? ? {@link java.io.File} .// w w  w  . j  a va 2s .co  m
 *
 * @param resourceUrl ? 
 * @param description ?  ?  (; ?  )
 * @return ?? {@link java.io.File} ?
 * @throws java.io.FileNotFoundException ?? ?   
 */
@SuppressWarnings({ "deprecation" })
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
    if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
        String message = MessageFormatter
                .format("'{}' is not absolute path because does not exists.", description, resourceUrl)
                .getMessage();
        throw new FileNotFoundException(message);
    }
    return new File(URLDecoder.decode(resourceUrl.getFile()));
}

From source file:WarUtil.java

public static URL createURL(final URL baseURL, String relativeURL) {
    try {/*from  www.  j av a  2  s.c o m*/
        String protocol = baseURL.getProtocol();
        relativeURL = relativeURL.replace("\\", SLASH);
        // TODO
        if (protocol.startsWith(FILE_PROTOCOL)) {
            if (relativeURL.startsWith(SLASH)) {
                relativeURL = relativeURL.substring(1, relativeURL.length());
            }
            return new URL(baseURL, relativeURL);
        } else {
            // TODO
            String baseArchivePath = baseURL.toExternalForm();
            if (baseArchivePath.endsWith(SLASH)) {
                baseArchivePath = baseArchivePath.substring(0, baseArchivePath.length() - 1);
            }
            if (baseArchivePath.endsWith("!")) {
                baseArchivePath = baseArchivePath.substring(0, baseArchivePath.length() - 1);
            }
            if (!relativeURL.startsWith(SLASH)) {
                relativeURL = SLASH + relativeURL;
            }
            return new URL(baseArchivePath + "!" + relativeURL);
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.netflix.config.ClasspathPropertiesConfiguration.java

/**
 * Get the conventional name of the configuration that comes from from the
 * given URL./*from  w ww  . j a  va  2  s .  co  m*/
 */
private static String getConfigName(Properties props, URL propertyFile) {
    String name = props.getProperty(configNameProperty);
    if (name == null) {
        name = propertyFile.toExternalForm();
        name = name.replace('\\', '/'); // Windows
        final String scheme = propertyFile.getProtocol().toLowerCase();
        if ("jar".equals(scheme) || "zip".equals(scheme)) {
            // Use the unqualified name of the jar file.
            final int bang = name.lastIndexOf("!");
            if (bang >= 0) {
                name = name.substring(0, bang);
            }
            final int slash = name.lastIndexOf("/");
            if (slash >= 0) {
                name = name.substring(slash + 1);
            }
        } else {
            // Use the URL of the enclosing directory.
            final int slash = name.lastIndexOf("/");
            if (slash >= 0) {
                name = name.substring(0, slash);
            }
        }
    }
    return name;
}

From source file:com.qpark.eip.core.spring.security.https.HttpsRequester.java

private static String read(final URL url, final String httpAuthBase64, final HostnameVerifier hostnameVerifier)
        throws IOException {
    StringBuffer sb = new StringBuffer(1024);
    HttpURLConnection connection = null;
    connection = (HttpURLConnection) url.openConnection();
    if (url.getProtocol().equalsIgnoreCase("https")) {
        connection = (HttpsURLConnection) url.openConnection();
        ((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier);
    }//from ww  w . j a v a2  s  .c o m
    if (httpAuthBase64 != null) {
        connection.setRequestProperty("Authorization", new StringBuffer(httpAuthBase64.length() + 6)
                .append("Basic ").append(httpAuthBase64).toString());
    }
    connection.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
    connection.setRequestMethod("GET");

    int returnCode = connection.getResponseCode();
    InputStream connectionIn = null;
    if (returnCode == 200) {
        connectionIn = connection.getInputStream();
    } else {
        connectionIn = connection.getErrorStream();
    }
    BufferedReader buffer = new BufferedReader(new InputStreamReader(connectionIn));
    String inputLine;
    while ((inputLine = buffer.readLine()) != null) {
        sb.append(inputLine);
    }
    buffer.close();

    return sb.toString();
}

From source file:HttpTransactionUtils.java

/**
 * Format a base URL string ( protocol://server[:port][/file-specification] )
 * /*  ww w. j  a  v  a2  s  .  c  o m*/
 * @param url
 *          URL to format
 * @param preserveFile
 *          Keep the /directory/filename portion of the URL?
 * @return URL string
 */
public static String formatUrl(URL url, boolean preserveFile) throws MalformedURLException {
    StringBuilder result;
    int port;

    result = new StringBuilder(url.getProtocol());

    result.append("://");
    result.append(url.getHost());

    if ((port = url.getPort()) != -1) {
        result.append(":");
        result.append(String.valueOf(port));
    }

    if (preserveFile) {
        String file = url.getFile();

        if (file != null) {
            result.append(file);
        }
    }
    return result.toString();
}

From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java

private static long getLastModified(URL url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {//from  ww w.  jav  a 2s.c  o  m
        HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        Builder builder = RequestConfig.custom();
        HttpHost proxy = getProxy(target);
        if (proxy != null) {
            builder = builder.setProxy(proxy);
        }
        RequestConfig config = builder.build();
        HttpHead request = new HttpHead(url.toURI());
        request.setConfig(config);
        response = httpclient.execute(target, request);
        Header[] s = response.getHeaders("last-modified");
        if (s != null && s.length > 0) {
            String lastModified = s[0].getValue();
            return new Date(lastModified).getTime();
        }
    } catch (Exception e) {
        logWarning(e);
        return -1;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return -1;
}

From source file:de.unigoettingen.sub.commons.util.stream.StreamUtils.java

/************************************************************************************
 * get {@link InputStream} from given URL using a basis path and proxy informations
 * // w  w  w. jav a  2 s .com
 * @param url the url from where to get the {@link InputStream}
 * @param basepath the basispath
 * @param httpproxyhost the host for proxy
 * @param httpproxyport the port for proxy
 * @param httpproxyusername the username for the proxy
 * @param httpproxypassword the password for the proxy
 * @return {@link InputStream} for url
 * @throws IOException
 ************************************************************************************/
public static InputStream getInputStreamFromUrl(URL url, String basepath, String httpproxyhost,
        String httpproxyport, String httpproxyusername, String httpproxypassword) throws IOException {
    InputStream inStream = null;

    if (url.getProtocol().equalsIgnoreCase("http")) {
        if (httpproxyhost != null) {
            Properties properties = System.getProperties();
            properties.put("http.proxyHost", httpproxyhost);
            if (httpproxyport != null) {
                properties.put("http.proxyPort", httpproxyport);
            } else {
                properties.put("http.proxyPort", "80");
            }
        }
        URLConnection con = url.openConnection();
        if (httpproxyusername != null) {
            String login = httpproxyusername + ":" + httpproxypassword;
            String encodedLogin = new String(Base64.encodeBase64(login.getBytes()));
            con.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
        }
        inStream = con.getInputStream();
    } else if (url.getProtocol().equalsIgnoreCase("file")) {
        int size = url.openConnection().getContentLength();
        Integer maxFileLength = ContentServerConfiguration.getInstance().getMaxFileLength();

        if (maxFileLength != 0 && size > maxFileLength) {
            // System.out.println("File " + url.getFile() + " is too large (" + size + "/" + maxFileLength + ")");
            return getInputStreamFromUrl(new URL(ContentServerConfiguration.getInstance().getErrorFile()));
        }
        String filepath = url.getFile();

        filepath = URLDecoder.decode(filepath, System.getProperty("file.encoding"));

        File f = new File(filepath);
        if (!f.isFile()) {
            // try for a file with different suffix case
            int suffixIndex = filepath.lastIndexOf('.');
            f = new File(filepath.substring(0, suffixIndex) + filepath.substring(suffixIndex).toLowerCase());
            if (!f.isFile()) {
                f = new File(
                        filepath.substring(0, suffixIndex) + filepath.substring(suffixIndex).toUpperCase());
            }
            // search all files in this directory for this case-insensitive name
            if (!f.isFile()) {
                File[] files = f.getParentFile().listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.getName().compareToIgnoreCase(f.getName()) == 0) {
                            f = file;
                            break;
                        }
                    }
                }
            }
        }
        inStream = new FileInputStream(f);

    } else if (url.getProtocol().length() == 0) {
        String filepath = url.getFile();
        // we just have the relative path, need to find the absolute path
        String path = basepath + filepath;

        // call this method again
        URL completeurl = new URL(path);
        inStream = getInputStreamFromUrl(completeurl);
    }

    return inStream;
}