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.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * Gets an absolute path to CKFinder file or folder for which path was provided as parameter.
 *
 * @param path relative or absolute path to a CKFinder resource (file or folder).
 * @param isAbsolute flag indicating if path to resource is absolute e.g. /usr/john/userfiles or "C:\\userfiles". If this parameter is
 * set to true path will be returned as is.
 * @param shouldExist flag indicating if resource, represented by path parameter, should exist (e.g. configuration file) in file system
 * or not (e.g. userfiles folder).<br>
 * If this parameter is set to true, path to file will only be returned if such file exists. If file can't be found, method will return
 * null./*from   w  w w .  ja v a 2  s. com*/
 * @return an absolute path to a resource in CKFinder
 * @throws ConnectorException when {@code ServletContext} is {@code null} or full path to resource cannot be obtained.
 */
public static String getFullPath(String path, boolean isAbsolute, boolean shouldExist)
        throws ConnectorException {
    if (path != null && !path.equals("")) {
        if (isAbsolute) {
            if (path.startsWith("/")) {
                //Check if this isn't Windows Path.
                String temporary = PathUtils.removeSlashFromBeginning(path);
                if (isStartsWithPattern(drivePatt, temporary)) {
                    path = temporary;
                }
            }
            return checkAndReturnPath(shouldExist, path);
        } else {
            ServletContext sc = ServletContextFactory.getServletContext();
            String tempPath = PathUtils.addSlashToEnd(PathUtils.addSlashToBeginning(path));
            try {
                java.net.URL url = sc.getResource(tempPath);
                //For srevers like Tomcat 6-7 the getResource method returns JNDI URL.
                if (url != null && url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("jndi")) {
                    //Assume file is inside application context and try to get path.
                    //This method will fail if war is not exploaded.
                    String result = sc.getRealPath(tempPath.replace(sc.getContextPath(), ""));
                    if (result != null) {
                        return result;
                    } else {
                        //If application is packed, we have to try constructing the path manually.
                        result = getClassPath();
                        if (tempPath.indexOf(sc.getContextPath() + "/") >= 0
                                && result.indexOf(sc.getContextPath() + "/") >= 0) {
                            result = result.substring(0, result.indexOf(sc.getContextPath()));
                            result = result + tempPath;
                        } else if (result.indexOf(sc.getContextPath() + "/") >= 0) {
                            result = result.substring(0,
                                    result.indexOf(sc.getContextPath()) + sc.getContextPath().length());
                            result = result + tempPath;
                        }

                        result = checkAndReturnPath(shouldExist, result);
                        if (result != null) {
                            return result;
                        }
                    }

                    //At this stage path is not in application context and is not absolute.
                    //We need to reset url as we cannot determine path from it.
                    if (result == null) {
                        url = null;
                    }
                }

                //For servers like Tomact 8 getResource method should return file:// url.
                if (path.startsWith("/") || isStartsWithPattern(drivePatt, path)) {
                    //This is most likely absolute path.
                    String absolutePath = checkAndReturnPath(shouldExist, path);
                    if (absolutePath != null && !absolutePath.equals("")) {
                        return absolutePath;
                    } else {
                        //If absolute path has failed, give it one last try with relative path.
                        //Either path or null will be returned.
                        return sc.getRealPath(path.replace(sc.getContextPath(), ""));
                    }
                }
            } catch (IOException ioex) {
                throw new ConnectorException(ioex);
            }
        }
    }
    return null;
}

From source file:com.alu.e3.gateway.loadbalancer.E3HttpClientConfigurer.java

/**
 * Converts a TargetHost to an HttpRoute 
 * @param targetHost the target host to transform
 * @return HttpRoute HTTP route/*  ww  w.j ava 2  s .  c  o m*/
 * @throws MalformedURLException
 */
