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:mobi.jenkinsci.alm.assembla.client.AssemblaClient.java

private URL getLatestRedirectedUrl() {
    try {/* w  w w .j ava  2s .c o m*/
        final HttpRequest request = (HttpRequest) httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        final HttpHost host = (HttpHost) httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        if (host.getPort() <= 0) {
            return new URL(host.getSchemeName(), host.getHostName(), request.getRequestLine().getUri());
        } else {
            return new URL(host.getSchemeName(), host.getHostName(), host.getPort(),
                    request.getRequestLine().getUri());
        }
    } catch (final MalformedURLException e) {
        throw new IllegalArgumentException("Cannot get last redirected URL from HTTP Context", e);
    }
}

From source file:com.ittm_solutions.ipacore.IpaApi.java

/**
 * Returns the final URI in a redirect chain of a request.
 *
 * @param context/*from  w  ww .  j a  v  a 2  s .co  m*/
 *            client context as returned by {@code clientContext}
 * @return URI
 */
private static URI currentRedirectUri(HttpClientContext context) {
    HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    URI uri = null;
    try {
        uri = ((currentReq.getURI().isAbsolute()) ? currentReq.getURI()
                : (new URI(currentHost.toURI() + currentReq.getURI())));
    } catch (URISyntaxException e) {
        // this should never happen
        throw new RuntimeException(e);
    }
    return uri;
}

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

@Test
public void testAbsoluteRequestURIWithFragment() throws Exception {
    register("*", new SimpleService());
    final HttpHost target = getServerHttp();

    final URI uri = new URIBuilder().setHost(target.getHostName()).setPort(target.getPort())
            .setScheme(target.getSchemeName()).setPath("/stuff").setFragment("blahblah").build();

    final HttpGet httpget = new HttpGet(uri);
    final HttpClientContext context = HttpClientContext.create();

    final HttpResponse response = this.httpclient.execute(httpget, context);
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    final HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    Assert.assertEquals("/stuff", request.getRequestLine().getUri());

    final URI location = getHttpLocation(httpget, context);
    Assert.assertEquals(uri, location);//www  . j  a v a  2 s.c  o  m
}

From source file:org.wildfly.camel.test.olingo4.Olingo4IntegrationTest.java

private String getRealServiceUrl(String baseUrl) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(baseUrl);
    HttpContext httpContext = new BasicHttpContext();
    httpclient.execute(httpGet, httpContext);
    HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString()
            : (currentHost.toURI() + currentReq.getURI());

    return currentUrl;
}

From source file:cn.wanghaomiao.seimi.core.SeimiProcessor.java

private String getRealUrl(HttpContext httpContext) {
    Object target = httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    Object reqUri = httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
    if (target == null || reqUri == null) {
        return null;
    }/*  w  w  w  .j a  va 2s  . c  om*/
    HttpHost t = (HttpHost) target;
    HttpUriRequest r = (HttpUriRequest) reqUri;
    return r.getURI().isAbsolute() ? r.getURI().toString() : t.toString() + r.getURI().toString();
}

From source file:com.googlecode.jdeltasync.DeltaSyncClient.java

private <T> T post(final IDeltaSyncSession session, String uri, final String userAgent,
        final String contentType, final byte[] data, final UriCapturingResponseHandler<T> handler)
        throws DeltaSyncException, IOException {

    final HttpPost post = createHttpPost(uri, userAgent, contentType, data);
    final HttpContext context = new BasicHttpContext();
    context.setAttribute(HttpClientContext.COOKIE_STORE, session.getCookieStore());

    try {/*from   ww  w. j  av  a 2 s  .c  o  m*/

        return httpClient.execute(post, new ResponseHandler<T>() {
            public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                try {
                    if (isRedirect(response)) {
                        URI redirectUri = getRedirectLocationURI(session, post, response, context);
                        return post(session, redirectUri.toString(), userAgent, contentType, data, handler);
                    }

                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        throw new HttpException(response.getStatusLine().getStatusCode(),
                                response.getStatusLine().getReasonPhrase());
                    }

                    HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
                    HttpHost host = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
                    URI uri;
                    try {
                        if (request instanceof HttpUriRequest) {
                            uri = ((HttpUriRequest) request).getURI();
                        } else {
                            uri = new URI(request.getRequestLine().getUri());
                        }
                        if (!uri.isAbsolute()) {
                            uri = URIUtils.rewriteURI(uri, host);
                        }
                    } catch (URISyntaxException e) {
                        throw new DeltaSyncException(e);
                    }
                    return handler.handle(uri, response);
                } catch (DeltaSyncException e) {
                    throw new RuntimeException(e);
                }
            }
        }, context);

    } catch (RuntimeException e) {
        Throwable t = e.getCause();
        while (t != null) {
            if (t instanceof DeltaSyncException) {
                throw (DeltaSyncException) t;
            }
            t = t.getCause();
        }
        throw e;
    }
}

