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.jboss.jdf.stacks.client.StacksClient.java

private InputStream retrieveStacksFromRemoteRepository(final URL url) throws Exception {
    if (url.getProtocol().startsWith("http")) {
        HttpGet httpGet = new HttpGet(url.toURI());
        DefaultHttpClient client = new DefaultHttpClient();
        configureProxy(client);/*  w  w  w.  java  2s.  c o  m*/
        HttpResponse httpResponse = client.execute(httpGet);
        switch (httpResponse.getStatusLine().getStatusCode()) {
        case 200:
            msg.showDebugMessage("Connected to repository! Getting available Stacks");
            break;

        case 404:
            msg.showErrorMessage("Failed! (Stacks file not found: " + url + ")");
            return null;

        default:
            msg.showErrorMessage(
                    "Failed! (server returned status code: " + httpResponse.getStatusLine().getStatusCode());
            return null;
        }
        return httpResponse.getEntity().getContent();
    } else if (url.getProtocol().startsWith("file")) {
        return new FileInputStream(new File(url.toURI()));
    }
    return null;
}

From source file:com.hp.autonomy.searchcomponents.hod.view.HodViewServerService.java

@Override
public void viewDocument(final String reference, final ResourceIdentifier index,
        final OutputStream outputStream) throws IOException, HodErrorException {
    final GetContentRequestBuilder getContentParams = new GetContentRequestBuilder().setPrint(Print.all);
    final Documents<Document> documents = getContentService.getContent(Collections.singletonList(reference),
            index, getContentParams);/* ww  w. j  av a2s.c  om*/

    // This document will always exist because the GetContentService.getContent throws a HodErrorException if the
    // reference doesn't exist in the index
    final Document document = documents.getDocuments().get(0);

    final Map<String, Serializable> fields = document.getFields();
    final Object urlField = fields.get(URL_FIELD);

    final String documentUrl = urlField instanceof List ? ((List<?>) urlField).get(0).toString()
            : document.getReference();

    final UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES);
    InputStream inputStream = null;

    try {
        try {
            final URL url = new URL(documentUrl);
            final URI uri = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);
            final String encodedUrl = uri.toASCIIString();

            if (urlValidator.isValid(encodedUrl)) {
                inputStream = viewDocumentService.viewUrl(encodedUrl, new ViewDocumentRequestBuilder());
            } else {
                throw new URISyntaxException(encodedUrl, "Invalid URL");
            }
        } catch (URISyntaxException | MalformedURLException e) {
            // URL was not valid, fall back to using the document content
            inputStream = formatRawContent(document);
        } catch (final HodErrorException e) {
            if (e.getErrorCode() == HodErrorCode.BACKEND_REQUEST_FAILED) {
                // HOD failed to read the url, fall back to using the document content
                inputStream = formatRawContent(document);
            } else {
                throw e;
            }
        }

        IOUtils.copy(inputStream, outputStream);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.iflytek.spider.net.BasicURLNormalizer.java

public String normalize(String urlString) throws MalformedURLException {
    if ("".equals(urlString)) // permit empty
        return urlString;

    urlString = urlString.trim(); // remove extra spaces

    URL url = new URL(urlString);

    String protocol = url.getProtocol();
    String host = url.getHost();/*  w ww .  java 2  s .  c o m*/
    int port = url.getPort();
    String file = url.getFile();

    boolean changed = false;

    if (!urlString.startsWith(protocol)) // protocol was lowercased
        changed = true;

    if ("http".equals(protocol) || "ftp".equals(protocol)) {

        if (host != null) {
            String newHost = host.toLowerCase(); // lowercase host
            if (!host.equals(newHost)) {
                host = newHost;
                changed = true;
            }
        }

        if (port == url.getDefaultPort()) { // uses default port
            port = -1; // so don't specify it
            changed = true;
        }

        if (file == null || "".equals(file)) { // add a slash
            file = "/";
            changed = true;
        }

        if (url.getRef() != null) { // remove the ref
            changed = true;
        }

        // check for unnecessary use of "/../"
        String file2 = substituteUnnecessaryRelativePaths(file);

        if (!file.equals(file2)) {
            changed = true;
            file = file2;
        }

    }

    if (changed)
        urlString = new URL(protocol, host, port, file).toString();

    return urlString;
}

From source file:de.jetwick.snacktory.JResult.java

private String fixMissingProtocol(String imageUrl) {
    if (StringUtils.isEmpty(imageUrl))
        return imageUrl;

    if (imageUrl.startsWith("//")) {
        String existingUrl = this.url != null ? this.url
                : this.originalUrl != null ? this.originalUrl : this.canonicalUrl;
        try {/*from   www  .j av  a2s . c om*/
            URL srcUrl = new URL(existingUrl);
            return srcUrl.getProtocol() + ":" + imageUrl;
        } catch (MalformedURLException e) {
            return "http:" + imageUrl;
        }
    }

    return imageUrl;
}

From source file:com.cladonia.xngreditor.URLUtilities.java

/**
 * Returns a String representation without the Username and Password.
 * //from   w w  w .j av  a  2 s.  c  o m
 * @param url the url to convert to a String...
 * 
 * @return the string representation.
 */