private HttpRoute getHttpRoute(TargetHost targetHost) throws MalformedURLException {

    HttpRoute route = null;

    URL url = new URL(targetHost.getUrl());

    boolean secured = url.getProtocol().equalsIgnoreCase(HTTP_SECURED_PROTOCOL);

    if (forwardProxy != null) {

        Integer proxyPort = Integer.parseInt(forwardProxy.getProxyPort());
        String proxyHost = forwardProxy.getProxyHost();

        route = new HttpRoute(new HttpHost(url.getHost(), url.getPort()), null,
                new HttpHost(proxyHost, proxyPort), secured);
    } else {

        route = new HttpRoute(new HttpHost(url.getHost(), url.getPort()), null, secured);
    }

    return route;
}

From source file:org.openremote.android.console.util.AsyncGroupLoader.java

@Override
public void run() {
    synchronized (this) {
        String server = AppSettingsModel.getSecuredServer(context);
        if (!TextUtils.isEmpty(server)) {
            HttpResponse response = null;
            try {
                URL url = new URL(server + "/rest/device/group");
                HttpGet request = new HttpGet(url.toString());
                HttpClient client = new DefaultHttpClient();
                Scheme sch = new Scheme(url.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                        url.getPort());//from  w  w  w  . j  a  v a2  s  .c o m
                client.getConnectionManager().getSchemeRegistry().register(sch);

                response = client.execute(request);
            } catch (ClientProtocolException e) {
                Log.e(LOG_CATEGORY + " run:", e.getMessage());
            } catch (IOException e) {
                Log.e(LOG_CATEGORY + " run:", e.getMessage());
            }

            String group = "";
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                String tmp;
                try {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));
                    while ((tmp = in.readLine()) != null) {
                        group += tmp;
                    }
                } catch (IOException e) {
                    Log.e(LOG_CATEGORY + " urlConnectionDidReceiveData:", e.getMessage());
                }

            }
            AppSettingsModel.setGroup(context, group);
        }
        done = true;
        notify();
    }
}

From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java

private String requestEncoding() throws IOException {
    URI uri;//w  w w.  ja  va2s  .c  o m
    try {
        URL localUrl = new URL(url);
        uri = new URI(localUrl.getProtocol(), null, localUrl.getHost(), localUrl.getPort(), "/api/datasets",
                "name=" + dataSetName + "&tag=components", null);
        LOGGER.debug("Request is: {}", uri);
    } catch (MalformedURLException | URISyntaxException e) {
        LOGGER.debug(messages.getMessage("error.wrongInputParameters", e));
        throw new IOException(messages.getMessage("error.wrongInputParameters", e));
    }
    return uri.toString();
}

From source file:org.eclipse.skalli.core.destination.DestinationComponent.java

private void setProxy(HttpClient client, URL url) {
    if (isLocalDomain(url)) {
        return;/* w  w  w.  jav  a 2  s  .c  o  m*/
    }

    String protocol = url.getProtocol();

    // use the system properties as default
    String defaultProxyHost = System.getProperty(HTTP_PROXY_HOST);
    String defaultProxyPort = System.getProperty(HTTP_PROXY_PORT);
    String proxyHost = HTTPS.equals(protocol) ? System.getProperty(HTTPS_PROXY_HOST, defaultProxyHost)
            : defaultProxyHost;
    int proxyPort = NumberUtils.toInt(
            HTTPS.equals(protocol) ? System.getProperty(HTTPS_PROXY_PORT, defaultProxyPort) : defaultProxyPort);
    String nonProxyHosts = System.getProperty(NON_PROXY_HOSTS, StringUtils.EMPTY);

    // allow to overwrite the system properties with configuration /api/config/proxy
    if (configService != null) {
        ProxyConfig proxyConfig = configService.readConfiguration(ProxyConfig.class);
        if (proxyConfig != null) {
            String defaultConfigProxyHost = proxyConfig.getHost();
            String defaultConfigProxyPort = proxyConfig.getPort();
            String configProxyHost = HTTPS.equals(protocol) ? proxyConfig.getHostSSL() : defaultConfigProxyHost;
            int configProxyPort = NumberUtils
                    .toInt(HTTPS.equals(protocol) ? proxyConfig.getPortSSL() : defaultConfigProxyPort);
            if (StringUtils.isNotBlank(configProxyHost) && configProxyPort > 0) {
                proxyHost = configProxyHost;
                proxyPort = configProxyPort;
            }
            String configNonProxyHosts = proxyConfig.getNonProxyHosts();
            if (StringUtils.isNotBlank(configNonProxyHosts)) {
                nonProxyHosts = configNonProxyHosts;
            }
        }
    }

    // sanitize the nonProxyHost pattern (remove whitespace etc.)
    if (StringUtils.isNotBlank(nonProxyHosts)) {
        nonProxyHosts = StringUtils.replaceEach(StringUtils.deleteWhitespace(nonProxyHosts), RE_SEARCH,
                RE_REPLACE);
    }

    if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0 && !Pattern.matches(nonProxyHosts, url.getHost())) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort, HTTP);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
}

