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.predic8.membrane.core.interceptor.rewrite.ReverseProxyingInterceptor.java

/**
 * handles "Destination" header (see RFC 2518 section 9.3; also used by WebDAV)
 *///from w w  w.  j av a2  s . c  o  m
@Override
public Outcome handleRequest(Exchange exc) throws Exception {
    if (exc.getRequest() == null)
        return Outcome.CONTINUE;
    String destination = exc.getRequest().getHeader().getFirstValue(Header.DESTINATION);
    if (destination == null)
        return Outcome.CONTINUE;
    if (!destination.contains("://"))
        return Outcome.CONTINUE; // local redirect (illegal by spec)
    // do not rewrite, if the client does not refer to the same host
    if (!isSameSchemeHostAndPort(getProtocol(exc) + "://" + exc.getRequest().getHeader().getHost(),
            destination))
        return Outcome.CONTINUE;
    // if we cannot determine the target hostname
    if (exc.getDestinations().isEmpty()) {
        // just remove the schema/hostname/port. this is illegal (by the spec),
        // but most clients understand it
        exc.getRequest().getHeader().setValue(Header.DESTINATION, new URL(destination).getFile());
        return Outcome.CONTINUE;
    }
    URL target = new URL(exc.getDestinations().get(0));
    // rewrite to our schema, host and port
    exc.getRequest().getHeader().setValue(Header.DESTINATION,
            Relocator.getNewLocation(destination, target.getProtocol(), target.getHost(),
                    target.getPort() == -1 ? target.getDefaultPort() : target.getPort()));
    return Outcome.CONTINUE;
}

From source file:net.sourceforge.jwbf.bots.HttpBot.java

/**
 * //  w  w w . j a  v  a 2 s . c  o  m
 * @param client
 *            if you whant to add some specials
 * @param u
 *            like http://www.yourOwnWiki.org/w/index.php
 * 
 */
protected final void setConnection(final HttpClient client, final URL u) {

    this.client = client;
    client.getParams().setParameter("http.useragent", "JWBF " + JWBF.getVersion());
    client.getHostConfiguration().setHost(u.getHost(), u.getPort(), u.getProtocol());
    cc = new HttpActionClient(client, u.getPath());

}

From source file:com.mirth.connect.connectors.http.HttpConnectorServlet.java

@Override
public ConnectionTestResponse testConnection(String channelId, String channelName,
        HttpDispatcherProperties properties) {
    try {// w ww.j a  v a 2  s  . c om
        URL url = new URL(replacer.replaceValues(properties.getHost(), channelId, channelName));
        int port = url.getPort();
        // If no port was provided, default to port 80 or 443.
        return ConnectorUtil.testConnection(url.getHost(),
                (port == -1) ? (StringUtils.equalsIgnoreCase(url.getProtocol(), "https") ? 443 : 80) : port,
                TIMEOUT);
    } catch (Exception e) {
        throw new MirthApiException(e);
    }
}

From source file:org.openremote.android.console.model.PollingHelper.java

/**
 * Request current status and start polling.
 *//*from  w w w .j  av  a 2  s. c o m*/
public void requestCurrentStatusAndStartPolling(Context context) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 50 * 1000);

    //make polling socket timout bigger than Controller (50s)
    HttpConnectionParams.setSoTimeout(params, 55 * 1000);

    client = new DefaultHttpClient(params);
    if (isPolling) {
        return;
    }

    try {
        URL uri = new URL(serverUrl);
        uri.toURI();
        if ("https".equals(uri.getProtocol())) {
            Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                    uri.getPort());
            client.getConnectionManager().getSchemeRegistry().register(sch);
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_CATEGORY, "Create URL fail:" + serverUrl);
        return;
    } catch (URISyntaxException e) {
        Log.e(LOG_CATEGORY, "Could not convert " + serverUrl + " to a compliant URI");
        return;
    }
    isPolling = true;
    handleRequest(serverUrl + "/rest/status/" + pollingStatusIds);
    while (isPolling) {
        doPolling();
    }
}

From source file:com.romeikat.datamessie.core.base.service.download.AbstractDownloader.java

protected String getProtocol(final String url) {
    final URL urlAsUrl;
    try {//w w w. jav  a2  s . c  o  m
        urlAsUrl = new URL(url);
    } catch (final Exception e) {
        return null;
    }

    final String protocol = urlAsUrl.getProtocol();
    return protocol;
}

From source file:com.impetus.kundera.classreading.ClasspathReader.java

/**
 * Scan class resource in the provided urls with the additional Class-Path
 * of each jar checking/*w  ww.  j av  a 2s  . co  m*/
 * 
 * @param classRelativePath
 *            relative path to a class resource
 * @param urls
 *            urls to be checked
 * @return list of class path included in the base package
 */