public static String toString(URL url) {
    if (url != null) {
        StringBuffer result = new StringBuffer(url.getProtocol());
        result.append(":");

        if (url.getHost() != null && url.getHost().length() > 0) {
            result.append("//");
            result.append(url.getHost());
        }

        if (url.getPort() > 0) {
            result.append(":");
            result.append(url.getPort());
        }

        if (url.getPath() != null) {
            result.append(url.getPath());
        }

        if (url.getQuery() != null) {
            result.append('?');
            result.append(url.getQuery());
        }

        if (url.getRef() != null) {
            result.append("#");
            result.append(url.getRef());
        }

        return result.toString();
    }

    return null;
}

From source file:org.cee.net.impl.DefaultWebClient.java

@Override
public WebResponse openWebResponse(final URL location, boolean bufferStream) {
    if (readerFactory == null) {
        throw new IllegalArgumentException("The property readerFactory has not been set yet!");
    }/*from  w  ww.  j a v  a2  s  . c o m*/
    String protocol = location.getProtocol();
    if (protocol.equalsIgnoreCase(HTTP_PROTOCOL) || protocol.equalsIgnoreCase(HTTPS_PROTOCOL)) {
        LOG.debug("open http response for {}", location);
        if (httpClient == null) {
            throw new IllegalArgumentException("The property httpClient has not been set yet!");
        }
        return new HttpWebResponse(location, httpClient, readerFactory, bufferStream);
    } else {
        LOG.debug("open standard response for {}", location);
        return new DefaultWebResponse(location, readerFactory, bufferStream);
    }
}

From source file:cn.openwatch.internal.http.loopj.AsyncHttpClient.java

/**
 * Will encode url, if not disabled, and adds params on the end of it
 *
 * @param url             String with URL, should be valid URL without params
 * @param params          RequestParams to be appended on the end of URL
 * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20)
 * @return encoded url if requested with params appended if any available
 *//*from w  w  w. j a va 2 s .  c  om*/
public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) {
    if (url == null)
        return null;

    if (shouldEncodeUrl) {
        try {
            String decodedURL = URLDecoder.decode(url, "UTF-8");
            URL _url = new URL(decodedURL);
            URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(),
                    _url.getPath(), _url.getQuery(), _url.getRef());
            url = _uri.toASCIIString();
        } catch (Exception ex) {
            // Should not really happen, added just for sake of validity
        }
    }

    if (params != null) {
        // Construct the query string and trim it, in case it
        // includes any excessive white spaces.
        String paramString = params.getParamString().trim();

        // Only add the query string if it isn't empty and it
        // isn't equal to '?'.
        if (!paramString.equals("") && !paramString.equals("?")) {
            url += url.contains("?") ? "&" : "?";
            url += paramString;
        }
    }

    return url;
}

From source file:cz.incad.kramerius.service.replication.ExternalReferencesFormat.java

private void processDataStreamVersions(Document document, Element dataStreamElm) throws ReplicateException {
    List<Element> versions = XMLUtils.getElements(dataStreamElm, new XMLUtils.ElementsFilter() {

        @Override/*ww  w .j a  v  a2s  .  c o  m*/
        public boolean acceptElement(Element element) {
            String locName = element.getLocalName();
            return locName.endsWith("datastreamVersion");
        }
    });

    for (Element version : versions) {
        Element found = XMLUtils.findElement(version, "contentLocation", version.getNamespaceURI());
        if (found != null && found.hasAttribute("REF")) {
            try {
                URL url = new URL(found.getAttribute("REF"));
                String protocol = url.getProtocol();
                if (protocol.equals("file")) {
                    changeDatastreamVersion(document, dataStreamElm, version, url);
                }
            } catch (MalformedURLException e) {
                throw new ReplicateException(e);
            } catch (IOException e) {
                throw new ReplicateException(e);
            }
        }
    }
}

From source file:net.sourceforge.jwbf.mediawiki.live.LoginIT.java

/**
 * Login on last MW with SSL and htaccess.
 *///from   w ww  .j a v a  2  s. c  om
@Test
public final void loginWikiMWLastSSLAndHtaccess() throws Exception {

    AbstractHttpClient httpClient = getSSLFakeHttpClient();
    Version latest = Version.getLatest();

    String url = getValueOrSkip("wiki_url_latest").replace("http", "https");
    assumeReachable(url);
    URL u = new URL(url);

    assertEquals("https", u.getProtocol());
    int port = 443;
    TestHelper.assumeReachable(u);
    {
        // test if authentication required
        HttpHost targetHost = new HttpHost(u.getHost(), port, u.getProtocol());
        HttpGet httpget = new HttpGet(u.getPath());
        HttpResponse resp = httpClient.execute(targetHost, httpget);

        assertEquals(401, resp.getStatusLine().getStatusCode());
        resp.getEntity().consumeContent();
    }

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(u.getHost(), port),
            new UsernamePasswordCredentials(BotFactory.getWikiUser(latest), BotFactory.getWikiPass(latest)));

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    HttpActionClient sslFakeClient = new HttpActionClient(clientBuilder, u);
    bot = new MediaWikiBot(sslFakeClient);

    bot.login(BotFactory.getWikiUser(latest), BotFactory.getWikiPass(latest));
    assertTrue(bot.isLoggedIn());
}

From source file:com.basho.riak.client.RiakConfig.java

public RiakConfig(URL url) {
    if (url == null) {
        throw new IllegalArgumentException();
    }/*w  ww.j  a  v  a2  s .  c om*/

    String protocol = url.getProtocol().toLowerCase();
    if (!protocol.equals("http") && !protocol.equals("https")) {
        throw new IllegalArgumentException();
    }

    this.setUrl(url.toExternalForm());
}