List of usage examples for org.apache.http.protocol HttpContext getAttribute
Object getAttribute(String str);
From source file:fr.ippon.wip.http.hc.LtpaRequestInterceptor.java
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { PortletRequest portletRequest = HttpClientResourceManager.getInstance().getCurrentPortletRequest(); PortletWindow windowState = PortletWindow.getInstance(portletRequest); WIPConfiguration wipConfig = WIPUtil.getConfiguration(portletRequest); // If it is the first request if (windowState.getActualURL() == null) { // If LTPA SSO enabled for this portlet if (wipConfig.isLtpaSsoAuthentication()) { // Create LTPA cookie & add it ot store String[] valueAndDomain = LtpaCookieUtil.getCookieValueAndDomain(portletRequest, wipConfig); if (valueAndDomain != null) { BasicClientCookie ltpaCookie = new BasicClientCookie(LtpaCookieUtil.COOKIE_NAME, valueAndDomain[0]); if (valueAndDomain[1] != null && !valueAndDomain[1].equals("")) { ltpaCookie.setDomain(valueAndDomain[1]); }/* ww w .ja va 2 s.c o m*/ CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE); cookieStore.addCookie(ltpaCookie); } } } }
From source file:org.artifactory.util.HttpClientConfigurator.java
/** * Produces a {@link ConnectionKeepAliveStrategy} * * @return keep-alive strategy to be used for connection pool *///ww w. j av a2 s. c o m private ConnectionKeepAliveStrategy getConnectionKeepAliveStrategy() { return new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST); if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) { return 5 * 1000; } else { return 30 * 1000; } } }; }
From source file:fr.ippon.wip.http.hc.TransformerResponseInterceptor.java
/** * If httpResponse must be transformed, creates an instance of * WIPTransformer, executes WIPTransformer#transform on the response content * and updates the response entity accordingly. * /*w w w.j av a 2 s. c o m*/ * @param httpResponse * @param context * @throws HttpException * @throws IOException */ public void process(HttpResponse httpResponse, HttpContext context) throws HttpException, IOException { PortletRequest portletRequest = HttpClientResourceManager.getInstance().getCurrentPortletRequest(); PortletResponse portletResponse = HttpClientResourceManager.getInstance().getCurrentPortletResponse(); WIPConfiguration config = WIPUtil.getConfiguration(portletRequest); RequestBuilder request = HttpClientResourceManager.getInstance().getCurrentRequest(); if (httpResponse == null) { // No response -> no transformation LOG.warning("No response to transform."); return; } HttpEntity entity = httpResponse.getEntity(); if (entity == null) { // No entity -> no transformation return; } ContentType contentType = ContentType.getOrDefault(entity); String mimeType = contentType.getMimeType(); String actualURL; RedirectLocations redirectLocations = (RedirectLocations) context .getAttribute("http.protocol.redirect-locations"); if (redirectLocations != null) actualURL = Iterables.getLast(redirectLocations.getAll()).toString(); else if (context.getAttribute(CachingHttpClient.CACHE_RESPONSE_STATUS) == CacheResponseStatus.CACHE_HIT) { actualURL = request.getRequestedURL(); } else { HttpRequest actualRequest = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost actualHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); actualURL = actualHost.toURI() + actualRequest.getRequestLine().getUri(); } // Check if actual URI must be transformed if (!config.isProxyURI(actualURL)) return; // a builder for creating a WIPTransformer instance TransformerBuilder transformerBuilder = new TransformerBuilder().setActualURL(actualURL) .setMimeType(mimeType).setPortletRequest(portletRequest).setPortletResponse(portletResponse) .setResourceType(request.getResourceType()).setXmlReaderPool(xmlReaderPool); // Creates an instance of Transformer depending on ResourceType and // MimeType int status = transformerBuilder.build(); if (status == TransformerBuilder.STATUS_NO_TRANSFORMATION) return; WIPTransformer transformer = transformerBuilder.getTransformer(); // Call WIPTransformer#transform method and update the response Entity // object try { String content = EntityUtils.toString(entity); String transformedContent = ((AbstractTransformer) transformer).transform(content); StringEntity transformedEntity; if (contentType.getCharset() != null) { transformedEntity = new StringEntity(transformedContent, contentType); } else { transformedEntity = new StringEntity(transformedContent); } transformedEntity.setContentType(contentType.toString()); httpResponse.setEntity(transformedEntity); } catch (SAXException e) { LOG.log(Level.SEVERE, "Could not transform HTML", e); throw new IllegalArgumentException(e); } catch (TransformerException e) { LOG.log(Level.SEVERE, "Could not transform HTML", e); throw new IllegalArgumentException(e); } }
From source file:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void test302CachedRedirectTarget() throws Exception { do {//from www .ja v a2 s.co m HttpGet get = new HttpGet("http://example.com/302"); get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); BasicHttpResponse redirect = new BasicHttpResponse(_302); redirect.setHeader("Location", "http://example.com/200"); redirect.setHeader("Cache-Control", "public,max-age=3600"); responses.add(redirect); BasicHttpResponse doc = new BasicHttpResponse(_200); doc.setHeader("Cache-Control", "public,max-age=3600"); responses.add(doc); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); return null; } }); } while (false); do { HttpContext localContext = new BasicHttpContext(); HttpGet get = new HttpGet("http://example.com/302"); get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); BasicHttpResponse redirect = new BasicHttpResponse(_302); redirect.setHeader("Location", "http://example.com/200"); redirect.setHeader("Cache-Control", "public,max-age=3600"); responses.add(redirect); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_302.getStatusCode(), response.getStatusLine().getStatusCode()); return null; } }, localContext); HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); URI root = new URI(host.getSchemeName(), null, host.getHostName(), -1, "/", null, null); assertEquals("http://example.com/302", root.resolve(req.getURI()).toASCIIString()); } while (false); }
From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java
/** * Parses the result and fills the SampleResult with its info * @param httpRequest the executed request * @param localContext the Http context which was used * @param res the SampleResult which is to be filled * @param httpResponse the response which is to be parsed * @throws IllegalStateException/*from w ww .j av a2 s . c o m*/ * @throws IOException */ private void parseResponse(HttpRequestBase httpRequest, HttpContext localContext, HTTPSampleResult res, HttpResponse httpResponse) throws IllegalStateException, IOException { // Needs to be done after execute to pick up all the headers final HttpRequest request = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); // We've finished with the request, so we can add the LocalAddress to it for display final InetAddress localAddr = (InetAddress) httpRequest.getParams() .getParameter(ConnRoutePNames.LOCAL_ADDRESS); if (localAddr != null) { request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString()); } res.setRequestHeaders(getConnectionHeaders(request)); Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (contentType != null) { String ct = contentType.getValue(); res.setContentType(ct); res.setEncodingAndType(ct); } HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); res.setResponseData(readResponse(res, instream, (int) entity.getContentLength())); } res.sampleEnd(); // Done with the sampling proper. currentRequest = null; // Now collect the results into the HTTPSampleResult: StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); res.setResponseCode(Integer.toString(statusCode)); res.setResponseMessage(statusLine.getReasonPhrase()); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseHeaders(getResponseHeaders(httpResponse)); if (res.isRedirect()) { final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException( "Missing location header in redirect for " + httpRequest.getRequestLine()); } String redirectLocation = headerLocation.getValue(); res.setRedirectLocation(redirectLocation); } // record some sizes to allow HTTPSampleResult.getBytes() with different options HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS); long headerBytes = res.getResponseHeaders().length() // condensed length (without \r) + httpResponse.getAllHeaders().length // Add \r for each header + 1 // Add \r for initial header + 2; // final \r\n before data long totalBytes = metrics.getReceivedBytesCount(); res.setHeadersSize((int) headerBytes); res.setBodySize((int) (totalBytes - headerBytes)); if (log.isDebugEnabled()) { log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); URI redirectURI = req.getURI(); if (redirectURI.isAbsolute()) { res.setURL(redirectURI.toURL()); } else { res.setURL(new URL(new URL(target.toURI()), redirectURI.toString())); } } }
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.// w w w. j a va 2s . c o 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.aludratest.service.gui.web.selenium.selenium2.AludraSeleniumHttpCommandExecutor.java
private Response createResponse(HttpResponse httpResponse, HttpContext context) throws IOException { org.openqa.selenium.remote.http.HttpResponse internalResponse = new org.openqa.selenium.remote.http.HttpResponse(); internalResponse.setStatus(httpResponse.getStatusLine().getStatusCode()); for (Header header : httpResponse.getAllHeaders()) { for (HeaderElement headerElement : header.getElements()) { internalResponse.addHeader(header.getName(), headerElement.getValue()); }// ww w .ja va 2s . c o m } HttpEntity entity = httpResponse.getEntity(); if (entity != null) { try { internalResponse.setContent(EntityUtils.toByteArray(entity)); } finally { EntityUtils.consume(entity); } } Response response = responseCodec.decode(internalResponse); if (response.getSessionId() == null) { HttpHost finalHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); String uri = finalHost.toURI(); String sessionId = HttpSessionId.getSessionId(uri); response.setSessionId(sessionId); } return response; }
From source file:com.smartsheet.api.internal.http.DefaultHttpClient.java
/** * Make an HTTP request and return the response. * * @param smartsheetRequest the smartsheet request * @return the HTTP response//from ww w. j ava2 s . com * @throws HttpClientException the HTTP client exception */ public HttpResponse request(HttpRequest smartsheetRequest) throws HttpClientException { Util.throwIfNull(smartsheetRequest); if (smartsheetRequest.getUri() == null) { throw new IllegalArgumentException("A Request URI is required."); } int attempt = 0; long start = System.currentTimeMillis(); HttpRequestBase apacheHttpRequest; HttpResponse smartsheetResponse; InputStream bodyStream = null; if (smartsheetRequest.getEntity() != null && smartsheetRequest.getEntity().getContent() != null) { bodyStream = smartsheetRequest.getEntity().getContent(); } // the retry logic will consume the body stream so we make sure it supports mark/reset and mark it boolean canRetryRequest = bodyStream == null || bodyStream.markSupported(); if (!canRetryRequest) { try { // attempt to wrap the body stream in a input-stream that does support mark/reset bodyStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(bodyStream)); // close the old stream (just to be tidy) and then replace it with a reset-able stream smartsheetRequest.getEntity().getContent().close(); smartsheetRequest.getEntity().setContent(bodyStream); canRetryRequest = true; } catch (IOException ignore) { } } // the retry loop while (true) { apacheHttpRequest = createApacheRequest(smartsheetRequest); // Set HTTP headers if (smartsheetRequest.getHeaders() != null) { for (Map.Entry<String, String> header : smartsheetRequest.getHeaders().entrySet()) { apacheHttpRequest.addHeader(header.getKey(), header.getValue()); } } HttpEntitySnapshot requestEntityCopy = null; HttpEntitySnapshot responseEntityCopy = null; // Set HTTP entity final HttpEntity entity = smartsheetRequest.getEntity(); if (apacheHttpRequest instanceof HttpEntityEnclosingRequestBase && entity != null && entity.getContent() != null) { try { // we need access to the original request stream so we can log it (in the event of errors and/or tracing) requestEntityCopy = new HttpEntitySnapshot(entity); } catch (IOException iox) { logger.error("failed to make copy of original request entity - {}", iox); } InputStreamEntity streamEntity = new InputStreamEntity(entity.getContent(), entity.getContentLength()); streamEntity.setChunked(false); // why? not supported by library? ((HttpEntityEnclosingRequestBase) apacheHttpRequest).setEntity(streamEntity); } // mark the body so we can reset on retry if (canRetryRequest && bodyStream != null) { bodyStream.mark((int) smartsheetRequest.getEntity().getContentLength()); } // Make the HTTP request smartsheetResponse = new HttpResponse(); HttpContext context = new BasicHttpContext(); try { long startTime = System.currentTimeMillis(); apacheHttpResponse = this.httpClient.execute(apacheHttpRequest, context); long endTime = System.currentTimeMillis(); // Set request headers to values ACTUALLY SENT (not just created by us), this would include: // 'Connection', 'Accept-Encoding', etc. However, if a proxy is used, this may be the proxy's CONNECT // request, hence the test for HTTP method first Object httpRequest = context.getAttribute("http.request"); if (httpRequest != null && HttpRequestWrapper.class.isAssignableFrom(httpRequest.getClass())) { HttpRequestWrapper actualRequest = (HttpRequestWrapper) httpRequest; switch (HttpMethod.valueOf(actualRequest.getMethod())) { case GET: case POST: case PUT: case DELETE: apacheHttpRequest.setHeaders(((HttpRequestWrapper) httpRequest).getAllHeaders()); break; } } // Set returned headers smartsheetResponse.setHeaders(new HashMap<String, String>()); for (Header header : apacheHttpResponse.getAllHeaders()) { smartsheetResponse.getHeaders().put(header.getName(), header.getValue()); } smartsheetResponse.setStatus(apacheHttpResponse.getStatusLine().getStatusCode(), apacheHttpResponse.getStatusLine().toString()); // Set returned entities if (apacheHttpResponse.getEntity() != null) { HttpEntity httpEntity = new HttpEntity(); httpEntity.setContentType(apacheHttpResponse.getEntity().getContentType().getValue()); httpEntity.setContentLength(apacheHttpResponse.getEntity().getContentLength()); httpEntity.setContent(apacheHttpResponse.getEntity().getContent()); smartsheetResponse.setEntity(httpEntity); responseEntityCopy = new HttpEntitySnapshot(httpEntity); } long responseTime = endTime - startTime; logRequest(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, responseTime); if (traces.size() > 0) { // trace-logging of request and response (if so configured) RequestAndResponseData requestAndResponseData = RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, traces); TRACE_WRITER.println(requestAndResponseData.toString(tracePrettyPrint)); } if (smartsheetResponse.getStatusCode() == 200) { // call successful, exit the retry loop break; } // the retry logic might consume the content stream so we make sure it supports mark/reset and mark it InputStream contentStream = smartsheetResponse.getEntity().getContent(); if (!contentStream.markSupported()) { // wrap the response stream in a input-stream that does support mark/reset contentStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(contentStream)); // close the old stream (just to be tidy) and then replace it with a reset-able stream smartsheetResponse.getEntity().getContent().close(); smartsheetResponse.getEntity().setContent(contentStream); } try { contentStream.mark((int) smartsheetResponse.getEntity().getContentLength()); long timeSpent = System.currentTimeMillis() - start; if (!shouldRetry(++attempt, timeSpent, smartsheetResponse)) { // should not retry, or retry time exceeded, exit the retry loop break; } } finally { if (bodyStream != null) { bodyStream.reset(); } contentStream.reset(); } // moving this to finally causes issues because socket is closed (which means response stream is closed) this.releaseConnection(); } catch (ClientProtocolException e) { try { logger.warn("ClientProtocolException " + e.getMessage()); logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY)); // if this is a PUT and was retried by the http client, the body content stream is at the // end and is a NonRepeatableRequest. If we marked the body content stream prior to execute, // reset and retry if (canRetryRequest && e.getCause() instanceof NonRepeatableRequestException) { if (smartsheetRequest.getEntity() != null) { smartsheetRequest.getEntity().getContent().reset(); } continue; } } catch (IOException ignore) { } throw new HttpClientException("Error occurred.", e); } catch (NoHttpResponseException e) { try { logger.warn("NoHttpResponseException " + e.getMessage()); logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY)); // check to see if the response was empty and this was a POST. All other HTTP methods // will be automatically retried by the http client. // (POST is non-idempotent and is not retried automatically, but is safe for us to retry) if (canRetryRequest && smartsheetRequest.getMethod() == HttpMethod.POST) { if (smartsheetRequest.getEntity() != null) { smartsheetRequest.getEntity().getContent().reset(); } continue; } } catch (IOException ignore) { } throw new HttpClientException("Error occurred.", e); } catch (IOException e) { try { logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY)); } catch (IOException ignore) { } throw new HttpClientException("Error occurred.", e); } } return smartsheetResponse; }