private URL[] findResourcesInUrls(String classRelativePath, URL[] urls) {
    List<URL> list = new ArrayList<URL>();
    for (URL url : urls) {
        if (AllowedProtocol.isValidProtocol(url.getProtocol().toUpperCase())
                && url.getPath().endsWith(".jar")) {
            try {
                JarFile jarFile = new JarFile(URLDecoder.decode(url.getFile(), Constants.CHARSET_UTF8));

                // Checking the dependencies of this jar file
                Manifest manifest = jarFile.getManifest();
                if (manifest != null) {
                    String classPath = manifest.getMainAttributes().getValue("Class-Path");
                    // Scan all entries in the classpath if they are
                    // specified in the jar
                    if (!StringUtils.isEmpty(classPath)) {
                        List<URL> subList = new ArrayList<URL>();
                        for (String cpEntry : classPath.split(" ")) {
                            try {
                                subList.add(new URL(cpEntry));
                            } catch (MalformedURLException e) {
                                URL subResources = ClasspathReader.class.getClassLoader().getResource(cpEntry);
                                if (subResources != null) {
                                    subList.add(subResources);
                                }
                                // logger.warn("Incorrect URL in the classpath of a jar file ["
                                // + url.toString()
                                // + "]: " + cpEntry);
                            }
                        }
                        list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath,
                                subList.toArray(new URL[subList.size()]))));
                    }
                }
                JarEntry present = jarFile.getJarEntry(classRelativePath + ".class");
                if (present != null) {
                    list.add(url);
                }
            } catch (IOException e) {
                logger.warn("Error during loading from context , Caused by:" + e.getMessage());
            }

        } else if (url.getPath().endsWith("/")) {
            File file = new File(url.getPath() + classRelativePath + ".class");
            if (file.exists()) {
                try {
                    list.add(file.toURL());
                } catch (MalformedURLException e) {
                    throw new ResourceReadingException(e);
                }
            }
        }

    }
    return list.toArray(new URL[list.size()]);
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.VitroURL.java

public VitroURL(String urlStr, String characterEncoding) {
    this.characterEncoding = characterEncoding;
    if (urlStr.indexOf("&amp;") > -1) {
        wasXMLEscaped = true;/*from   w ww  .  j a va 2 s . c om*/
        urlStr = StringEscapeUtils.unescapeXml(urlStr);
    }
    try {
        URL url = new URL(urlStr);
        this.protocol = url.getProtocol();
        this.host = url.getHost();
        this.port = Integer.toString(url.getPort());
        this.pathParts = splitPath(url.getPath());
        this.pathBeginsWithSlash = beginsWithSlash(url.getPath());
        this.pathEndsInSlash = endsInSlash(url.getPath());
        this.queryParams = parseQueryParams(url.getQuery());
        this.fragment = url.getRef();
    } catch (Exception e) {
        // Under normal circumstances, this is because the urlStr is relative
        // We'll assume that we just have a path and possibly a query string.
        // This is likely to be a bad assumption, but let's roll with it.
        Matcher m = pathPattern.matcher(urlStr);
        String[] urlParts = new String[2];
        if (m.matches()) {
            urlParts[0] = m.group(1);
            if (m.groupCount() == 2)
                urlParts[1] = m.group(2);
        } else {
            //???
        }

        try {
            this.pathParts = splitPath(URLDecoder.decode(getPath(urlStr), characterEncoding));
            this.pathBeginsWithSlash = beginsWithSlash(urlParts[0]);
            this.pathEndsInSlash = endsInSlash(urlParts[0]);
            if (urlParts.length > 1) {
                this.queryParams = parseQueryParams(URLDecoder.decode(urlParts[1], characterEncoding));
            }
        } catch (UnsupportedEncodingException uee) {
            log.error("Unable to use character encoding " + characterEncoding, uee);
        }
    }
}

From source file:com.celamanzi.liferay.portlets.rails286.HeadProcessor.java

protected HeadProcessor(String servlet, java.net.URL baseUrl, String namespace) {
    this.servlet = servlet;
    this.baseUrl = baseUrl;
    this.namespace = namespace;
    this.location = baseUrl.getProtocol() + "://" + baseUrl.getHost() + ":" + baseUrl.getPort() + servlet;
    log.debug("Initializing HeadProcessor @: " + this.location);
}

From source file:de.axelfaust.alfresco.nashorn.repo.loaders.AlfrescoClasspathURLStreamHandler.java

/**
 * {@inheritDoc}// ww  w  .j  a v a 2s .c  om
 */
@Override
protected URLConnection openConnection(final URL url) throws IOException {
    final String script;
    final boolean allowExtension = "extclasspath".equals(url.getProtocol());
    final boolean allowBase = !"rawclasspath".equals(url.getProtocol());
    if (allowBase && this.basePath != null && !this.basePath.trim().isEmpty()) {
        script = this.basePath + "/" + url.getPath();
    } else {
        script = url.getPath();
    }

    final List<String> precendenceChain = this.getOrCreatePrecedenceChain(script, allowExtension);

    URLConnection con = null;
    for (final String potentialScript : precendenceChain) {
        ScriptFile scriptFile = this.scriptHandles.get(potentialScript);
        if (scriptFile == null) {
            scriptFile = new ClasspathScriptFile(potentialScript);
            this.scriptHandles.put(potentialScript, scriptFile);
        }

        if (scriptFile.exists(false)) {
            con = new ScriptFileURLConnection(url, scriptFile);
            break;
        }
    }

    if (con == null) {
        throw new IOException("Script " + url + " does not exist");
    }

    return con;
}

From source file:it.tidalwave.bluemarine2.downloader.impl.SimpleHttpCacheStorage.java

/*******************************************************************************************************************
 *
 * //from   ww w  .j  a v a 2 s . c om
 *
 ******************************************************************************************************************/
@Nonnull
private Path getCacheItemPath(final @Nonnull URL url) throws MalformedURLException {
    final int port = url.getPort();
    final URL url2 = new URL(url.getProtocol(), url.getHost(), (port == 80) ? -1 : port, url.getFile());
    final Path cachePath = Paths.get(url2.toString().replaceAll(":", ""));
    return folderPath.resolve(cachePath);
}