From source file:crawlercommons.fetcher.http.SimpleHttpFetcher.java

private String extractRedirectedUrl(String url, HttpContext localContext) {
    // This was triggered by HttpClient with the redirect count was
    // exceeded.//from   w  w w. j  a v  a2 s  . co m
    HttpHost host = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    HttpUriRequest finalRequest = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);

    try {
        URL hostUrl = new URI(host.toURI()).toURL();
        return new URL(hostUrl, finalRequest.getURI().toString()).toExternalForm();
    } catch (MalformedURLException e) {
        LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI());
        return url;
    } catch (URISyntaxException e) {
        LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI());
        return url;
    }
}

From source file:org.apache.http.impl.client.cache.CachingHttpAsyncClient.java

private void handleCacheHit(final BasicFuture<HttpResponse> future, final HttpHost target,
        final HttpRequestWrapper request, final HttpCacheContext clientContext, final HttpCacheEntry entry)
        throws IOException {
    recordCacheHit(target, request);//from  w  ww  .java  2 s .  c om
    final HttpResponse out;
    final Date now = getCurrentDate();
    if (this.suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
        log.debug("Cache hit");
        out = generateCachedResponse(request, clientContext, entry, now);
    } else if (!mayCallBackend(request)) {
        log.debug("Cache entry not suitable but only-if-cached requested");
        out = generateGatewayTimeout(clientContext);
    } else if (validityPolicy.isRevalidatable(entry) && !(entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED
            && !suitabilityChecker.isConditional(request))) {
        log.debug("Revalidating cache entry");
        revalidateCacheEntry(future, target, request, clientContext, entry, now);
        return;
    } else {
        log.debug("Cache entry not usable; calling backend");
        callBackend(future, target, request, clientContext);
        return;
    }
    clientContext.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(target));
    clientContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    clientContext.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
    clientContext.setAttribute(HttpCoreContext.HTTP_RESPONSE, out);
    clientContext.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.TRUE);
    future.completed(out);
}

From source file:org.apache.http.impl.execchain.MinimalClientExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    rewriteRequestURI(request, route);// w  ww  . j  a  v  a2 s . c  o  m

    final ConnectionRequest connRequest = connManager.requestConnection(route, null);
    if (execAware != null) {
        if (execAware.isAborted()) {
            connRequest.cancel();
            throw new RequestAbortedException("Request aborted");
        } else {
            execAware.setCancellable(connRequest);
        }
    }

    final RequestConfig config = context.getRequestConfig();

    final HttpClientConnection managedConn;
    try {
        final int timeout = config.getConnectionRequestTimeout();
        managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS);
    } catch (final InterruptedException interrupted) {
        Thread.currentThread().interrupt();
        throw new RequestAbortedException("Request aborted", interrupted);
    } catch (final ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        throw new RequestAbortedException("Request execution failed", cause);
    }

    final ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn);
    try {
        if (execAware != null) {
            if (execAware.isAborted()) {
                releaseTrigger.close();
                throw new RequestAbortedException("Request aborted");
            } else {
                execAware.setCancellable(releaseTrigger);
            }
        }

        if (!managedConn.isOpen()) {
            final int timeout = config.getConnectTimeout();
            this.connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context);
            this.connManager.routeComplete(managedConn, route, context);
        }
        final int timeout = config.getSocketTimeout();
        if (timeout >= 0) {
            managedConn.setSocketTimeout(timeout);
        }

        HttpHost target = null;
        final HttpRequest original = request.getOriginal();
        if (original instanceof HttpUriRequest) {
            final URI uri = ((HttpUriRequest) original).getURI();
            if (uri.isAbsolute()) {
                target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
            }
        }
        if (target == null) {
            target = route.getTargetHost();
        }

        context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
        context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);
        context.setAttribute(HttpClientContext.HTTP_ROUTE, route);

        httpProcessor.process(request, context);
        final HttpResponse response = requestExecutor.execute(request, managedConn, context);
        httpProcessor.process(response, context);

        // The connection is in or can be brought to a re-usable state.
        if (reuseStrategy.keepAlive(response, context)) {
            // Set the idle duration of this connection
            final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
            releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS);
            releaseTrigger.markReusable();
        } else {
            releaseTrigger.markNonReusable();
        }

        // check for entity, release connection if possible
        final HttpEntity entity = response.getEntity();
        if (entity == null || !entity.isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            releaseTrigger.releaseConnection();
            return Proxies.enhanceResponse(response, null);
        } else {
            return Proxies.enhanceResponse(response, releaseTrigger);
        }
    } catch (final ConnectionShutdownException ex) {
        final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (final HttpException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    } catch (final IOException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    } catch (final RuntimeException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    }
}