List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:tech.sirwellington.alchemy.http.AlchemyRequestMapperTest.java
@Test public void testGet() throws Exception { instance = AlchemyRequestMapper.GET; assertThat(instance, notNullValue()); HttpUriRequest result = instance.convertToApacheRequest(request); assertThat(result, notNullValue());/* w w w. j av a 2 s .co m*/ assertThat(result.getURI(), is(url.toURI())); assertThat(result, instanceOf(HttpGet.class)); }
From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java
@Test public void testJiraKnox58() throws URISyntaxException, IOException { URI uri = new URI("http://unreachable-host"); BasicHttpParams params = new BasicHttpParams(); HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpUriRequest.class); EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes(); EasyMock.expect(outboundRequest.getURI()).andReturn(uri).anyTimes(); EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes(); HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class); HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.expect(outboundResponse.getOutputStream()) .andAnswer(new IAnswer<SynchronousServletOutputStreamAdapter>() { @Override//from ww w . j a v a 2s . c o m public SynchronousServletOutputStreamAdapter answer() throws Throwable { return new SynchronousServletOutputStreamAdapter() { @Override public void write(int b) throws IOException { throw new IOException("unreachable-host"); } }; } }); EasyMock.replay(outboundRequest, inboundRequest, outboundResponse); DefaultDispatch dispatch = new DefaultDispatch(); dispatch.setHttpClient(new DefaultHttpClient()); try { dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse); fail("Should have thrown IOException"); } catch (IOException e) { assertThat(e.getMessage(), not(containsString("unreachable-host"))); assertThat(e, not(instanceOf(UnknownHostException.class))); assertThat("Message needs meaningful content.", e.getMessage().trim().length(), greaterThan(12)); } }
From source file:org.dataconservancy.ui.it.support.HttpAssert.java
public static void assertStatus(HttpClient hc, HttpUriRequest url, int statusFrom, int statusTo, String message, ResponseHolder holder) {/* ww w . j av a2s . co m*/ assertValidStatusRange(statusFrom, statusTo); boolean range = (statusFrom != statusTo); HttpResponse res = null; try { res = hc.execute(url); if (isLogging) { logRequest(url); logResponse(res); } final StatusLine statusLine = res.getStatusLine(); final int rc = statusLine.getStatusCode(); if (holder != null) holder.statusCode = rc; if (holder != null && res.getFirstHeader("Location") != null) holder.locationHeader = res.getFirstHeader("Location").getValue(); final String reasonPhrase = (statusLine.getReasonPhrase() == null ? "<reason phrase was empty>" : statusLine.getReasonPhrase()); if (range) { String assertionMessage = null; if (message == null) { assertionMessage = String.format(STATUS_FAIL_RANGE, rc, url.getURI().toString(), statusFrom, statusTo, reasonPhrase); } else { assertionMessage = String.format(STATUS_FAIL_RANGE_WITH_MESSAGE, message, rc, url.getURI().toString(), statusFrom, statusTo, reasonPhrase); } if (holder != null) holder.reasonPhrase = assertionMessage; assertTrue(assertionMessage, statusFrom <= rc && rc <= statusTo); } else { String assertionMessage = null; if (message == null) { assertionMessage = String.format(STATUS_FAIL, rc, url.getURI().toString(), statusFrom, reasonPhrase); } else { assertionMessage = String.format(STATUS_FAIL_WITH_MESSAGE, message, rc, url.getURI().toString(), statusFrom, reasonPhrase); } if (holder != null) holder.reasonPhrase = assertionMessage; assertEquals(assertionMessage, statusFrom, rc); } if (holder != null) { holder.body = freeAndCopy(res); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (res != null) { free(res); } } }
From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java
protected HttpResponse executeOutboundRequest(HttpUriRequest outboundRequest) throws IOException { LOG.dispatchRequest(outboundRequest.getMethod(), outboundRequest.getURI()); HttpResponse inboundResponse;//from w ww.j a v a 2 s. c om try { auditor.audit(Action.DISPATCH, outboundRequest.getURI().toString(), ResourceType.URI, ActionOutcome.UNAVAILABLE, RES.requestMethod(outboundRequest.getMethod())); if (!"true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) { // Hadoop cluster not Kerberos enabled addCredentialsToRequest(outboundRequest); } inboundResponse = client.execute(outboundRequest); int statusCode = inboundResponse.getStatusLine().getStatusCode(); if (statusCode != 201) { LOG.dispatchResponseStatusCode(statusCode); } else { Header location = inboundResponse.getFirstHeader("Location"); if (location == null) { LOG.dispatchResponseStatusCode(statusCode); } else { LOG.dispatchResponseCreatedStatusCode(statusCode, location.getValue()); } } auditor.audit(Action.DISPATCH, outboundRequest.getURI().toString(), ResourceType.URI, ActionOutcome.SUCCESS, RES.responseStatus(statusCode)); } catch (Exception e) { // We do not want to expose back end host. port end points to clients, see JIRA KNOX-58 auditor.audit(Action.DISPATCH, outboundRequest.getURI().toString(), ResourceType.URI, ActionOutcome.FAILURE); LOG.dispatchServiceConnectionException(outboundRequest.getURI(), e); throw new IOException(RES.dispatchConnectionError()); } return inboundResponse; }
From source file:org.apache.hadoop.gateway.dispatch.HttpClientDispatch.java
protected HttpResponse executeOutboundRequest(HttpUriRequest outboundRequest) throws IOException { LOG.dispatchRequest(outboundRequest.getMethod(), outboundRequest.getURI()); HttpResponse inboundResponse = null; DefaultHttpClient client = new DefaultHttpClient(); try {// w ww . j a v a 2s. c o m String query = outboundRequest.getURI().getQuery(); if (!"true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) { // Hadoop cluster not Kerberos enabled addCredentialsToRequest(outboundRequest); inboundResponse = client.execute(outboundRequest); } else if (query.contains(Q_DELEGATION_EQ) || // query string carries delegation token query.contains(AMP_DELEGATION_EQ)) { inboundResponse = client.execute(outboundRequest); } else { // Kerberos secured, no delegation token in query string inboundResponse = executeKerberosDispatch(outboundRequest, client); } } catch (IOException e) { // we do not want to expose back end host. port end points to clients, see JIRA KNOX-58 LOG.dispatchServiceConnectionException(outboundRequest.getURI(), e); auditor.audit(Action.DISPATCH, outboundRequest.getURI().toString(), ResourceType.URI, ActionOutcome.FAILURE); throw new IOException(RES.dispatchConnectionError()); } finally { if (inboundResponse != null) { int statusCode = inboundResponse.getStatusLine().getStatusCode(); if (statusCode != 201) { LOG.dispatchResponseStatusCode(statusCode); } else { Header location = inboundResponse.getFirstHeader("Location"); if (location == null) { LOG.dispatchResponseStatusCode(statusCode); } else { LOG.dispatchResponseCreatedStatusCode(statusCode, location.getValue()); } } auditor.audit(Action.DISPATCH, outboundRequest.getURI().toString(), ResourceType.URI, ActionOutcome.SUCCESS, RES.responseStatus(statusCode)); } else { auditor.audit(Action.DISPATCH, outboundRequest.getURI().toString(), ResourceType.URI, ActionOutcome.UNAVAILABLE); } } return inboundResponse; }
From source file:org.opencastproject.workflow.handler.HttpNotificationWorkflowOperationHandler.java
/** * Execute the given notification request. If the target is not responding, retry as many time as the maxAttampts * parameter with in between each try a sleep time. * * @param request/*from w w w . j a v a2 s .c o m*/ * The request to execute * @param maxAttempts * The number of attempts in case of error * @param timeout * The wait time in milliseconds at which a connection attempt will throw * @return true if the request has been executed successfully */ private boolean executeRequest(HttpUriRequest request, int maxAttempts, int timeout, int sleepTime) { logger.debug(format("Executing notification request on target %s, %d attemps left", request.getURI(), maxAttempts)); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); HttpResponse response; try { response = httpClient.execute(request); } catch (ClientProtocolException e) { logger.error(format("Protocol error during execution of query on target %s: %s", request.getURI(), e.getMessage())); return false; } catch (IOException e) { logger.error(format("I/O error during execution of query on target %s: %s", request.getURI(), e.getMessage())); return false; } Integer statusCode = response.getStatusLine().getStatusCode(); if (statusCode == SC_OK || statusCode == SC_NO_CONTENT || statusCode == SC_ACCEPTED) { logger.debug(format("Request successfully executed on target %s, status code: %d", request.getURI(), statusCode)); return true; } else if (maxAttempts > 1) { logger.debug(format("Request failed on target %s, status code: %d, will retry in %d seconds", request.getURI(), statusCode, sleepTime / 1000)); try { Thread.sleep(sleepTime); return executeRequest(request, --maxAttempts, timeout, sleepTime * SLEEP_SCALE_FACTOR); } catch (InterruptedException e) { logger.error("Error during sleep time before new notification request try: {}", e.getMessage()); return false; } } else { logger.warn(format("Request failed on target %s, status code: %d, no more attempt.", request.getURI(), statusCode)); return false; } }
From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java
private static String getErrorMessage(HttpUriRequest request, CloseableHttpResponse response) { String controllerHost = null; String controllerVersion = null; if (response.containsHeader(CommonConstants.Controller.HOST_HTTP_HEADER)) { controllerHost = response.getFirstHeader(CommonConstants.Controller.HOST_HTTP_HEADER).getValue(); controllerVersion = response.getFirstHeader(CommonConstants.Controller.VERSION_HTTP_HEADER).getValue(); }/* ww w. j a v a2s. c o m*/ StatusLine statusLine = response.getStatusLine(); String reason; try { reason = new JSONObject(EntityUtils.toString(response.getEntity())).getString("error"); } catch (Exception e) { reason = "Failed to get reason"; } String errorMessage = String.format( "Got error status code: %d (%s) with reason: \"%s\" while sending request: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase(), reason, request.getURI()); if (controllerHost != null) { errorMessage = String.format("%s to controller: %s, version: %s", errorMessage, controllerHost, controllerVersion); } return errorMessage; }
From source file:com.vmware.photon.controller.client.RestClientTest.java
@Test public void testPerformPut() { String payload = "{name: DUMMY}"; ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.PUT, new StringEntity(payload, ContentType.APPLICATION_JSON)); HttpUriRequest request = argumentCaptor.getValue(); assertNotNull(request);//from ww w . ja v a 2 s . c om assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.PUT.toString())); assertEquals(request.getURI().toString(), uri); HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) request; String actualPayload = null; try { actualPayload = IOUtils.toString(httpEntityEnclosingRequest.getEntity().getContent()); } catch (IOException e) { fail(e.getMessage()); } assertEquals(actualPayload, payload); }
From source file:com.yahoo.validatar.execution.rest.JSON.java
/** * Makes the request and returns the String response using the given client, request and query. * * @param client The HttpClient to use./*from w w w.j av a 2 s . c om*/ * @param request The HttpUriRequest to make. * @param query The Query object being run. * @return The String response of the call, null if exception (query is failed). */ String makeRequest(HttpClient client, HttpUriRequest request, Query query) { try { log.info("{}ing to {} with headers {}", request.getMethod(), request.getURI(), request.getAllHeaders()); HttpResponse response = client.execute(request); StatusLine line = response.getStatusLine(); log.info("Received {}: {} with headers {}", line.getStatusCode(), line.getReasonPhrase(), response.getAllHeaders()); String data = EntityUtils.toString(response.getEntity()); log.info("Received response as string {}", data); return data; } catch (IOException ioe) { log.error("Could not execute request", ioe); query.setFailure("Could not execute request"); query.addMessage(ioe.toString()); } catch (NullPointerException npe) { log.error("Received no response", npe); query.setFailure("Received no response"); query.addMessage(npe.toString()); } return null; }
From source file:com.nominanuda.hyperapi.HyperApiHttpInvocationHandler.java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HttpUriRequest req = encode(uriPrefix, hyperApi, method, args); HttpResponse resp = client.execute(req); int status = resp.getStatusLine().getStatusCode(); if (status >= 500) { throw new Http500Exception(resp.getStatusLine().getReasonPhrase() + " for " + req.getURI()); } else if (status >= 400) { throw new Http400Exception(resp.getStatusLine().getReasonPhrase() + " for " + req.getURI()); }//from w ww . j av a 2s .co m Object result = decode(hyperApi, method, resp); return result; }