Example usage for org.apache.http.protocol HttpCoreContext HTTP_REQUEST

List of usage examples for org.apache.http.protocol HttpCoreContext HTTP_REQUEST

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpCoreContext HTTP_REQUEST.

Prototype

String HTTP_REQUEST

To view the source code for org.apache.http.protocol HttpCoreContext HTTP_REQUEST.

Click Source Link

Usage

From source file:org.callimachusproject.client.GUnzipInterceptor.java

@Override
public void process(HttpResponse resp, HttpContext context) throws HttpException, IOException {
    HttpRequest req = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpEntity entity = resp.getEntity();
    if (entity == null)
        return;/*from  w  ww.java  2  s  .c  o  m*/
    Header cache = req.getFirstHeader("Cache-Control");
    if (cache != null && cache.getValue().contains("no-transform"))
        return;
    Header encoding = resp.getFirstHeader("Content-Encoding");
    if (encoding != null && "gzip".equals(encoding.getValue())) {
        resp.removeHeaders("Content-MD5");
        resp.removeHeaders("Content-Length");
        resp.setHeader("Content-Encoding", "identity");
        resp.addHeader("Warning", WARN_214);
        resp.setEntity(gunzip(entity));
    }
}

From source file:ch.cyberduck.core.s3.S3HttpRequestRetryHandler.java

@Override
public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
    if (super.retryRequest(exception, executionCount, context)) {
        final Object attribute = context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        if (attribute instanceof HttpUriRequest) {
            final HttpUriRequest method = (HttpUriRequest) attribute;
            log.warn(String.format("Retrying request %s", method));
            try {
                // Build the authorization string for the method.
                authorizer.authorizeHttpRequest(method, context, null);
                return true;
            } catch (ServiceException e) {
                log.warn("Unable to generate updated authorization string for retried request", e);
            }/*from w ww  . ja  v a 2  s . co  m*/
        }
    }
    return false;
}

From source file:com.netflix.spinnaker.orca.pipeline.util.HttpClientUtils.java

private static CloseableHttpClient httpClientWithServiceUnavailableRetryStrategy() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                @Override//from  w  w w.  j  a  v a2  s  . c  o m
                public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    HttpUriRequest currentReq = (HttpUriRequest) context
                            .getAttribute(HttpCoreContext.HTTP_REQUEST);
                    LOGGER.info("Response code {} for {}", statusCode, currentReq.getURI());

                    if (statusCode >= HttpStatus.SC_OK && statusCode <= 299) {
                        return false;
                    }

                    boolean shouldRetry = (statusCode == 429
                            || RETRYABLE_500_HTTP_STATUS_CODES.contains(statusCode))
                            && executionCount <= MAX_RETRIES;
                    if (!shouldRetry) {
                        throw new RetryRequestException(String.format("Not retrying %s. Count %d, Max %d",
                                currentReq.getURI(), executionCount, MAX_RETRIES));
                    }

                    LOGGER.error("Retrying request on response status {}. Count {} Max is {}", statusCode,
                            executionCount, MAX_RETRIES);
                    return true;
                }

                @Override
                public long getRetryInterval() {
                    return RETRY_INTERVAL;
                }
            });

    httpClientBuilder.setRetryHandler((exception, executionCount, context) -> {
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        Uninterruptibles.sleepUninterruptibly(RETRY_INTERVAL, TimeUnit.MILLISECONDS);
        LOGGER.info("Encountered network error. Retrying request {},  Count {} Max is {}", currentReq.getURI(),
                executionCount, MAX_RETRIES);
        return executionCount <= MAX_RETRIES;
    });

    httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_MILLIS)
            .setConnectTimeout(TIMEOUT_MILLIS).setSocketTimeout(TIMEOUT_MILLIS).build());

    return httpClientBuilder.build();
}

From source file:org.blocks4j.reconf.infra.http.layer.RetryHandler.java

public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (exception instanceof SocketException && executionCount <= 1) {
        return true;
    }/*w  w  w  .j a v  a2 s .  c o m*/
    if (executionCount >= maxRetry) {
        // Do not retry if over max retry count
        return false;
    }
    if (exception instanceof NoHttpResponseException) {
        // Retry if the server dropped connection on us
        return true;
    }
    if (exception instanceof SSLHandshakeException) {
        // Do not retry on SSL handshake exception
        return false;
    }
    HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    if (idempotent) {
        // Retry if the request is considered idempotent
        return true;
    }
    return false;
}

From source file:com.norconex.collector.http.crawler.TargetURLRedirectStrategy.java

public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    boolean isRedirected = nested.isRedirected(request, response, context);
    HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    if (!isRedirected) {
        if (currentReq.getURI().isAbsolute()) {
            CURRENT_URL.set(currentReq.getURI().toString());
        } else {//from w  w  w .  java 2 s  .  co m
            CURRENT_URL.set(currentHost.toURI() + currentReq.getURI());
        }
    }
    return isRedirected;
}

From source file:com.github.parisoft.resty.request.retry.RequestRetryHandler.java

