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.turn.camino.config.ConfigBuilder.java

/**
 * Resolves include config to context location
 *
 * @param include include config//from w  w  w.  ja va2 s.  c o  m
 * @param context URI context
 * @return resolved URI
 * @throws IOException
 */
protected URI resolveInclude(String include, URI context) throws IOException {
    URI uri = URI.create(include);
    if (uri.getScheme() != null) {
        return uri;
    }
    if (context != null) {
        return context.resolve(uri);
    }
    throw new IOException("Cannot find config " + include);
}

From source file:opendap.auth.RemotePDP.java

@Override
public void init(Element config) throws ConfigurationException {

    String msg;//from  www .j a  va 2  s  .  com
    Element e;

    if (config == null) {
        msg = "Configuration MAY NOT be null!.";
        _log.error("init() - {}", msg);
        throw new ConfigurationException(msg);
    }

    try {
        _pdpServiceEndpoint = new URI(DEFAULT_PDP_SERVICE);
        e = config.getChild("PDPServiceEndpoint");
        if (e != null) {
            URI uri = new URI(e.getTextTrim());
            if (!uri.getScheme().equalsIgnoreCase("https")) {
                _log.warn("init() - RemotePDP connection is not using https.");
            }
            _pdpServiceEndpoint = uri;
        }
        _log.debug("init() - RemotePDP URL: {}", _pdpServiceEndpoint);
    } catch (URISyntaxException e1) {
        throw new ConfigurationException(e1);
    }

}

From source file:com.thoughtworks.go.util.command.UrlArgument.java

