List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:ch.entwine.weblounge.test.harness.content.ImagesTest.java
/** * Tests for the correctness of the German scaled image response. * // ww w . j a v a2s . co m * @param response * the http response * @param style * the image style */ @SuppressWarnings("cast") private void testGermanScaled(HttpUriRequest request, ImageStyle style, List<String> eTags) throws Exception { HttpClient httpClient = new DefaultHttpClient(); String eTagValue = null; Date modificationDate = null; try { logger.info("Requesting scaled German image '{}' at {}", style.getIdentifier(), request.getURI()); HttpResponse response = TestUtils.request(httpClient, request, null); assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); assertTrue("Response did not contain any content", response.getEntity().getContentLength() > 0); // Test general headers assertEquals(1, response.getHeaders("Content-Type").length); assertEquals(mimetypeGerman, response.getHeaders("Content-Type")[0].getValue()); assertEquals(1, response.getHeaders("Content-Disposition").length); SeekableStream seekableInputStream = null; StringBuilder fileName = new StringBuilder(FilenameUtils.getBaseName(filenameGerman)); try { // Test file size if (!ImageScalingMode.None.equals(style.getScalingMode())) { float scale = ImageStyleUtils.getScale(originalWidth, originalHeight, style); int scaledWidth = (int) Math.round(originalWidth * scale) - (int) ImageStyleUtils .getCropX(Math.round(originalWidth * scale), Math.round(originalHeight * scale), style); int scaledHeight = (int) Math.round(originalHeight * scale) - (int) ImageStyleUtils .getCropY(Math.round(originalWidth * scale), Math.round(originalHeight * scale), style); // Load the image from the given input stream seekableInputStream = new FileCacheSeekableStream(response.getEntity().getContent()); RenderedOp image = JAI.create("stream", seekableInputStream); if (image == null) throw new IOException("Error reading image from input stream"); // Get the original image size int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); assertEquals(scaledHeight, imageHeight, 1); assertEquals(scaledWidth, imageWidth, 1); } fileName.append("-").append(style.getIdentifier()); } finally { IOUtils.closeQuietly(seekableInputStream); } // Test filename fileName.append(".").append(FilenameUtils.getExtension(filenameGerman)); String contentDisposition = response.getHeaders("Content-Disposition")[0].getValue(); assertTrue(contentDisposition.startsWith("inline; filename=" + fileName.toString())); // Test ETag header Header eTagHeader = response.getFirstHeader("ETag"); assertNotNull(eTagHeader); assertNotNull(eTagHeader.getValue()); eTagValue = eTagHeader.getValue(); // Make sure ETags are created in a proper way (no duplicates) assertFalse("Duplicate ETag returned", eTags.contains(eTagValue)); if (!"none".equals(style.getIdentifier())) { eTags.add(eTagValue); } // Test Last-Modified header Header modifiedHeader = response.getFirstHeader("Last-Modified"); assertNotNull(modifiedHeader); modificationDate = lastModifiedDateFormat.parse(modifiedHeader.getValue()); } finally { eTags.clear(); httpClient.getConnectionManager().shutdown(); } TestSiteUtils.testETagHeader(request, eTagValue, logger, null); TestSiteUtils.testModifiedHeader(request, modificationDate, logger, null); }
From source file:ch.entwine.weblounge.test.harness.content.ImagesTest.java
/** * Tests for the correctness of the English scaled image response. * //from w ww.j a v a 2 s . c om * @param response * the http response * @param style * the image style */ @SuppressWarnings("cast") private void testEnglishScaled(HttpUriRequest request, ImageStyle style, List<String> eTags) throws Exception { HttpClient httpClient = new DefaultHttpClient(); String eTagValue = null; Date modificationDate = null; try { logger.info("Requesting scaled English image '{}' at {}", style.getIdentifier(), request.getURI()); HttpResponse response = TestUtils.request(httpClient, request, null); assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); assertTrue("Response did not contain any content", response.getEntity().getContentLength() > 0); // Test general headers assertEquals(1, response.getHeaders("Content-Type").length); assertEquals(mimetypeEnglish, response.getHeaders("Content-Type")[0].getValue()); assertEquals(1, response.getHeaders("Content-Disposition").length); SeekableStream seekableInputStream = null; StringBuilder fileName = new StringBuilder(FilenameUtils.getBaseName(filenameEnglish)); try { // Test file size if (!ImageScalingMode.None.equals(style.getScalingMode())) { float scale = ImageStyleUtils.getScale(originalWidth, originalHeight, style); int scaledWidth = (int) Math.round(originalWidth * scale) - (int) ImageStyleUtils .getCropX(Math.round(originalWidth * scale), Math.round(originalHeight * scale), style); int scaledHeight = (int) Math.round(originalHeight * scale) - (int) ImageStyleUtils .getCropY(Math.round(originalWidth * scale), Math.round(originalHeight * scale), style); // Load the image from the given input stream seekableInputStream = new MemoryCacheSeekableStream(response.getEntity().getContent()); RenderedOp image = JAI.create("stream", seekableInputStream); if (image == null) throw new IOException("Error reading image from input stream"); // Get the actual image size int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); assertEquals(scaledHeight, imageHeight, 1); assertEquals(scaledWidth, imageWidth, 1); } fileName.append("-").append(style.getIdentifier()); } finally { IOUtils.closeQuietly(seekableInputStream); } // Test filename fileName.append(".").append(FilenameUtils.getExtension(filenameEnglish)); String contentDisposition = response.getHeaders("Content-Disposition")[0].getValue(); assertTrue(contentDisposition.startsWith("inline; filename=" + fileName.toString())); // Test ETag header Header eTagHeader = response.getFirstHeader("ETag"); assertNotNull(eTagHeader); assertNotNull(eTagHeader.getValue()); eTagValue = eTagHeader.getValue(); // Make sure ETags are created in a proper way (no duplicates) assertFalse("Duplicate ETag returned", eTags.contains(eTagValue)); if (!"none".equals(style.getIdentifier())) { eTags.add(eTagValue); } // Test Last-Modified header Header modifiedHeader = response.getFirstHeader("Last-Modified"); assertNotNull(modifiedHeader); modificationDate = lastModifiedDateFormat.parse(modifiedHeader.getValue()); } finally { eTags.clear(); httpClient.getConnectionManager().shutdown(); } TestSiteUtils.testETagHeader(request, eTagValue, logger, null); TestSiteUtils.testModifiedHeader(request, modificationDate, logger, null); }
From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaDispatch.java
@Override protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException { HttpResponse inboundResponse = null; try {/*from w w w . j av a 2 s.co m*/ inboundResponse = executeOutboundRequest(outboundRequest); writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse); } catch (StandbyException e) { LOG.errorReceivedFromStandbyNode(e); failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e); } catch (SafeModeException e) { LOG.errorReceivedFromSafeModeNode(e); retryRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e); } catch (IOException e) { LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e); failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e); } }
From source file:org.elasticsearch.client.RestClientMultipleHostsTests.java
@Before @SuppressWarnings("unchecked") public void createRestClient() throws IOException { CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class); when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))) .thenAnswer(new Answer<Future<HttpResponse>>() { @Override public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable { HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock .getArguments()[0]; HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest(); HttpHost httpHost = requestProducer.getTarget(); HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2]; assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class)); FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock .getArguments()[3]; //return the desired status code or exception depending on the path if (request.getURI().getPath().equals("/soe")) { futureCallback.failed(new SocketTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/coe")) { futureCallback.failed(new ConnectTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/ioe")) { futureCallback.failed(new IOException(httpHost.toString())); } else { int statusCode = Integer.parseInt(request.getURI().getPath().substring(1)); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, ""); futureCallback.completed(new BasicHttpResponse(statusLine)); }/*from w w w . j av a 2 s. c om*/ return null; } }); int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5); httpHosts = new HttpHost[numHosts]; for (int i = 0; i < numHosts; i++) { httpHosts[i] = new HttpHost("localhost", 9200 + i); } failureListener = new HostsTrackingFailureListener(); restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener); }
From source file:com.socialize.net.AsyncHttpRequestProcessor.java
@Override protected AsyncHttpResponse doInBackground(AsyncHttpRequest... params) { AsyncHttpRequest request = params[0]; AsyncHttpResponse response = new AsyncHttpResponse(); response.setRequest(request);//from w w w . jav a 2 s. c o m try { HttpUriRequest httpRequest = request.getRequest(); if (!clientFactory.isDestroyed()) { if (logger != null && logger.isDebugEnabled()) { logger.debug( "Request: " + httpRequest.getMethod() + " " + httpRequest.getRequestLine().getUri()); StringBuilder builder = new StringBuilder(); Header[] allHeaders = httpRequest.getAllHeaders(); for (Header header : allHeaders) { builder.append(header.getName()); builder.append(":"); builder.append(header.getValue()); builder.append("\n"); } logger.debug("REQUEST \nurl:[" + httpRequest.getURI().toString() + "] \nheaders:\n" + builder.toString()); if (httpRequest instanceof HttpPost) { HttpPost post = (HttpPost) httpRequest; HttpEntity entity = post.getEntity(); if (!(entity instanceof MultipartEntity)) { String requestData = ioUtils.readSafe(entity.getContent()); logger.debug("REQUEST \ndata:[" + requestData + "]"); } } } HttpClient client = clientFactory.getClient(); HttpResponse httpResponse = client.execute(httpRequest); response.setResponse(httpResponse); if (logger != null && logger.isDebugEnabled()) { logger.debug("RESPONSE CODE: " + httpResponse.getStatusLine().getStatusCode()); } HttpEntity entity = null; try { entity = httpResponse.getEntity(); if (httpUtils.isHttpError(httpResponse)) { String msg = ioUtils.readSafe(entity.getContent()); throw new SocializeApiError(httpUtils, httpResponse.getStatusLine().getStatusCode(), msg); } else { String responseData = ioUtils.readSafe(entity.getContent()); if (logger != null && logger.isDebugEnabled()) { logger.debug("RESPONSE: " + responseData); } response.setResponseData(responseData); } } finally { closeEntity(entity); } } else { throw new SocializeException("Cannot execute http request. HttpClient factory was destroyed."); } } catch (Exception e) { response.setError(e); } return response; }
From source file:com.jgoetsch.eventtrader.source.HttpPollingMsgSource.java
public void receiveMsgs(HttpClient client) { NewMsgHandler msgHandler = new NewMsgHandler(); HttpUriRequest req = createRequest(); for (;;) {/*from w w w . ja va 2s .c om*/ HttpEntity entity = null; try { if (isUseIfModifiedSince() && lastModifiedDate != null) req.setHeader("If-Modified-Since", lastModifiedDate); long startTime = System.currentTimeMillis(); HttpResponse rsp = client.execute(req); if (rsp.containsHeader("Last-Modified")) { lastModifiedDate = rsp.getFirstHeader("Last-Modified").getValue(); //log.debug("Resource last modified: " + lastModifiedDate); } entity = rsp.getEntity(); if (rsp.getStatusLine().getStatusCode() >= 400) { log.warn("HTTP request to " + req.getURI().getHost() + " failed [" + rsp.getStatusLine().getStatusCode() + " " + rsp.getStatusLine().getReasonPhrase() + ", " + (System.currentTimeMillis() - startTime) + " ms]"); // 400 level error should be unrecoverable so just quit out if (rsp.getStatusLine().getStatusCode() < 500) return; else { // give server some more time to recover before retrying if it returned 500 level error // probably means site crashed and continuing to hit it will only make things worse try { Thread.sleep(pollingInterval * 6); } catch (InterruptedException e) { } } } else { boolean bContinue = true; if (entity != null && rsp.getStatusLine().getStatusCode() != 304) { // 304 = not modified bContinue = getMsgParser().parseContent(entity.getContent(), entity.getContentLength(), entity.getContentType() == null ? null : entity.getContentType().getValue(), msgHandler); msgHandler.nextPass(); } if (log.isDebugEnabled()) { log.debug( "Checked site at " + req.getURI().getHost() + " [" + rsp.getStatusLine().getStatusCode() + " " + rsp.getStatusLine().getReasonPhrase() + ", " + (entity != null ? (entity.getContentLength() != -1 ? entity.getContentLength() + " bytes, " : "unknown length, ") : "") + (System.currentTimeMillis() - startTime) + " ms]"); } if (!bContinue) return; } } catch (IOException e) { log.warn(e.getClass() + ": " + e.getMessage()); } catch (Exception e) { log.warn(e.getClass() + ": " + e.getMessage(), e); } finally { if (entity != null) { // release connection gracefully try { entity.consumeContent(); } catch (IOException e) { } } } delay(); } }
From source file:com.akop.bach.parser.Parser.java
protected void submitRequest(HttpUriRequest request) throws IOException { request.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); request.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*"); if (App.getConfig().logToConsole()) App.logv("Parser: Fetching %s", request.getURI()); long started = System.currentTimeMillis(); initRequest(request);//from w w w.ja va 2 s. c om try { synchronized (mHttpClient) { mLastResponse = mHttpClient.execute(request); HttpEntity entity = mLastResponse.getEntity(); if (entity != null) entity.consumeContent(); } } finally { if (App.getConfig().logToConsole()) displayTimeTaken("Parser: Fetch took", started); } }
From source file:lucee.runtime.tag.Http.java
public static URL locationURL(HttpUriRequest req, HttpResponse rsp) { URL url = null;/*from w w w . j a va 2 s.c om*/ try { url = req.getURI().toURL(); } catch (MalformedURLException e1) { return null; } Header h = HTTPResponse4Impl.getLastHeaderIgnoreCase(rsp, "location"); if (h != null) { String str = h.getValue(); try { return new URL(str); } catch (MalformedURLException e) { try { return new URL(url.getProtocol(), url.getHost(), url.getPort(), mergePath(url.getFile(), str)); } catch (MalformedURLException e1) { return null; } } } return null; }
From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaBaseDispatcher.java
@Override protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException { HttpResponse inboundResponse = this.getInboundResponse(); try {//from w w w.j a va 2s . c om if (this.getInboundResponse() == null) { inboundResponse = executeOutboundRequest(outboundRequest); } writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse); } catch (StandbyException e) { LOG.errorReceivedFromStandbyNode(e); failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e); } catch (SafeModeException e) { LOG.errorReceivedFromSafeModeNode(e); retryRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e); } catch (IOException e) { LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e); failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e); } }
From source file:com.keydap.sparrow.SparrowClient.java
/** * Sends the given request to the server * /* www .j av a 2 s . co m*/ * @param req the HTTP request * @param resClas class of the resourcetype * @return */ public <T> Response<T> sendRawRequest(HttpUriRequest req, Class<T> resClas) { Response<T> result = new Response<T>(); try { authenticator.addHeaders(req); LOG.debug("Sending {} request to {}", req.getMethod(), req.getURI()); HttpResponse resp = client.execute(req); authenticator.saveHeaders(resp); StatusLine sl = resp.getStatusLine(); int code = sl.getStatusCode(); LOG.debug("Received status code {} from the request to {}", code, req.getURI()); HttpEntity entity = resp.getEntity(); String json = null; if (entity != null) { json = EntityUtils.toString(entity); } result.setHttpCode(code); // if it is success there will be response body to read if (code == SC_OK || code == SC_CREATED || code == SC_NOT_MODIFIED) { if (json != null) { // some responses have no body, so check for null T t = unmarshal(json, resClas); result.setResource(t); } } else { if (json != null) { Error error = serializer.fromJson(json, Error.class); result.setError(error); } } result.setHttpBody(json); result.setHeaders(resp.getAllHeaders()); } catch (Exception e) { LOG.warn("", e); result.setHttpCode(-1); Error err = new Error(); err.setDetail(e.getMessage()); result.setError(err); } return result; }