private boolean isRequestIdempotent(HttpContext context) {
    final HttpUriRequest request = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    return IdempotentRequestMethods.getInstance().contains(request.getMethod());
}

From source file:com.mxhero.plugin.cloudstorage.onedrive.api.command.HttpRequestRetryHandler.java

@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (executionCount >= retries) {
        logger.debug("no more retries, cancel");
        return false;
    }//from   w  ww .  j a  v a 2s  . c  om
    if (exception instanceof NoHttpResponseException) {
        logger.debug("is NoHttpResponseException, retrying...");
        return true;
    }
    if (exception instanceof ConnectTimeoutException || exception instanceof ConnectionPoolTimeoutException) {
        logger.debug("is ConnectTimeoutException or ConnectionPoolTimeoutException, retrying...");
        return true;
    }
    if (exception instanceof InterruptedIOException) {
        logger.debug("is InterruptedIOException, retrying...");
        return true;
    }
    if (exception instanceof UnknownHostException) {
        logger.debug("is UnknownHostException, cancel");
        return false;
    }
    if (exception instanceof ConnectException) {
        logger.debug("is ConnectException, cancel");
        return false;
    }
    if (exception instanceof SSLException) {
        logger.debug("is SSLException, cancel");
        return false;
    }
    HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    if (idempotent) {
        logger.debug("is idempotent, retrying...");
        return true;
    }
    Boolean b = (Boolean) context.getAttribute(HttpCoreContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b.booleanValue());
    if (!sent) {
        logger.debug("is not sent, retrying...");
        return true;
    }
    return false;
}

From source file:org.esigate.http.OutgoingRequestContext.java

/**
 * @return the actual request sent by th HttpClient.
 */
public HttpRequest getSentRequest() {
    return (HttpRequest) getAttribute(HttpCoreContext.HTTP_REQUEST);
}

From source file:com.normalexception.app.rx8club.html.HtmlFormUtils.java

/**
 * Submit a form and its contents/*from  w  w  w  .  java2  s.  com*/
 * @param url       The url to submit the form to
 * @param nvps      The name value pair of the contents
 * @param attachment If true, add attachment headers
 * @return           True if it worked
 * @throws ClientProtocolExecption
 * @throws IOException
 */
private static boolean formSubmit(String url, List<NameValuePair> nvps, boolean attachment)
        throws ClientProtocolException, IOException {
    HttpClient httpclient = LoginFactory.getInstance().getClient();

    HttpPost httpost = ClientUtils.getHttpPost(url);
    Log.d(TAG, "[Submit] Submit URL: " + url);

    // If there is an attachment, we need to add some data
    // to the post header
    if (attachment) {
        String pN = "";
        for (NameValuePair nvp : nvps) {
            if (nvp.getName().equals(VBulletinKeys.PostNumber.getValue())) {
                pN = nvp.getValue();
                break;
            }
        }

        httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpost.setHeader("Referer", WebUrls.postSubmitAddress + pN);
    }

    httpost.setEntity(new UrlEncodedFormEntity(nvps));

    HttpContext context = LoginFactory.getInstance().getHttpContext();
    HttpResponse response = httpclient.execute(httpost, context);
    HttpEntity entity = response.getEntity();
    StatusLine statusLine = response.getStatusLine();

    Log.d(TAG, "[Submit] Status: " + statusLine.getStatusCode());
    if (entity != null) {
        responseContent = EntityUtils.toString(entity, "UTF-8");

        //httpost.releaseConnection();

        HttpUriRequest request = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);

        responseUrl = request.getURI().toString();
        Log.d(TAG, "[Submit] Response URL: " + responseUrl);

        return true;
    }

    return false;
}

From source file:com.norconex.collector.http.redirect.impl.GenericRedirectURLProvider.java

@Override
public String provideRedirectURL(HttpRequest request, HttpResponse response, HttpContext context) {
    HttpRequest currentReq = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);

    String originalURL = toAbsoluteURI(currentHost, currentReq);

    //--- Location ---
    Header hl = response.getLastHeader(HttpHeaders.LOCATION);
    if (hl == null) {
        //TODO should throw exception instead?
        LOG.error("Redirect detected to a null Location for: " + toAbsoluteURI(currentHost, currentReq));
        return null;
    }//from www .  ja v  a  2  s  .c o  m
    String redirectLocation = hl.getValue();

    //--- Charset ---
    String charset = null;
    Header hc = response.getLastHeader("Content-Type");
    if (hc != null) {
        String contentType = hc.getValue();
        if (contentType.contains(";")) {
            charset = StringUtils.substringAfterLast(contentType, "charset=");
        }
    }
    if (StringUtils.isBlank(charset)) {
        charset = fallbackCharset;
    }

    //--- Build/fix redirect URL ---
    String targetURL = HttpURL.toAbsolute(originalURL, redirectLocation);
    targetURL = resolveRedirectURL(targetURL, charset);

    if (LOG.isDebugEnabled()) {
        LOG.debug("URL redirect: " + originalURL + " -> " + targetURL);
    }
    return targetURL;
}