Example usage for java.net URI getScheme

List of usage examples for java.net URI getScheme

Introduction

In this page you can find the example usage for java.net URI getScheme.

Prototype

public String getScheme() 

Source Link

Document

Returns the scheme component of this URI.

Usage

From source file:com.anrisoftware.globalpom.checkfilehash.CheckFileHash.java

private HashName hashName(URI hashResource) {
    if (StringUtils.equals(hashResource.getScheme(), "md5")) {
        return HashName.forExtension("md5");
    } else if (StringUtils.equals(hashResource.getScheme(), "sha1")) {
        return HashName.forExtension("sha1");
    } else {/*from  w w  w.ja  v  a2  s  . co  m*/
        String ex = getExtension(hashResource.getPath());
        return HashName.forExtension(ex);
    }
}

From source file:com.amarinfingroup.net.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString/*ww  w.jav a2 s . c o  m*/
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);
    req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                Collect.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                Header contentEncoding = entity.getContentEncoding();
                if (contentEncoding != null
                        && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING)) {
                    is = new GZIPInputStream(is);
                }
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:org.bedework.synch.cnctrs.file.FileConnectorInstance.java

@Override
public URI getUri() throws SynchException {
    try {/*from  ww w  . j  a  va  2  s  .  co m*/
        //Get yesterdays date
        final LocalDate yesterday = LocalDate.now().minus(1, ChronoUnit.DAYS);
        final String yesterdayStr = yesterday.format(DateTimeFormatter.ISO_LOCAL_DATE);

        final URI infoUri = new URI(info.getUri());
        return new URIBuilder().setScheme(infoUri.getScheme()).setHost(infoUri.getHost())
                .setPort(infoUri.getPort()).setPath(infoUri.getPath()).build();
    } catch (final SynchException se) {
        throw se;
    } catch (final Throwable t) {
        throw new SynchException(t);
    }
}

From source file:org.artifactory.webapp.wicket.util.validation.UriValidator.java

@Override
protected void onValidate(IValidatable validatable) {
    String uri = (String) validatable.getValue();

    if (!PathUtils.hasText(uri)) {
        addError(validatable, "The URL cannot be empty");
        return;// ww  w .  jav a 2s.  co m
    }

    try {
        URI parsedUri = new URIBuilder(uri).build();
        String scheme = parsedUri.getScheme();
        if (!anySchemaAllowed() && StringUtils.isBlank(scheme)) {
            addError(validatable,
                    String.format(
                            "Url scheme cannot be empty. The following schemes are allowed: %s. "
                                    + "For example: %s://host",
                            Arrays.asList(allowedSchemes), allowedSchemes[0]));

        } else if (!allowedSchema(scheme)) {
            addError(validatable,
                    String.format("Scheme '%s' is not allowed. The following schemes are allowed: %s", scheme,
                            Arrays.asList(allowedSchemes)));
        }

        HttpHost host = URIUtils.extractHost(parsedUri);
        if (host == null) {
            addError(validatable, "Cannot resolve host from url: " + uri);
        }
    } catch (URISyntaxException e) {
        addError(validatable, String.format("'%s' is not a valid url", uri));
    }
}

From source file:io.druid.firehose.s3.StaticS3FirehoseFactory.java

@JsonCreator
public StaticS3FirehoseFactory(@JacksonInject("s3Client") RestS3Service s3Client,
        @JsonProperty("uris") List<URI> uris) {
    this.s3Client = s3Client;
    this.uris = ImmutableList.copyOf(uris);

    for (final URI inputURI : uris) {
        Preconditions.checkArgument(inputURI.getScheme().equals("s3"), "input uri scheme == s3 (%s)", inputURI);
    }//from  www .  j  a  v a 2s  . c  om
}

From source file:com.marvelution.gadgets.sonar.servlet.SonarMakeRequestServlet.java

/**
 * Get the {@link Host} from a given {@link URI}
 * //  w ww.  j  a va  2  s.  co m
 * @param uri the {@link URI}
 * @return the {@link Host}
 */
private Host getHost(URI uri) {
    StringBuilder hostUri = new StringBuilder();
    hostUri.append(uri.getScheme()).append("://");
    if (uri.getAuthority().indexOf("@") > -1) {
        hostUri.append(uri.getAuthority().substring(uri.getAuthority().lastIndexOf("@") + 1));
    } else {
        hostUri.append(uri.getAuthority());
    }
    Host host = new Host(hostUri.toString());
    if (uri.getAuthority().indexOf("@") > -1) {
        String userInfo = uri.getAuthority().substring(0, uri.getAuthority().lastIndexOf("@"));
        host.setUsername(userInfo.substring(0, userInfo.indexOf(":")));
        host.setPassword(userInfo.substring(userInfo.indexOf(":") + 1));
    }
    return host;
}

From source file:io.druid.firehose.oss.StaticOSSFirehoseFactory.java

@JsonCreator
public StaticOSSFirehoseFactory(@JacksonInject("ossClient") OSSClient ossClient,
        @JsonProperty("uris") List<URI> uris) {
    this.ossClient = ossClient;
    this.uris = ImmutableList.copyOf(uris);

    for (final URI inputURI : uris) {
        Preconditions.checkArgument(inputURI.getScheme().equals("oss"), "input uri scheme == oss (%s)",
                inputURI);//from  w  w  w. j ava2 s. co m
    }
}