From source file:com.oakesville.mythling.util.MediaStreamProxy.java

private HttpResponse download() throws IOException {

    httpClient = AndroidHttpClient.newInstance("Android");
    // httpClient.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost("127.0.0.1"));

    URL netUrl = proxyInfo.netUrl;
    HttpHost host = new HttpHost(netUrl.getHost(), netUrl.getPort(), netUrl.getProtocol());

    HttpRequestBase request = new HttpGet(netUrl.toString());
    HttpResponse response = null;/*  ww w. j ava2  s.  c  o  m*/
    Log.d(TAG, "Proxy starting download");
    if (authType == AuthType.Digest) {
        HttpContext context = HttpHelper.getDigestAuthContext(netUrl.getHost(), netUrl.getPort(),
                proxyInfo.user, proxyInfo.password);
        response = httpClient.execute(host, request, context);
    } else if (authType == AuthType.Basic) {
        String credentials = Base64.encodeToString((proxyInfo.user + ":" + proxyInfo.password).getBytes(),
                Base64.DEFAULT);
        request.setHeader("Authorization", "Basic " + credentials);
        response = httpClient.execute(host, request);
    } else {
        response = httpClient.execute(host, request);
    }
    Log.d(TAG, "Proxy response downloaded");
    return response;
}

From source file:com.adaptris.core.AbstractMarshaller.java

/**
 * @see AdaptrisMarshaller#marshal(java.lang.Object, java.net.URL)
 *///from w w  w . ja v a  2 s.com
@Override
public void marshal(Object obj, URL fileUrl) throws CoreException {
    if (obj == null || fileUrl == null) {
        throw new IllegalArgumentException("Cannot marshall to a null URL");
    }

    if (!fileUrl.getProtocol().equals("file")) { // URL can only be file
        throw new CoreException("URL protocol must be file:");
    }

    this.marshal(obj, new File(fileUrl.getFile()));
}

From source file:Main.java

/**
 * Returns <code>true</code> if the URL represents a path, and 
 * <code>false</code> otherwise.
 * /*from   w  w w.  ja va 2 s. co m*/
 * @param baseURL  the URL.
 * 
 * @return A boolean.
 */
private boolean isPath(final URL baseURL) {
    if (getPath(baseURL).endsWith("/")) {
        return true;
    } else if (baseURL.getProtocol().equals("file")) {
        final File f = new File(getPath(baseURL));
        try {
            if (f.isDirectory()) {
                return true;
            }
        } catch (SecurityException se) {
            // ignored ...
        }
    }
    return false;
}

From source file:fr.gael.dhus.datastore.scanner.ScannerFactory.java

private String showPublicURL(URL url) {
    String protocol = url.getProtocol();
    String host = url.getHost();/* ww w  .java  2  s.  co  m*/
    int port = url.getPort();
    String path = url.getFile();
    if (protocol == null)
        protocol = "";
    else
        protocol += "://";

    String s_port = "";
    if (port != -1)
        s_port = ":" + port;

    return protocol + host + s_port + path;
}