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:org.wso2.carbon.apimgt.gateway.throttling.util.BlockingConditionRetriever.java

/**
 * This method will retrieve blocking conditions by calling a WebService.
 *
 * @return String object array which contains throttled keys.
 *//* www. j  a v  a 2  s  .c om*/
private BlockConditionsDTO retrieveBlockConditionsData() {

    try {
        ThrottleProperties.BlockCondition blockConditionRetrieverConfiguration = ServiceReferenceHolder
                .getInstance().getThrottleProperties().getBlockCondition();
        String url = blockConditionRetrieverConfiguration.getServiceUrl() + "/block";
        byte[] credentials = Base64.encodeBase64((blockConditionRetrieverConfiguration.getUsername() + ":"
                + blockConditionRetrieverConfiguration.getPassword()).getBytes(StandardCharsets.UTF_8));
        HttpGet method = new HttpGet(url);
        method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
        URL keyMgtURL = new URL(url);
        int keyMgtPort = keyMgtURL.getPort();
        String keyMgtProtocol = keyMgtURL.getProtocol();
        HttpClient httpClient = APIUtil.getHttpClient(keyMgtPort, keyMgtProtocol);
        HttpResponse httpResponse = null;
        int retryCount = 0;
        boolean retry;
        do {
            try {
                httpResponse = httpClient.execute(method);
                retry = false;
            } catch (IOException ex) {
                retryCount++;
                if (retryCount < blockConditionsDataRetrievalRetries) {
                    retry = true;
                    log.warn("Failed retrieving Blocking Conditions from remote endpoint: " + ex.getMessage()
                            + ". Retrying after " + blockConditionsDataRetrievalTimeoutInSeconds
                            + " seconds...");
                    Thread.sleep(blockConditionsDataRetrievalTimeoutInSeconds * 1000);
                } else {
                    throw ex;
                }
            }
        } while (retry);

        String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        if (responseString != null && !responseString.isEmpty()) {
            return new Gson().fromJson(responseString, BlockConditionsDTO.class);
        }
    } catch (IOException | InterruptedException e) {
        log.error("Exception when retrieving Blocking Conditions from remote endpoint ", e);
    }
    return null;
}

From source file:com.gargoylesoftware.htmlunit.CookieManager.java

/**
 * {@link org.apache.commons.httpclient.cookie.CookieSpec#match(String, int, String, boolean, Cookie[])} doesn't
 * like empty hosts and negative ports, but these things happen if we're dealing with a local file. This method
 * allows us to work around this limitation in HttpClient by feeding it a bogus host and port.
 *
 * @param url the URL to replace if necessary
 * @return the replacement URL, or the original URL if no replacement was necessary
 *//*  ww  w .jav  a 2s  . c  om*/
