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:it.geosolutions.geostore.core.security.password.URLMasterPasswordProvider.java

/**
 * Writes the master password in the file
 * @param url/*  w w  w.j  a v  a2s .  c om*/
 * @param configDir
 * @return
 * @throws IOException
 */
static OutputStream output(URL url, File configDir) throws IOException {
    //check for file URL
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        File f;
        try {
            f = new File(url.toURI());
        } catch (URISyntaxException e) {
            f = new File(url.getPath());
        }
        if (!f.isAbsolute()) {
            //make relative to config dir
            f = new File(configDir, f.getPath());
        }
        return new FileOutputStream(f);
    } else {
        URLConnection cx = url.openConnection();
        cx.setDoOutput(true);
        return cx.getOutputStream();
    }
}

From source file:WarUtil.java

public static boolean isResourceExist(URL resource) {
    if (resource.getProtocol().equals(FILE_PROTOCOL)) {
        try {/*from  w  w w . j  av a  2s .  c o m*/
            File file = new File(resource.toURI());
            return file.exists();
        } catch (URISyntaxException e) {
            return false;
        }
    }
    InputStream is = null;
    try {
        is = resource.openStream();
        return (is != null);
    } catch (Exception ioe) {
        return false;
    }
}

From source file:jp.go.nict.langrid.management.logic.service.HttpClientUtil.java

/**
 * // w ww  . ja  v  a  2s  .c  om
 * 
 */
public static HttpClient createHttpClientWithHostConfig(URL url) {
    HttpClient client = new HttpClient();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
        if (port == -1) {
            port = 80;
        }
    }
    if ((url.getProtocol().equalsIgnoreCase("https")) && (sslSocketFactory != null)) {
        Protocol https = new Protocol("https",
                (ProtocolSocketFactory) new SSLSocketFactorySSLProtocolSocketFactory(sslSocketFactory), port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), https);
    } else {
        Protocol http = new Protocol("http", new SocketFactoryProtocolSocketFactory(SocketFactory.getDefault()),
                port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), http);
    }
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
        for (Proxy p : proxies) {
            if (p.equals(Proxy.NO_PROXY))
                continue;
            if (!p.type().equals(Proxy.Type.HTTP))
                continue;
            InetSocketAddress addr = (InetSocketAddress) p.address();
            client.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
            break;
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return client;
}

From source file:com.bfd.harpc.common.configure.PathUtils.java

/**
 * Normalize the path by suppressing sequences like "path/.." and inner
 * simple dots./*from  w w  w . ja va2s. com*/
 * <p>
 * The result is convenient for path comparison. For other uses, notice that
 * Windows separators ("\") are replaced by simple slashes.
 * 
 * @param originalUrl
 *            the url with original path
 * @return the url with normalized path
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
public static URL cleanPath(URL originalUrl) throws MalformedURLException, URISyntaxException {
    String path = originalUrl.toString();
    if (StringUtils.isEmpty(path)) {
        return null;
    }
    URL curl = new URL(cleanPath(path));
    // curl.toURI().getPath()?
    return new URL(curl.getProtocol(), curl.getHost(), curl.toURI().getPath());
}

From source file:com.xiongyingqi.util.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 WebLogic Server and WebSphere, respectively,
 * but can be treated like jar files.//from   www . j a  v a2  s. c  om
 *
 * @param url the URL to check
 * @return whether the URL has been identified as a JAR URL
 */
public static boolean isJarURL(URL url) {
    String up = url.getProtocol();
    return (URL_PROTOCOL_JAR.equals(up) || URL_PROTOCOL_ZIP.equals(up) || URL_PROTOCOL_WSJAR.equals(up));
}

From source file:spark.utils.ResourceUtils.java

/**
 * Determine whether the given URL points to a resource in the file system,
 * that is, has protocol "file" or "vfs".
 *
 * @param url the URL to check//from  ww w  .  j  a  v a 2s .  c o  m
 * @return whether the URL has been identified as a file system URL
 */
public static boolean isFileURL(URL url) {
    String protocol = url.getProtocol();
    return (URL_PROTOCOL_FILE.equals(protocol));
}

From source file:jp.terasoluna.fw.batch.unit.util.ClassLoaderUtils.java

/**
 * <pre>//from   w  w  w  .j  a  v  a  2  s  .c o  m
 * srcPaths??????????
 * ??????
 * ????destPaths????
 * </pre>
 * 
 * @param destPaths
 * @param srcPaths
 */
public static void addPathIfExists(List<String> destPaths, List<String> srcPaths) {
    Assert.notNull(destPaths);
    Assert.notNull(srcPaths);

    ClassLoader cl = getClassLoader();
    for (String path : srcPaths) {
        if (path != null) {
            URL r = cl.getResource(path);
            if (r != null) {
                try {
                    String protocol = r.getProtocol();
                    if (protocol.equals("file")) {
                        URI uri = r.toURI();
                        File f = new File(uri);
                        if (f.isFile()) {
                            // ?????
                            destPaths.add(path);
                        }
                    } else {
                        // jar
                        URLConnection con = null;
                        try {
                            con = r.openConnection();
                            if (con.getContentLength() > 0) {
                                // ?????
                                destPaths.add(path);
                            }
                        } catch (IOException e) {
                            // ?????????
                            LOG.warn(con + " is illegal.", e);
                        }
                    }
                } catch (URISyntaxException e) {
                    // r != null???????????????
                    LOG.warn(path + " is illegal.", e);
                }
            } else {
                LOG.debug(path + " is not found.");
            }
        }
    }
}

From source file:crow.weibo.util.WeiboUtil.java

/**
 * ?URL,URL Path URL ???//w w w.  j  a v a 2 s .  co  m
 * 
 * @param url
 * @return
 */
public static String getNormalizedUrl(String url) {
    try {
        URL ul = new URL(url);
        StringBuilder buf = new StringBuilder();
        buf.append(ul.getProtocol());
        buf.append("://");
        buf.append(ul.getHost());
        if ((ul.getProtocol().equals("http") || ul.getProtocol().equals("https")) && ul.getPort() != -1) {
            buf.append(":");
            buf.append(ul.getPort());
        }
        buf.append(ul.getPath());
        return buf.toString();
    } catch (Exception e) {
    }
    return null;
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.intragrid.HttpClientUtil.java

/**
 * //from   w  ww.  j  av  a  2 s  .  c o  m
 * 
 */
public static HttpClient createHttpClientWithHostConfig(URL url) {
    HttpClient client = new HttpClient();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
        if (port == -1) {
            port = 80;
        }
    }
    if ((url.getProtocol().equalsIgnoreCase("https")) && (sslSocketFactory != null)) {
        Protocol https = new Protocol("https",
                (ProtocolSocketFactory) new SSLSocketFactorySSLProtocolSocketFactory(sslSocketFactory), port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), https);
    } else {
        Protocol http = new Protocol("http", new SocketFactoryProtocolSocketFactory(SocketFactory.getDefault()),
                port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), http);
    }
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
        for (Proxy p : proxies) {
            if (p.equals(Proxy.NO_PROXY))
                continue;
            if (!p.type().equals(Proxy.Type.HTTP))
                continue;
            InetSocketAddress addr = (InetSocketAddress) p.address();
            client.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
            client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", ""));
            break;
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return client;
}