From source file:com.anrisoftware.simplerest.owncloud.DefaultOwncloudAccountURIFromEnv.java

private URI fromCredentials() {
    try {//from w  ww . j  a  v a 2s . c o m
        URI base = new URI(owncloudBaseUri);
        String string = format("%s://%s:%s@%s/%s", base.getScheme(), owncloudAccountUser,
                owncloudAccountPassword, base.getHost(), base.getPath());
        try {
            return new URI(string);
        } catch (URISyntaxException e) {
            throw new BuildAccountURIException(e, string);
        }
    } catch (URISyntaxException e) {
        throw new BuildAccountURIException(e, owncloudBaseUri);
    }
}

From source file:com.nesscomputing.service.discovery.client.ServiceURI.java

public ServiceURI(final URI uri) throws URISyntaxException {
    if (!"srvc".equals(uri.getScheme())) {
        throw new URISyntaxException(uri.toString(), "ServiceURI only supports srvc:// URIs");
    }/*w  ww.  j av a 2s . c o m*/
    if (!StringUtils.startsWith(uri.getSchemeSpecificPart(), "//")) {
        throw new URISyntaxException(uri.toString(), "ServiceURI only supports srvc:// URIs");
    }

    final String schemeSpecificPart = uri.getSchemeSpecificPart().substring(2);
    final int slashIndex = schemeSpecificPart.indexOf('/');
    if (slashIndex == -1) {
        throw new URISyntaxException(uri.toString(), "ServiceURI requires a slash at the end of the service!");
    }
    final int colonIndex = schemeSpecificPart.indexOf(':');
    if (colonIndex == -1 || colonIndex > slashIndex) {
        serviceName = schemeSpecificPart.substring(0, slashIndex);
        serviceType = null;
    } else {
        serviceName = schemeSpecificPart.substring(0, colonIndex);
        serviceType = schemeSpecificPart.substring(colonIndex + 1, slashIndex);
    }

    path = uri.getRawPath();
    query = uri.getRawQuery();
    fragment = uri.getRawFragment();
}

From source file:org.esco.portlet.flashinfo.service.bean.FlashUrlBuilderImpl.java

@Override
public String transform(final PortletRequest request, final String url) {
    String rewroteUrl = url;/*from   w ww  . j  ava 2  s.c om*/
    if (log.isDebugEnabled()) {
        log.debug("Url in entry is '{}'", rewroteUrl);
    }
    final Matcher matcher = p.matcher(url);
    if (matcher.find()) {
        for (int i = 1; i <= matcher.groupCount(); i++) {
            // Using the first value only
            final List<String> values = userResource.getUserInfo(request, matcher.group(i));
            if (values != null && !values.isEmpty()) {
                rewroteUrl = rewroteUrl.replaceAll("\\{" + matcher.group(i) + "\\}", values.get(0));
            } else {
                log.warn("No value was retrived from user info of '{}' on attribute '{}'",
                        request.getUserPrincipal(), matcher.group(i));
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Replacement regexp of flashUrl from {} to {}", url, rewroteUrl);
    }

    try {
        final URI uri = new URI(rewroteUrl);
        if (uri.getScheme() == null && uri.getHost() == null) {
            final int tmpPort = request.getServerPort();
            final String port = ((tmpPort != 80) && (tmpPort != 443) && (tmpPort > 0)) ? ":" + tmpPort : "";
            // if start with // we add only the scheme
            // else if relative url start with / we add to the url only the scheme and domain
            // else if relative url we add sheme + domain + contextPath so in this case only we need to context path
            final String ctx = (!rewroteUrl.startsWith("//") && !rewroteUrl.startsWith("/"))
                    ? request.getContextPath() + "/"
                    : "";
            if (log.isDebugEnabled()) {
                log.debug(
                        "Rewrite flashUrl from {} to {}, with params scheme {}, host {}, port {}, context path {}",
                        rewroteUrl,
                        request.getScheme() + "://" + request.getServerName() + port + ctx + rewroteUrl,
                        request.getScheme(), request.getServerName(), port, ctx);
            }
            rewroteUrl = request.getScheme() + "://" + request.getServerName() + port + ctx + rewroteUrl;
        } else if (uri.getScheme() == null) {
            final String path = !rewroteUrl.startsWith("//") ? "//" : "";
            if (log.isDebugEnabled()) {
                log.debug("Rewrite flashUrl from {} to {}, with params scheme {}", rewroteUrl,
                        request.getScheme() + ":" + path + rewroteUrl, request.getScheme() + path);
            }
            rewroteUrl = request.getScheme() + ":" + path + rewroteUrl;
        }
    } catch (URISyntaxException e) {
        log.error("The url '" + rewroteUrl + "' to get flashInfos is malformed !", e);
        return null;
    }
    if (log.isDebugEnabled()) {
        log.debug("Url at end is '{}'", rewroteUrl);
    }
    return rewroteUrl;
}