Example usage for org.apache.http.client.methods HttpUriRequest getURI

List of usage examples for org.apache.http.client.methods HttpUriRequest getURI

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest getURI.

Prototype

URI getURI();

Source Link

Document

Returns the URI this request uses, such as <code>http://example.org/path/to/file</code>.

Usage

From source file:illab.nabal.proxy.AbstractContext.java

/**
 * Get base string for HMAC-SHA1 encoding.
 * /*from   w  ww  .  jav a  2 s  .  co m*/
 * @deprecated
 * @param request
 * @return  signatureBaseString
 * @throws Exception
 */
protected String getSignatureBaseString(HttpUriRequest request) throws Exception {

    String signatureBaseString = "";

    URI uri = request.getURI();

    StringHelper strings = new StringHelper();
    strings.appendAllAtOnce(request.getMethod(), AMPERSEND, URLEncoder.encode(uri.getPath(), UTF_8), AMPERSEND);

    List<NameValuePair> oauthParams = new ArrayList<NameValuePair>();
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entry = ((HttpEntityEnclosingRequest) request).getEntity();
        if (entry instanceof UrlEncodedFormEntity) {
            List<NameValuePair> params = URLEncodedUtils.parse(entry);
            if (params != null) {
                oauthParams.addAll(params);
            }
        }
    }

    List<NameValuePair> params = URLEncodedUtils.parse(uri, UTF_8);
    if (params != null) {
        oauthParams.addAll(params);
        if (oauthParams.size() > 0) {
            StringHelper paramStrings = new StringHelper();
            NameValuePair[] sortedParams = oauthParams.toArray(new NameValuePair[params.size()]);
            Arrays.sort(sortedParams, ParameterHelper.paramComparator);
            int paramCnt = 0;
            for (NameValuePair param : sortedParams) {
                if (paramCnt > 0) {
                    paramStrings.append(AMPERSEND);
                }
                paramStrings.append(param.getName());
                paramStrings.append(EQUAL_MARK);
                if (StringHelper.isEmpty(param.getName()) == false && OAUTH_CALLBACK.equals(param.getName())) {
                    paramStrings.append(URLEncoder.encode(param.getValue(), UTF_8));
                } else {
                    paramStrings.append(StringHelper.nvl(param.getValue()));
                }
                paramCnt++;
            }
            strings.append(URLEncoder.encode(paramStrings.toString(), UTF_8));

            paramStrings = null;
            sortedParams = null;
            params = null;
            oauthParams = null;
        }
    }

    signatureBaseString = strings.toString();

    strings = null;

    return signatureBaseString;
}

From source file:org.openrdf.http.client.SparqlSession.java

/**
 * Convenience method to deal with HTTP level errors of tuple, graph and
 * boolean queries in the same way. This method aborts the HTTP connection.
 * //  w  w  w .j  av a2s.  c  om
 * @param method
 * @throws OpenRDFException
 */