public URL replaceForCookieIfNecessary(URL url) {
    final String protocol = url.getProtocol();
    final boolean file = "file".equals(protocol);
    if (file) {
        try {
            url = UrlUtils.getUrlWithNewHostAndPort(url,
                    HtmlUnitBrowserCompatCookieSpec.LOCAL_FILESYSTEM_DOMAIN, 0);
        } catch (final MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
    return url;
}

From source file:cn.homecredit.web.listener.MyOsgiHost.java

protected String getVersion(URL url) {
    if ("jar".equals(url.getProtocol())) {
        try {//from ww  w  .  j a v a 2s .com
            JarFile jarFile = new JarFile(new File(URLUtil.normalizeToFileProtocol(url).toURI()));
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (StringUtils.isNotBlank(version)) {
                    return getVersionFromString(version);
                }
            } else {
                //try to get the version from the file name
                return getVersionFromString(jarFile.getName());
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Unable to extract version from [#0], defaulting to '1.0.0'", url.toExternalForm());
            }
        }
    }
    return "1.0.0";
}

From source file:com.ibm.mf.geofence.demo.SlackHTTPService.java

@Override
protected Uri getBaseQueryURI() throws Exception {
    URL url = new URL(getServerURL());
    int port = url.getPort();
    String portStr = (port < 0) ? "" : ":" + port;
    Uri.Builder builder = new Uri.Builder().scheme(url.getProtocol()).encodedAuthority(url.getHost() + portStr);
    return builder.build();
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlMeta.java

/**
 * Handles the cookies specified in meta tags,
 * like <tt>&lt;meta http-equiv='set-cookie' content='webm=none; path=/;'&gt;</tt>.
 *//*from   w w w . j a  v a  2 s. c o m*/
protected void performSetCookie() {
    final String[] parts = COOKIES_SPLIT_PATTERN.split(getContentAttribute(), 0);
    final String name = StringUtils.substringBefore(parts[0], "=");
    final String value = StringUtils.substringAfter(parts[0], "=");
    final URL url = getPage().getUrl();
    final String host = url.getHost();
    final boolean secure = "https".equals(url.getProtocol());
    String path = null;
    Date expires = null;
    for (int i = 1; i < parts.length; i++) {
        final String partName = StringUtils.substringBefore(parts[i], "=").trim().toLowerCase();
        final String partValue = StringUtils.substringAfter(parts[i], "=").trim();
        if ("path".equals(partName)) {
            path = partValue;
        } else if ("expires".equals(partName)) {
            expires = com.gargoylesoftware.htmlunit.util.StringUtils.parseHttpDate(partValue);
        } else {
            notifyIncorrectness("set-cookie http-equiv meta tag: unknown attribute '" + partName + "'.");
        }
    }
    final Cookie cookie = new Cookie(host, name, value, path, expires, secure);
    getPage().getWebClient().getCookieManager().addCookie(cookie);
}

From source file:com.asual.summer.core.faces.FacesResourceResolver.java

public URL resolveUrl(String path) {
    if (!resources.containsKey(path)) {
        URL url = ResourceUtils
                .getClasspathResource("/".equals(path) ? "META-INF/" : path.replaceAll("^/", ""));
        if (url != null) {
            try {
                url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile(),
                        new FacesStreamHandler(url));
            } catch (AccessControlException e) {
            } catch (NoClassDefFoundError e) {
            } catch (MalformedURLException e) {
                throw new FacesException(e);
            }/*  ww  w. j a  v  a 2 s  .co m*/
        } else {
            logger.warn("The requested resource [" + path + "] cannot be resolved.");
        }
        resources.put(path, url);
    }
    return resources.get(path);
}

From source file:io.fabric8.maven.core.handler.ProbeHandler.java

private HTTPGetAction getHTTPGetAction(String getUrl) {
    if (getUrl == null || !getUrl.subSequence(0, 4).toString().equalsIgnoreCase("http")) {
        return null;
    }//from w  w w.  j  a  v a2s.co m
    try {
        URL url = new URL(getUrl);
        return new HTTPGetAction(url.getHost(), null /* headers */, url.getPath(),
                new IntOrString(url.getPort()), url.getProtocol());
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Invalid URL " + getUrl + " given for HTTP GET readiness check");
    }
}

From source file:io.fabric8.maven.enricher.fabric8.DocLinkEnricher.java

protected String findDocumentationUrl() {
    DistributionManagement distributionManagement = findProjectDistributionManagement();
    if (distributionManagement != null) {
        Site site = distributionManagement.getSite();
        if (site != null) {
            String url = site.getUrl();
            if (StringUtils.isNotBlank(url)) {
                // lets replace any properties...
                MavenProject project = getProject();
                if (project != null) {
                    url = replaceProperties(url, project.getProperties());
                }/*  w  ww  .j av  a2s.co  m*/

                // lets convert the internal dns name to a public name
                try {
                    String urlToParse = url;
                    int idx = url.indexOf("://");
                    if (idx > 0) {
                        // lets strip any previous schemes such as "dav:"
                        int idx2 = url.substring(0, idx).lastIndexOf(':');
                        if (idx2 >= 0 && idx2 < idx) {
                            urlToParse = url.substring(idx2 + 1);
                        }
                    }
                    URL u = new URL(urlToParse);
                    String serviceName = u.getHost();
                    String protocol = u.getProtocol();
                    if (isOnline()) {
                        // lets see if the host name is a service name in which case we'll resolve to the public URL
                        String publicUrl = getExternalServiceURL(serviceName, protocol);
                        if (StringUtils.isNotBlank(publicUrl)) {
                            return String.format("%s/%s", publicUrl, u.getPath());
                        }
                    }
                } catch (MalformedURLException e) {
                    getLog().error("Failed to parse URL: %s. %s", url, e);
                }
                return url;
            }
        }
    }
    return null;
}

From source file:org.apache.mina.springrpc.MinaClientInterceptor.java

private URL getURL() throws MalformedURLException {
    URL url = new URL(null, getServiceUrl(), new DummyURLStreamHandler());
    String protocol = url.getProtocol();
    if (protocol != null && !"tcp".equals(protocol)) {
        throw new MalformedURLException("Invalid URL scheme '" + protocol + "'");
    }//from  www  . ja v  a 2  s .c o m
    return url;
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java

public AvaticaCommonsHttpClientImpl(URL url) {
    this.host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    this.uri = toURI(Objects.requireNonNull(url));
    initializeClient();//from  w  w w  .  jav  a2  s . c om
}