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:org.wso2.carbon.http2.transport.Http2TransportSender.java

/**
 * Handels requests come from Axis2 Engine
 *
 * @param msgCtx//  w ww.java 2  s.  c om
 * @param targetEPR
 * @param trpOut
 * @throws AxisFault
 */
public void sendMessage(MessageContext msgCtx, String targetEPR, OutTransportInfo trpOut) throws AxisFault {
    try {
        if (targetEPR.toLowerCase().contains("http2://")) {
            targetEPR = targetEPR.replaceFirst("http2://", "http://");
        } else if (targetEPR.toLowerCase().contains("https2://")) {
            targetEPR = targetEPR.replaceFirst("https2://", "https://");
        }
        URI uri = new URI(targetEPR);
        String scheme = uri.getScheme() != null ? uri.getScheme() : "http";
        String hostname = uri.getHost();
        int port = uri.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equals(target.getSchemeName());

        HttpHost proxy = proxyConfig.selectProxy(target);

        msgCtx.setProperty(PassThroughConstants.PROXY_PROFILE_TARGET_HOST, target.getHostName());

        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }
        Http2TargetRequestUtil util = new Http2TargetRequestUtil(targetConfiguration, route);
        msgCtx.setProperty(Http2Constants.PASSTHROUGH_TARGET, util);

        if (msgCtx.getProperty(PassThroughConstants.PASS_THROUGH_PIPE) == null) {
            Pipe pipe = new Pipe(targetConfiguration.getBufferFactory().getBuffer(), "Test",
                    targetConfiguration);
            msgCtx.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
            msgCtx.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
        }

        Http2ClientHandler clientHandler = connectionFactory.getChannelHandler(target);

        String tenantDomain = (msgCtx.getProperty(MultitenantConstants.TENANT_DOMAIN) == null) ? null
                : (String) msgCtx.getProperty(MultitenantConstants.TENANT_DOMAIN);
        String dispatchSequence = (msgCtx.getProperty(Http2Constants.HTTP2_DISPATCH_SEQUENCE) == null) ? null
                : (String) msgCtx.getProperty(Http2Constants.HTTP2_DISPATCH_SEQUENCE);
        String errorSequence = (msgCtx.getProperty(Http2Constants.HTTP2_ERROR_SEQUENCE) == null) ? null
                : (String) msgCtx.getProperty(Http2Constants.HTTP2_ERROR_SEQUENCE);
        InboundResponseSender responseSender = (msgCtx
                .getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER) == null) ? null
                        : (InboundResponseSender) msgCtx
                                .getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER);
        boolean serverPushEnabled = (msgCtx
                .getProperty(Http2Constants.HTTP2_PUSH_PROMISE_REQEUST_ENABLED) == null) ? false
                        : (boolean) msgCtx.getProperty(Http2Constants.HTTP2_PUSH_PROMISE_REQEUST_ENABLED);

        clientHandler.setResponseReceiver(tenantDomain, dispatchSequence, errorSequence, responseSender,
                targetConfiguration, serverPushEnabled);
        clientHandler.channelWrite(msgCtx);

    } catch (URISyntaxException e) {
        log.error("Error parsing the http2 endpoint url");
        throw new AxisFault(e.getMessage());
    }
}

From source file:com.datazuul.iiif.presentation.backend.repository.impl.PresentationRepositoryImpl.java

