Example usage for org.apache.http.client.utils URIBuilder getPath

List of usage examples for org.apache.http.client.utils URIBuilder getPath

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder getPath.

Prototype

public String getPath() 

Source Link

Usage

From source file:com.thoughtworks.go.http.mocks.HttpRequestBuilder.java

public HttpRequestBuilder withPath(String path) {
    try {/*from   ww w  . j a v a  2 s.co m*/
        URIBuilder uri = new URIBuilder(path);
        request.setServerName("test.host");
        request.setContextPath(CONTEXT_PATH);
        request.setParameters(splitQuery(uri));
        request.setRequestURI(CONTEXT_PATH + uri.getPath());
        request.setServletPath(uri.getPath());
        if (!uri.getQueryParams().isEmpty()) {
            request.setQueryString(URLEncodedUtils.format(uri.getQueryParams(), UTF_8));
        }
        return this;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.amos.tool.SelfRedirectStrategy.java

/**
 * @since 4.1//from ww w.  ja  v  a2 s .  c  o  m
 */
protected URI createLocationURI(final String location) throws ProtocolException {

    System.out.println("redirect_location:" + location);

    try {
        final URIBuilder b = new URIBuilder(new URI(location).normalize());
        final String host = b.getHost();
        if (host != null) {
            b.setHost(host.toLowerCase(Locale.ENGLISH));
        }
        final String path = b.getPath();
        if (TextUtils.isEmpty(path)) {
            b.setPath("/");
        }
        return b.build();
    } catch (final URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }
}

From source file:net.rcarz.jiraclient.RestClient.java

/**
 * Build a URI from a path and query parmeters.
 *
 * @param path Path to append to the base URI
 * @param params Map of key value pairs// w  w w  .  j  a  va2  s  .  c o m
 *
 * @return the full URI
 *
 * @throws URISyntaxException when the path is invalid
 */
public URI buildURI(String path, Map<String, String> params) throws URISyntaxException {
    URIBuilder ub = new URIBuilder(uri);
    ub.setPath(ub.getPath() + path);

    if (params != null) {
        for (Map.Entry<String, String> ent : params.entrySet())
            ub.addParameter(ent.getKey(), ent.getValue());
    }

    return ub.build();
}

From source file:com.qualinsight.plugins.sonarqube.badges.internal.QualityGateStatusRetriever.java

private String responseBodyForKey(final String key) throws IOException, URISyntaxException {
    final URIBuilder uriBuilder = new URIBuilder(this.settings.getString(SERVER_BASE_URL_KEY));
    final String uriQuery = new StringBuilder().append("resource=").append(key)
            .append("&metrics=quality_gate_details&format=json").toString();
    this.httpGet.setURI(new URI(uriBuilder.getScheme(), null, uriBuilder.getHost(), uriBuilder.getPort(),
            StringUtils.removeEnd(uriBuilder.getPath(), URI_SEPARATOR) + "/api/resources/index/", uriQuery,
            null));// ww  w .  ja v  a  2s.  com
    LOGGER.debug("Http GET request line: {}", this.httpGet.getRequestLine());
    final String responseBody = this.httpclient.execute(this.httpGet, this.responseHandler);
    LOGGER.debug("Http GET response body: {}", responseBody);
    return responseBody;
}

From source file:org.springframework.boot.cli.command.init.ProjectGenerationRequest.java

/**
 * Generates the URI to use to generate a project represented by this request.
 * @param metadata the metadata that describes the service
 * @return the project generation URI//  ww  w  . j  av  a  2s. c om
 */
URI generateUrl(InitializrServiceMetadata metadata) {
    try {
        URIBuilder builder = new URIBuilder(this.serviceUrl);
        StringBuilder sb = new StringBuilder();
        if (builder.getPath() != null) {
            sb.append(builder.getPath());
        }

        ProjectType projectType = determineProjectType(metadata);
        this.type = projectType.getId();
        sb.append(projectType.getAction());
        builder.setPath(sb.toString());

        if (!this.dependencies.isEmpty()) {
            builder.setParameter("dependencies",
                    StringUtils.collectionToCommaDelimitedString(this.dependencies));
        }

        if (this.groupId != null) {
            builder.setParameter("groupId", this.groupId);
        }
        String resolvedArtifactId = resolveArtifactId();
        if (resolvedArtifactId != null) {
            builder.setParameter("artifactId", resolvedArtifactId);
        }
        if (this.version != null) {
            builder.setParameter("version", this.version);
        }
        if (this.name != null) {
            builder.setParameter("name", this.name);
        }
        if (this.description != null) {
            builder.setParameter("description", this.description);
        }
        if (this.packageName != null) {
            builder.setParameter("packageName", this.packageName);
        }
        if (this.type != null) {
            builder.setParameter("type", projectType.getId());
        }
        if (this.packaging != null) {
            builder.setParameter("packaging", this.packaging);
        }
        if (this.javaVersion != null) {
            builder.setParameter("javaVersion", this.javaVersion);
        }
        if (this.language != null) {
            builder.setParameter("language", this.language);
        }
        if (this.bootVersion != null) {
            builder.setParameter("bootVersion", this.bootVersion);
        }

        return builder.build();
    } catch (URISyntaxException e) {
        throw new ReportableException("Invalid service URL (" + e.getMessage() + ")");
    }
}

From source file:org.aicer.hibiscus.http.client.HttpClient.java

/**
 * A URI representing the Absolute URL for the Request
 *
 * @param uri//from  w ww  .  j  a  va  2  s  .c om
 * @return
 */
public HttpClient setURI(final URI uri) {

    final URIBuilder builder = new URIBuilder(uri);

    this.scheme = builder.getScheme();
    this.host = builder.getHost();
    this.port = builder.getPort();
    this.path = builder.getPath();

    this.fragment = builder.getFragment();

    this.resetQueryParameters();

    for (NameValuePair nvp : builder.getQueryParams()) {
        this.queryParameters.add(new BasicNameValuePair(nvp.getName(), nvp.getValue()));
    }

    return this;
}

From source file:com.arrow.acs.client.api.ApiAbstract.java

public URI buildUri(String path) {
    Validate.notNull(apiConfig, "apiConfig is not set");
    try {/*from w ww .jav a 2  s. c  om*/
        URIBuilder uriBuilder;
        if (!StringUtils.isBlank(apiConfig.getBaseUrl())) {
            uriBuilder = new URIBuilder(apiConfig.getBaseUrl());
        } else {
            uriBuilder = new URIBuilder();
        }
        if (!StringUtils.isEmpty(path)) {
            StringBuilder pathBuilder = new StringBuilder()
                    .append(uriBuilder.getPath() != null ? uriBuilder.getPath() : "").append("/").append(path);
            uriBuilder.setPath(pathBuilder.toString().replaceAll("/{2,}", "/"));
        }
        return uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new AcsClientException("Invalid base: " + apiConfig.getBaseUrl() + ", path: " + path,
                new AcsErrorResponse());
    }
}

From source file:at.gv.egiz.pdfas.lib.pki.impl.OCSPClient.java

/**
 * Retrieves an OCSP response for a certain certificate ({@code eeCertificate}) of a certain CA
 * ({@code issuerCertificate}).//w  ww .  j  a  v a  2 s .  c o  m
 * 
 * @param issuerCertificate The issuer certificate (required; must not be {@code null}).
 * @param eeCertificate     The end entity certificate (required; must not be {@code null}).
 * @return The OCSP response (never {@code null}) with guaranteed response status "successful" and with <strong>any
 *         revocation state</strong>.
 * @throws IOException              Thrown in case of error communicating with OCSP responder.
 * @throws OCSPClientException      In case the client could not process the response (e.g. non-successful response
 *                                  state like malformedRequest, internalError... or an unknown/unsupported response
 *                                  type).
 * @throws IllegalArgumentException In case the provided {@code eeCertificate} does not provide an OCSP responder
 *                                  url (use {@link Util#hasOcspResponder(X509Certificate)} in order to determine if
 *                                  it is safe to call this method) or the provided certificates could not be used
 *                                  for OCSP request creation.
 * @implNote This implementation just returns OCSP responses (<strong>of any revocation status</strong>) as they
 *           were retrieved from the OCSP responder (provided the response status indicates a successful response)
 *           without performing further checks like OCSP signature verification or OCSP responder certificate
 *           validation.
 */
public OCSPResponse getOcspResponse(X509Certificate issuerCertificate, X509Certificate eeCertificate)
        throws IOException, OCSPClientException {

    Objects.requireNonNull(issuerCertificate, "Issuer certificate required... must not be null.");
    Objects.requireNonNull(eeCertificate, "End-entity certificate required... must not be null.");

    StopWatch sw = new StopWatch();
    sw.start();

    if (log.isDebugEnabled()) {
        log.debug("Retrieving OCSP revocation info for: {}", eeCertificate.getSubjectDN());
    } else if (log.isInfoEnabled()) {
        log.info("Retrieving OCSP revocation info for certificate (SHA-1 fingerprint): {}",
                Hex.encodeHexString(eeCertificate.getFingerprintSHA()));
    }

    String ocspUrl = Util.getOcspUrl(eeCertificate);
    if (ocspUrl == null) {
        throw new IllegalArgumentException("The provided certificate does not feature an ocsp responder url.");
    }

    // create request
    byte[] ocspRequestEncoded;
    ReqCert reqCert;
    try {

        CertID certID = new CertID(AlgorithmID.sha1, issuerCertificate, eeCertificate);
        reqCert = new ReqCert(ReqCert.certID, certID);
        Request request = new Request(reqCert);
        OCSPRequest ocspRequest = new OCSPRequest();
        ocspRequest.setRequestList(new Request[] { request });
        ocspRequestEncoded = ocspRequest.getEncoded();

        if (log.isTraceEnabled()) {
            log.trace("Creating OCSP request: {}", request);
        }

    } catch (NoSuchAlgorithmException e) {
        // should not occur actually
        throw new IllegalStateException("Required algorithm (SHA-1) not available.", e);
    } catch (CodingException e) {
        throw new IllegalArgumentException(
                "Unable to encode ocsp request with the provided issuer and end-entity certificates.", e);
    }

    // https://tools.ietf.org/html/rfc6960
    // GET {url}/{url-encoding of base-64 encoding of the DER encoding of the OCSPRequest}
    String b64OcspRequest = org.apache.commons.codec.binary.Base64.encodeBase64String(ocspRequestEncoded);
    String urlEncodedB64OcspRequest = URLEncoder.encode(b64OcspRequest, "UTF-8");

    HttpRequestBase request;

    if (httpCachingEnabled && urlEncodedB64OcspRequest.length() <= 255) {
        // spec proposes GET request
        URI ocspResponderUri;
        try {
            URIBuilder uriBuilder = new URIBuilder(ocspUrl);
            uriBuilder
                    .setPath(StringUtils.appendIfMissing(uriBuilder.getPath(), "/") + urlEncodedB64OcspRequest);
            ocspResponderUri = uriBuilder.build();
        } catch (URISyntaxException e) {
            // can only occur with eeCertificate containing invalid ocsp responder url
            throw new IllegalArgumentException(
                    "Unable process OCSP responder uri of provided certificate: " + ocspUrl, e);
        }

        request = new HttpGet(ocspResponderUri);
        log.debug("Sending OCSP request using HTTP GET to: {}", ocspUrl);

    } else {
        // spec proposes POST request
        HttpPost httpPost = new HttpPost(ocspUrl);
        httpPost.setEntity(
                new ByteArrayEntity(ocspRequestEncoded, ContentType.create("application/ocsp-request")));
        request = httpPost;
        log.debug("Sending OCSP request using HTTP POST to: {}", ocspUrl);
    }

    request.setConfig(requestConfig);

    try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {

        StatusLine statusLine = httpResponse.getStatusLine();
        log.debug("OCSP response HTTP status: {}", statusLine);
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw new IOException("OCSP responder did not report HTTP 200: " + statusLine);
        }

        HttpEntity responseEntity = httpResponse.getEntity();

        OCSPResponse ocspResponse;
        try (InputStream in = responseEntity.getContent()) {

            ocspResponse = new OCSPResponse(in);

        } catch (UnknownResponseException e) {
            throw new OCSPClientException("Unknown (unsupported) OCSP response type: " + e.getResponseType(),
                    e);
        }

        if (log.isTraceEnabled()) {
            log.trace("OCSP response: {}", ocspResponse);
        }

        log.debug("OCSP response status: {}", ocspResponse.getResponseStatusName());
        if (ocspResponse.getResponseStatus() != OCSPResponse.successful) {
            throw new OCSPClientException("OCSP response status was not successful, got response status: "
                    + ocspResponse.getResponseStatusName());
        }

        // get the basic ocsp response (which is the only type currently supported, otherwise an
        // UnknownResponseException would have been thrown during parsing the response)
        BasicOCSPResponse basicOCSPResponse = (BasicOCSPResponse) ocspResponse.getResponse();

        // for future improvement: verify ocsp response, responder certificate...

        SingleResponse singleResponse;
        try {
            log.trace("Looking for OCSP response specific for: {}", reqCert);
            singleResponse = basicOCSPResponse.getSingleResponse(reqCert);
        } catch (OCSPException e) {
            try {
                singleResponse = basicOCSPResponse.getSingleResponse(issuerCertificate, eeCertificate, null);
            } catch (OCSPException e1) {
                throw new OCSPClientException(
                        "Unable to process received OCSP response for the provided certificate (SHA-1 fingerprint): "
                                + Hex.encodeHexString(eeCertificate.getFingerprintSHA()),
                        e1);
            }
        }

        if (log.isTraceEnabled()) {
            log.trace("OCSP respose for specific certificate: {}", singleResponse);
        }

        CertStatus certStatus = singleResponse.getCertStatus();
        String formattedThisUpdate = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT
                .format(singleResponse.getThisUpdate());
        log.info("Certificate revocation state (@{}}: {}", formattedThisUpdate, certStatus);

        sw.stop();
        log.debug("OCSP query took: {}ms", sw.getTime());

        return ocspResponse;

    } // close httpResponse

}

From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java

/**
 * Splice base URL and URL of resource/*from  ww  w . j  ava2s  . c  o m*/
 *
 * @param resource   REST Resource Path
 * @param parameters Map of query parameters
 * @return Absolute URL to the REST Resource including server and port
 * @throws RestEndpointIOException In case of incorrect URL format
 */
final URI spliceUrl(String resource, Map<String, String> parameters) throws RestEndpointIOException {
    try {
        URIBuilder builder;
        if (!Strings.isNullOrEmpty(baseUrl)) {
            builder = new URIBuilder(baseUrl);
            builder.setPath(builder.getPath() + resource);
        } else {
            builder = new URIBuilder(resource);
        }
        for (Entry<String, String> parameter : parameters.entrySet()) {
            builder.addParameter(parameter.getKey(), parameter.getValue());
        }
        return builder.build();
    } catch (URISyntaxException e) {
        throw new RestEndpointIOException(
                "Unable to builder URL with base url '" + baseUrl + "' and resouce '" + resource + "'", e);
    }
}