@Override
public String forDisplay() {
    try {/*from   ww  w.  ja va  2s  . c o  m*/
        URI uri = new URI(sanitizeUrl());
        if (uri.getUserInfo() != null) {
            uri = new URI(uri.getScheme(), clean(uri.getScheme(), uri.getUserInfo()), uri.getHost(),
                    uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
        }
        return uri.toString();
    } catch (URISyntaxException e) {
        return url;
    }
}

From source file:com.subgraph.vega.impl.scanner.urls.UriParser.java

public IPathState processUri(URI uri) {
    final HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    final IWebHost webHost = getWebHost(host);
    IWebPath path = webHost.getRootPath();
    final boolean hasTrailingSlash = uri.getPath().endsWith("/");

    String[] parts = uri.getPath().split("/");
    IWebPath childPath;/*w  w  w  .  j ava  2  s . com*/
    for (int i = 1; i < parts.length; i++) {
        synchronized (path) {
            childPath = path.getChildPath(parts[i]);
            if (childPath == null) {
                childPath = path.addChildPath(parts[i]);
            }
            processPath(childPath, uri, (i == (parts.length - 1)), hasTrailingSlash);
        }
        path = childPath;
    }
    return pathStateManager.getStateForPath(path);
}

From source file:com.aaasec.sigserv.cscommon.xmldsig.OfflineResolver.java

/**
 * We resolve http URIs <I>without</I> fragment...
 *
 * @param uri/*  w  ww.j ava  2  s.co m*/
 * @param BaseURI
 *
 */
public boolean engineCanResolve(Attr uri, String BaseURI) {

    String uriNodeValue = uri.getNodeValue();
    if (uriNodeValue.equals("") || uriNodeValue.startsWith("#")) {
        return false;
    }

    try {
        URI uriNew = getNewURI(uri.getNodeValue(), BaseURI);
        if (uriNew.getScheme().equals("http")) {
            log.debug("I state that I can resolve " + uriNew.toString());
            return true;
        }

        log.debug("I state that I can't resolve " + uriNew.toString());
    } catch (URISyntaxException ex) {
        //
    }

    return false;
}

From source file:com.yahoo.gondola.container.LocalTestRoutingServer.java

public LocalTestRoutingServer(Gondola gondola, RoutingHelper routingHelper,
        ProxyClientProvider proxyClientProvider, Map<String, RoutingService> services,
        ChangeLogProcessor changeLogProcessor) throws Exception {
    routingFilter = new RoutingFilter(gondola, routingHelper, proxyClientProvider, services,
            changeLogProcessor);/*from ww  w. j  a  v a 2  s  .  com*/
    routingFilter.start();
    localTestServer = new LocalTestServer((request, response, context) -> {
        try {
            URI requestUri = URI.create(request.getRequestLine().getUri());
            URI baseUri = URI
                    .create(requestUri.getScheme() + "://" + requestUri.getHost() + ":" + requestUri.getPort());
            ContainerRequest containerRequest = new ContainerRequest(baseUri, requestUri,
                    request.getRequestLine().getMethod(), null, new MapPropertiesDelegate());
            routingFilter.filter(containerRequest);

            Response abortResponse = containerRequest.getAbortResponse();
            Response jaxrsResponse;
            if (abortResponse != null) {
                jaxrsResponse = abortResponse;
            } else {
                jaxrsResponse = new OutboundJaxrsResponse.Builder(null).status(200).build();
            }

            ContainerResponse containerResponse = new ContainerResponse(containerRequest, jaxrsResponse);
            routingFilter.filter(containerRequest, containerResponse);
            response.setStatusCode(containerResponse.getStatus());
            response.setEntity(new StringEntity(containerResponse.getEntity().toString()));

            Set<Map.Entry<String, List<Object>>> entries = containerResponse.getHeaders().entrySet();
            for (Map.Entry<String, List<Object>> e : entries) {
                String headerName = e.getKey();
                for (Object o : e.getValue()) {
                    String headerValue = o.toString();
                    response.setHeader(headerName, headerValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    });
    host = localTestServer.start();
}

From source file:oauth.signpost.signature.SignatureBaseString.java

public String normalizeUrl(String url) throws URISyntaxException {
    URI uri = new URI(url);
    String scheme = uri.getScheme().toLowerCase();
    String authority = uri.getAuthority().toLowerCase();
    boolean dropPort = (scheme.equals("http") && uri.getPort() == 80)
            || (scheme.equals("https") && uri.getPort() == 443);
    if (dropPort) {
        // find the last : in the authority
        int index = authority.lastIndexOf(":");
        if (index >= 0) {
            authority = authority.substring(0, index);
        }/*from www . jav  a 2s  .c  om*/
    }
    String path = uri.getRawPath();
    if (path == null || path.length() <= 0) {
        path = "/"; // conforms to RFC 2616 section 3.2.2
    }
    // we know that there is no query and no fragment here.
    return scheme + "://" + authority + path;
}

From source file:com.mpower.clientcollection.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/*from ww w  . ja  v  a 2  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?
                ClientCollection.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:com.subgraph.vega.internal.analysis.ContentAnalyzer.java

private void runExtractUrls(ContentAnalyzerResult result, IHttpResponse response, IWebModel webModel) {
    if (response.isMostlyAscii()) {
        for (URI u : urlExtractor.findUrls(response)) {
            if (addLinksToModel
                    && (u.getScheme().equalsIgnoreCase("http") || u.getScheme().equalsIgnoreCase("https")))
                webModel.getWebPathByUri(u);
            result.addUri(u);/*from ww w  . j av  a  2  s. c o  m*/
        }
    }
}

From source file:org.trancecode.xproc.step.HttpRequestStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) {
    final XdmNode sourceDoc = input.readNode(XProcPorts.SOURCE);
    final XdmNode request = SaxonAxis.childElement(sourceDoc);
    if (!XProcXmlModel.Elements.REQUEST.equals(request.getNodeName())) {
        throw XProcExceptions.xc0040(input.getStep().getLocation());
    }// ww w . ja  va2 s .c  o m

    final Map<QName, Object> serializationOptions = Steps.getSerializationOptions(input,
            DEFAULT_SERIALIZATION_OPTIONS);
    LOG.trace("  serializationOptions = {}", serializationOptions);

    final RequestParser parser = new RequestParser(serializationOptions);
    final Processor processor = input.getPipelineContext().getProcessor();

    final XProcHttpRequest xProcRequest = parser.parseRequest(request, processor);
    final URI uri = xProcRequest.getHttpRequest().getURI();
    if (uri.getScheme() != null && !StringUtils.equals("file", uri.getScheme())
            && !StringUtils.equals("http", uri.getScheme())) {
        throw XProcExceptions.xd0012(input.getLocation(), uri.toASCIIString());
    }

    final BasicHttpContext localContext = new BasicHttpContext();
    final HttpClient httpClient = prepareHttpClient(xProcRequest, localContext);
    try {
        final ResponseHandler<XProcHttpResponse> responseHandler = new HttpResponseHandler(processor,
                xProcRequest.isDetailled(), xProcRequest.isStatusOnly(), xProcRequest.getOverrideContentType());
        final XProcHttpResponse response = httpClient.execute(xProcRequest.getHttpRequest(), responseHandler,
                localContext);
        final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());
        builder.startDocument();
        if (response.getNodes() != null) {
            builder.nodes(response.getNodes());
        }
        builder.endDocument();
        output.writeNodes(XProcPorts.RESULT, builder.getNode());
    } catch (final IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}