@Override
public Manifest getManifest(String identifier) throws NotFoundException {
    Manifest manifest = null;/*from  w w w. ja  va 2s  .c o m*/

    LOGGER.debug("Try to get manifest for: " + identifier);

    LOGGER.debug("START getManifest() for " + identifier);
    PresentationResolver resolver = getManifestResolver(identifier);
    URI manifestUri = resolver.getURI(identifier);

    String json;
    try {
        if (manifestUri.getScheme().equals("file")) {
            json = IOUtils.toString(manifestUri);
            manifest = objectMapper.readValue(json, Manifest.class);
        } else if (manifestUri.getScheme().equals("classpath")) {
            Resource resource = applicationContext.getResource(manifestUri.toString());
            InputStream is = resource.getInputStream();
            json = IOUtils.toString(is);
            manifest = objectMapper.readValue(json, Manifest.class);
        } else if (manifestUri.getScheme().startsWith("http")) {
            String cacheKey = getCacheKey(identifier);
            manifest = httpCache.getIfPresent(cacheKey);
            if (manifest == null) {
                LOGGER.debug("HTTP Cache miss!");
                json = httpExecutor.execute(Request.Get(manifestUri)).returnContent().asString();
                manifest = objectMapper.readValue(json, Manifest.class);
                httpCache.put(cacheKey, manifest);
            } else {
                LOGGER.debug("HTTP Cache hit!");
            }
        }
    } catch (IOException e) {
        throw new NotFoundException(e);
    }
    LOGGER.debug("DONE getManifest() for " + identifier);

    if (manifest == null) {
        throw new NotFoundException("No manifest for identifier: " + identifier);
    }

    return manifest;
}

From source file:org.apache.ambari.server.controller.internal.AppCookieManager.java

/**
 * Returns hadoop.auth cookie, doing needed SPNego authentication
 * /*from   ww w .  jav  a2s.  c om*/
 * @param endpoint
 *          the URL of the Hadoop service
 * @param refresh
 *          flag indicating wehther to refresh the cookie, if
 *          <code>true</code>, we do a new SPNego authentication and refresh
 *          the cookie even if the cookie already exists in local cache
 * @return hadoop.auth cookie value
 * @throws IOException
 *           in case of problem getting hadoop.auth cookie
 */