protected HttpResponse executeOK(HttpUriRequest method) throws IOException, OpenRDFException {
    boolean fail = true;
    HttpResponse response = execute(method);

    try {
        int httpCode = response.getStatusLine().getStatusCode();
        if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_NOT_AUTHORITATIVE) {
            fail = false;
            return response; // everything OK, control flow can continue
        } else {
            // trying to contact a non-Sesame server?
            throw new RepositoryException("Failed to get server protocol; no such resource on this server: "
                    + method.getURI().toString());
        }
    } finally {
        if (fail) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java

/**
 * Convenience method to deal with HTTP level errors of tuple, graph and boolean queries in the same way.
 * This method aborts the HTTP connection.
 * //from w  w  w  .j av a 2s . c o m
 * @param method
 * @throws RDF4JException
 */
protected HttpResponse executeOK(HttpUriRequest method) throws IOException, RDF4JException {
    boolean fail = true;
    HttpResponse response = execute(method);

    try {
        int httpCode = response.getStatusLine().getStatusCode();
        if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_NOT_AUTHORITATIVE) {
            fail = false;
            return response; // everything OK, control flow can continue
        } else {
            // trying to contact a non-SPARQL server?
            throw new RepositoryException("Failed to get server protocol; no such resource on this server: "
                    + method.getURI().toString());
        }
    } finally {
        if (fail) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

From source file:org.rundeck.api.ApiCall.java

/**
 * Execute an HTTP request to the Rundeck instance. We will login first, and then execute the API call.
 *
 * @param request to execute. see {@link HttpGet}, {@link HttpDelete}, and so on...
 * @return a new {@link InputStream} instance, not linked with network resources
 * @throws RundeckApiException in case of error when calling the API
 * @throws RundeckApiLoginException if the login fails (in case of login-based authentication)
 * @throws RundeckApiTokenException if the token is invalid (in case of token-based authentication)
 *//*from   ww  w .  ja va  2s . c o m*/
private <T> T execute(HttpUriRequest request, Handler<HttpResponse, T> handler)
        throws RundeckApiException, RundeckApiLoginException, RundeckApiTokenException {
    try (CloseableHttpClient httpClient = instantiateHttpClient()) {
        // we only need to manually login in case of login-based authentication
        // note that in case of token-based auth, the auth (via an HTTP header) is managed by an interceptor.
        if (client.getToken() == null && client.getSessionID() == null) {
            login(httpClient);
        }

        // execute the HTTP request
        HttpResponse response = null;
        try {
            response = httpClient.execute(request);
        } catch (IOException e) {
            throw new RundeckApiException(
                    "Failed to execute an HTTP " + request.getMethod() + " on url : " + request.getURI(), e);
        }

        // in case of error, we get a redirect to /api/error
        // that we need to follow manually for POST and DELETE requests (as GET)
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode / 100 == 3) {
            String newLocation = response.getFirstHeader("Location").getValue();
            try {
                EntityUtils.consume(response.getEntity());
            } catch (IOException e) {
                throw new RundeckApiException("Failed to consume entity (release connection)", e);
            }
            request = new HttpGet(newLocation);
            try {
                response = httpClient.execute(request);
                statusCode = response.getStatusLine().getStatusCode();
            } catch (IOException e) {
                throw new RundeckApiException("Failed to execute an HTTP GET on url : " + request.getURI(), e);
            }
        }

        // check the response code (should be 2xx, even in case of error : error message is in the XML result)
        if (statusCode / 100 != 2) {
            if (statusCode == 403 && (client.getToken() != null || client.getSessionID() != null)) {
                throw new RundeckApiTokenException("Invalid Token or sessionID ! Got HTTP response '"
                        + response.getStatusLine() + "' for " + request.getURI());
            } else {
                throw new RundeckApiException.RundeckApiHttpStatusException(
                        "Invalid HTTP response '" + response.getStatusLine() + "' for " + request.getURI(),
                        statusCode);
            }
        }
        if (statusCode == 204) {
            return null;
        }
        if (response.getEntity() == null) {
            throw new RundeckApiException(
                    "Empty Rundeck response ! HTTP status line is : " + response.getStatusLine());
        }
        return handler.handle(response);
    } catch (IOException e) {
        throw new RundeckApiException("failed closing http client", e);
    }
}

From source file:org.duniter.core.client.service.HttpServiceImpl.java

protected Object parseResponse(HttpUriRequest request, HttpResponse response, Class<?> ResultClass)
        throws IOException {
    Object result = null;/*from   w  w  w  .  j  a  v a 2s .c  o  m*/

    boolean isStreamContent = ResultClass == null || ResultClass.equals(InputStream.class);
    boolean isStringContent = !isStreamContent && ResultClass != null && ResultClass.equals(String.class);

    InputStream content = response.getEntity().getContent();

    // If should return an inputstream
    if (isStreamContent) {
        result = content; // must be close by caller
    }

    // If should return String
    else if (isStringContent) {
        try {
            String stringContent = getContentAsString(content);
            // Add a debug before returning the result
            if (log.isDebugEnabled()) {
                log.debug("Parsing response:\n" + stringContent);
            }
            return stringContent;
        } finally {
            if (content != null) {
                content.close();
            }
        }
    }

    // deserialize Json
    else {

        try {
            result = readValue(content, ResultClass);
        } catch (Exception e) {
            String requestPath = request.getURI().toString();

            // Check if content-type error
            ContentType contentType = ContentType.getOrDefault(response.getEntity());
            String actualMimeType = contentType.getMimeType();
            if (!ObjectUtils.equals(ContentType.APPLICATION_JSON.getMimeType(), actualMimeType)) {
                throw new TechnicalException(I18n.t("duniter4j.client.core.invalidResponseContentType",
                        requestPath, ContentType.APPLICATION_JSON.getMimeType(), actualMimeType));
            }

            // throw a generic error
            throw new TechnicalException(I18n.t("duniter4j.client.core.invalidResponse", requestPath), e);
        } finally {
            if (content != null) {
                content.close();
            }
        }
    }

    if (result == null) {
        throw new TechnicalException(
                I18n.t("duniter4j.client.core.emptyResponse", request.getURI().toString()));
    }

    return result;
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private HttpResponse execute(HttpUriRequest hr, DefaultHttpClient client, HttpContext context)
        throws ClientProtocolException, IOException {
    HttpResponse response = null;//w ww  . j a va  2 s  .  c o  m
    if (hr.getURI().getAuthority().contains("_")) {
        URL urlObj = hr.getURI().toURL();
        HttpHost host;
        if (urlObj.getPort() == -1) {
            host = new HttpHost(urlObj.getHost(), 80, urlObj.getProtocol());
        } else {
            host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
        }
        response = client.execute(host, hr, context);
    } else {
        response = client.execute(hr, context);
    }
    return response;
}

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

/**
 * Executes {@link org.apache.http.client.methods.HttpUriRequest}
 *
 * @param rq       - Request/*from   www. j  a v  a 2s. co  m*/
 * @param callback - Callback to be applied on response
 * @param <RS>     type of response
 * @return - Serialized Response Body
 * @throws RestEndpointIOException IO exception
 */
private <RS> Will<Response<RS>> executeInternal(final HttpUriRequest rq, final HttpEntityCallback<RS> callback)
        throws RestEndpointIOException {

    final SettableFuture<Response<RS>> future = SettableFuture.create();
    httpClient.execute(rq, new FutureCallback<org.apache.http.HttpResponse>() {

        @Override
        public void completed(final org.apache.http.HttpResponse response) {
            try {
                if (errorHandler.hasError(response)) {
                    errorHandler.handle(rq, response);
                }

                HttpEntity entity = response.getEntity();
                Header[] allHeaders = response.getAllHeaders();
                ImmutableMultimap.Builder<String, String> headersBuilder = ImmutableMultimap.builder();
                for (Header header : allHeaders) {
                    for (HeaderElement element : header.getElements()) {
                        headersBuilder.put(header.getName(),
                                null == element.getValue() ? "" : element.getValue());
                    }
                }

                Response<RS> rs = new Response<RS>(rq.getURI().toASCIIString(),
                        response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(),
                        headersBuilder.build(), callback.callback(entity));

                future.set(rs);
            } catch (SerializerException e) {
                future.setException(e);
            } catch (IOException e) {
                future.setException(new RestEndpointIOException("Unable to execute request", e));
            } catch (Exception e) {
                future.setException(e);
            }

        }

        @Override
        public void failed(final Exception ex) {
            future.setException(new RestEndpointIOException("Unable to execute request", ex));
        }

        @Override
        public void cancelled() {
            final TimeoutException timeoutException = new TimeoutException();
            future.setException(timeoutException);
        }

    });
    return Wills.forListenableFuture(future);

}