From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken)
        throws URISyntaxException, UnsupportedEncodingException {
    String host = msgRequest.getTargetHost();
    if (host == null)
        throw new URISyntaxException(host, "null URI");
    if (!host.endsWith("/"))
        host += '/';
    String address = msgRequest.getTargetAddress();
    if (address == null)
        address = "";
    if (address.startsWith("/"))
        address = address.substring(1);//from   w  w  w  .j a va 2  s.c o m
    String uriString = host + address;
    try {
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (MalformedURLException e) {
        throw new URISyntaxException(uriString, e.getMessage());
    }
    if (msgRequest.getQuery() != null)
        uriString += "?" + msgRequest.getQuery();

    //      new URI(uriString);

    HttpRequestBase request = null;
    if (msgRequest.getMethod().equals(Method.POST)) {
        HttpPost post = new HttpPost(uriString);
        HttpEntity httpEntity = null;
        if (msgRequest.getRequestParams() != null) {
            // if body and requestparams are either not null there is an
            // exception
            if (msgRequest.getBody() != null && msgRequest != null) {
                throw new IllegalArgumentException("body and requestParams cannot be either populated");
            }
            httpEntity = new MultipartEntity();

            for (RequestParam param : msgRequest.getRequestParams()) {
                if (param.getParamName() == null || param.getParamName().trim().length() == 0) {
                    throw new IllegalArgumentException("paramName cannot be null or empty");
                }
                if (param instanceof FileRequestParam) {
                    FileRequestParam fileparam = (FileRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody(
                            fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename()));
                }
                if (param instanceof ObjectRequestParam) {
                    ObjectRequestParam objectparam = (ObjectRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(),
                            new StringBody(convertObject(objectparam.getVars())));
                }
            }
            // mpe.addPart("file",
            // new ByteArrayBody(msgRequest.getFileContent(), ""));
            // post.setEntity(mpe);
        }
        if (msgRequest.getBody() != null) {
            httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            ((StringEntity) httpEntity).setContentType(msgRequest.getContentType());
        }
        post.setEntity(httpEntity);
        request = post;
    } else if (msgRequest.getMethod().equals(Method.PUT)) {
        HttpPut put = new HttpPut(uriString);
        if (msgRequest.getBody() != null) {
            StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            se.setContentType(msgRequest.getContentType());
            put.setEntity(se);
        }
        request = put;
    } else if (msgRequest.getMethod().equals(Method.DELETE)) {
        request = new HttpDelete(uriString);
    } else {
        // default: GET
        request = new HttpGet(uriString);
    }

    Map<String, String> headers = new HashMap<String, String>();

    // default headers
    if (appToken != null) {
        headers.put(RequestHeader.APP_TOKEN.toString(), appToken);
    }
    if (authToken != null) {
        // is here for compatibility
        headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken);
        headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken);
    }
    headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType());

    if (msgRequest.getCustomHeaders() != null) {
        headers.putAll(msgRequest.getCustomHeaders());
    }

    for (String key : headers.keySet()) {
        request.addHeader(key, headers.get(key));
    }

    return request;
}