public String getAppCookie(String endpoint, boolean refresh) throws IOException {

    HttpUriRequest outboundRequest = new HttpGet(endpoint);
    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    if (!refresh) {
        String appCookie = endpointCookieMap.get(endpoint);
        if (appCookie != null) {
            return appCookie;
        }
    }

    clearAppCookie(endpoint);

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = new HttpOptions(path);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        if (hadoopAuthCookie == null) {
            LOG.error("SPNego authentication failed, can not get hadoop.auth cookie for URL: " + endpoint);
            throw new IOException("SPNego authentication failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }

    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(endpoint, hadoopAuthCookie);
    if (LOG.isInfoEnabled()) {
        LOG.info("Successful SPNego authentication to URL:" + uri.toString());
    }
    return hadoopAuthCookie;
}

From source file:com.metamx.druid.indexing.common.index.StaticS3FirehoseFactory.java

@JsonCreator
public StaticS3FirehoseFactory(@JacksonInject("s3Client") S3Service s3Client,
        @JsonProperty("parser") StringInputRowParser parser, @JsonProperty("uris") List<URI> uris) {
    this.s3Client = s3Client;
    this.parser = Preconditions.checkNotNull(parser, "parser");
    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  2  s  .c o m
}

From source file:jenkins.scm.impl.subversion.SubversionSampleRepoRule.java

public String rootUrl() throws URISyntaxException {
    URI u = repo.toURI();
    // TODO SVN rejects File.toUri syntax (requires blank authority field)
    return new URI(u.getScheme(), "", u.getPath(), u.getFragment()).toString();
}

From source file:org.geosdi.geoplatform.connector.server.security.PreemptiveSecurityConnector.java

/**
 * If the URI don't have e port, retrieve the standard port wrt scheme
 * ["http" or "https"].//from   w w  w  . ja va 2 s  . c  o m
 */
private int retrieveNoSetPort(URI uri) {
    int port = uri.getPort();
    if (port > 0) {
        return port;
    }

    String scheme = uri.getScheme();
    if ("https".equals(scheme)) {
        port = 443;
    } else if ("http".equals(scheme)) {
        port = 80; // TODO Test Catalog with credentials on port 80 (insert the URL without specifying the port)
    } else {
        throw new IllegalArgumentException("Scheme don't recognize");
    }

    return port;
}

From source file:me.footlights.core.crypto.Fingerprint.java

private Fingerprint(MessageDigest hashAlgorithm, ByteBuffer fingerprintBytes, URI uri) {
    Preconditions.check(uri.getScheme().equals("urn"));

    this.algorithm = hashAlgorithm;
    this.bytes = fingerprintBytes;
    this.uri = uri;
}

From source file:net.paoding.spdy.server.tomcat.impl.RequestDecoder.java

private Request decode(SynStream synStream) throws URISyntaxException {
    Request request = new Request();
    request.setStartTime(synStream.getTimestamp());
    CoyoteAttributes.setSynStream(request, synStream);
    ///*  ww w .j ava 2s  .  c  o  m*/
    String method = synStream.getHeader("method");
    String url = synStream.getHeader("url");
    String version = synStream.getHeader("version");
    if (method == null && url == null && version == null) {
        throw new IllegalArgumentException("method=" + method + "; url=" + url + "; version=" + version);
    }
    request.method().setString(method);
    URI uri = new URI(url);
    request.protocol().setString(uri.getScheme());
    request.requestURI().setString(uri.getPath());
    request.query().setString(uri.getQuery());
    request.serverName().setString(uri.getHost());
    int port = uri.getPort();
    request.setServerPort(port > 0 ? port : 80);
    // copy headers
    MimeHeaders coyoteHeaders = request.getMimeHeaders();
    Map<String, String> headers = synStream.getHeaders();
    for (Map.Entry<String, String> header : headers.entrySet()) {
        MessageBytes val = coyoteHeaders.addValue(header.getKey());
        val.setString(header.getValue());
    }
    // body
    request.setInputBuffer(new SpdyInputBuffer(synStream));
    //        System.out.println("RequestDecoder.decode: returnrequest " + request.decodedURI());
    return request;
}

From source file:de.thischwa.pmcms.tool.Link.java

public void init(final String link) {
    try {//from www .j av a  2 s .  co  m
        URI uri = new URI(link);
        String schema = uri.getScheme();
        if (schema != null) {
            if (schema.equalsIgnoreCase("file")) {
                isFile = true;
            } else if (schema.equalsIgnoreCase("javascript")) {
                isExternal = true;
            } else if (schema.equalsIgnoreCase("mailto")) {
                isMailto = true;
                isExternal = true;
            } else if (schema.equalsIgnoreCase("http") && uri.getHost() != null
                    && uri.getHost().equalsIgnoreCase(host)) {
                isExternal = false;
            } else if (schema.equalsIgnoreCase("http") || schema.equalsIgnoreCase("https")
                    || schema.equalsIgnoreCase("ftp") || schema.equalsIgnoreCase("ftps"))
                isExternal = true;
        }
        path = uri.getPath();
    } catch (Exception e) {
        logger.warn("While trying to get the URI: " + e.getMessage(), e);
    }

    try {
        URL url = new URL(link);
        if (path == null)
            path = url.getPath();
        String query = url.getQuery();
        if (query != null) {
            String[] parameterPairs = StringUtils.split(query, "&");
            for (String parameterPair : parameterPairs) {
                if (StringUtils.isNotBlank(parameterPair)) {
                    KeyValue kv = new KeyValue(parameterPair);
                    String val = decodeQuietly(kv.val);
                    parameters.put(kv.key, val);
                }
            }
        }
    } catch (Exception e) {
        if (path == null)
            throw new IllegalArgumentException(e);
    }
}

From source file:com.orange.cloud.servicebroker.filter.securitygroups.domain.Destination.java

public Destination(String uriString) {
    try {/*from w  w  w .  j a v  a 2s .  co  m*/
        URI uri = new URI(uriString);
        setHost(uri.getHost());
        if (noPort(uri)) {
            setDefaultPort(uri.getScheme());
        } else {
            setPort(ImmutablePort.of(uri.getPort()));
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Cannot create connection info. Invalid URI " + uriString, e);
    }
}