List of usage examples for org.apache.http.client.methods HttpUriRequest getMethod
String getMethod();
From source file:org.elasticsearch.client.RequestLoggerTests.java
public void testResponseWarnings() throws Exception { HttpHost host = new HttpHost("localhost", 9200); HttpUriRequest request = randomHttpRequest(new URI("/index/type/_api")); int numWarnings = randomIntBetween(1, 5); StringBuilder expected = new StringBuilder("request [").append(request.getMethod()).append(" ").append(host) .append("/index/type/_api] returned ").append(numWarnings).append(" warnings: "); Header[] warnings = new Header[numWarnings]; for (int i = 0; i < numWarnings; i++) { String warning = "this is warning number " + i; warnings[i] = new BasicHeader("Warning", warning); if (i > 0) { expected.append(","); }//from w w w.j av a 2 s . c om expected.append("[").append(warning).append("]"); } assertEquals(expected.toString(), RequestLogger.buildWarningMessage(request, host, warnings)); }
From source file:io.soabase.client.apache.WrappedHttpClient.java
@Override public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException { addRequestId(request);//from w w w . j av a 2 s . c o m RetryContext retryContext = new RetryContext(retryComponents, request.getURI(), request.getMethod()); for (int retryCount = 0; /* no check */; ++retryCount) { SoaDiscoveryInstance instance = ClientUtils.hostToInstance(discovery, retryContext.getOriginalHost()); retryContext.setInstance(instance); URI filteredUri = ClientUtils.filterUri(request.getURI(), instance); if (filteredUri != null) { request = new WrappedHttpUriRequest(request, filteredUri); } try { HttpResponse response = implementation.execute(request, context); if (!retryContext.shouldBeRetried(retryCount, response.getStatusLine().getStatusCode(), null)) { return response; } } catch (IOException e) { if (!retryContext.shouldBeRetried(retryCount, 0, e)) { throw e; } } } }
From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaDispatchTest.java
@Test public void testConnectivityFailover() throws Exception { String serviceName = "RESOURCEMANAGER"; HaDescriptor descriptor = HaDescriptorFactory.createDescriptor(); descriptor.addServiceConfig(// w ww. ja v a 2s . c om HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null)); HaProvider provider = new DefaultHaProvider(descriptor); URI uri1 = new URI("http://passive-host"); URI uri2 = new URI("http://other-host"); URI uri3 = new URI("http://active-host"); ArrayList<String> urlList = new ArrayList<>(); urlList.add(uri1.toString()); urlList.add(uri2.toString()); urlList.add(uri3.toString()); provider.addHaService(serviceName, urlList); FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class); ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class); EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes(); EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)) .andReturn(provider).anyTimes(); BasicHttpResponse inboundResponse = EasyMock.createNiceMock(BasicHttpResponse.class); EasyMock.expect(inboundResponse.getStatusLine()).andReturn(getStatusLine()).anyTimes(); EasyMock.expect(inboundResponse.getEntity()).andReturn(getResponseEntity()).anyTimes(); EasyMock.expect(inboundResponse.getFirstHeader(LOCATION)).andReturn(getFirstHeader(uri3.toString())) .anyTimes(); BasicHttpParams params = new BasicHttpParams(); HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class); EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes(); EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes(); EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes(); HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class); EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once(); EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0)) .once(); EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1)) .once(); HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() { @Override public ServletOutputStream answer() throws Throwable { return new ServletOutputStream() { @Override public void write(int b) throws IOException { throw new IOException("unreachable-host"); } @Override public void setWriteListener(WriteListener arg0) { } @Override public boolean isReady() { return false; } }; } }).once(); Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName)); EasyMock.replay(filterConfig, servletContext, inboundResponse, outboundRequest, inboundRequest, outboundResponse); RMHaDispatch dispatch = new RMHaDispatch(); dispatch.setHttpClient(new DefaultHttpClient()); dispatch.setHaProvider(provider); dispatch.init(); long startTime = System.currentTimeMillis(); try { dispatch.setInboundResponse(inboundResponse); dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse); } catch (IOException e) { //this is expected after the failover limit is reached } Assert.assertEquals(uri3.toString(), dispatch.getUriFromInbound(inboundRequest, inboundResponse, null).toString()); long elapsedTime = System.currentTimeMillis() - startTime; Assert.assertEquals(uri3.toString(), provider.getActiveURL(serviceName)); //test to make sure the sleep took place Assert.assertTrue(elapsedTime > 1000); }
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 w w. ja v a2s. c o m*/ 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 . jav a 2 s . 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.loadtest.engage.util.TrustedHttpClient.java
/** * {@inheritDoc}// w ww .ja v a 2 s . c o m * @see org.opencastproject.loadtest.engage.util.remotetest.util.security.api.TrustedHttpClient#execute(org.apache.http.client.methods.HttpUriRequest) */ public HttpResponse execute(HttpUriRequest httpUriRequest) { // Add the request header to elicit a digest auth response httpUriRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH); if ("GET".equalsIgnoreCase(httpUriRequest.getMethod()) || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) { // Set the user/pass UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); // Run the request (the http client handles the multiple back-and-forth requests) try { return httpClient.execute(httpUriRequest); } catch (IOException e) { throw new TrustedHttpClientException(e); } } // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart // request), so we need to handle the details of the digest auth back-and-forth manually HttpRequestBase digestRequest; try { digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance(); } catch (Exception e) { throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName()); } digestRequest.setURI(httpUriRequest.getURI()); digestRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH); String[] realmAndNonce = getRealmAndNonce(digestRequest); if (realmAndNonce != null) { // Set the user/pass UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); // Set up the digest authentication with the required values DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", realmAndNonce[0]); digestAuth.overrideParamter("nonce", realmAndNonce[1]); // Add the authentication header try { httpUriRequest.addHeader(digestAuth.authenticate(creds, httpUriRequest)); } catch (Exception e) { // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } } try { return httpClient.execute(httpUriRequest); } catch (Exception e) { // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } }
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./* w w w . ja va 2 s . c o m*/ * @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:retsys.client.http.HttpHelper.java
public String executeHttpRequest(HttpClient client, HttpUriRequest req) throws IOException { String response = null;/*w w w . j a va2 s. c o m*/ HttpResponse httpResponse = client.execute(req); int httpStatus = httpResponse.getStatusLine().getStatusCode(); if (httpStatus >= 200 && httpStatus < 300) { if (!HttpDelete.METHOD_NAME.equals(req.getMethod()) && !HttpPut.METHOD_NAME.equals(req.getMethod())) { response = readFromStream(httpResponse.getEntity().getContent()); } } else if (httpStatus == 409) { response = readFromStream(httpResponse.getEntity().getContent()); System.out.println("response: " + response); response = "!ERROR!"; } else { response = "!ERROR!"; } return response; }
From source file:com.surevine.alfresco.connector.BaseAlfrescoHttpConnector.java
/** * This should be the only place our connectors exercise an {@link HttpUriRequest}. * /*from www . j a va 2 s. c o m*/ * @param request The URI we want to retrieve. * @return A wrapped HttpResponse allowing us to request Strings, JSON Objects, Arrays, etc. * @throws AlfrescoException On error. */ private AlfrescoHttpResponse fetch(final HttpUriRequest request) throws AlfrescoException { try { return new AlfrescoHttpResponse(client.execute(request)); } catch (final ClientProtocolException e) { throw new AlfrescoException("Failed on HTTP " + request.getMethod(), e); } catch (final IOException e) { throw new AlfrescoException("Failed on HTTP " + request.getMethod(), e); } }
From source file:com.comcast.cim.rest.client.xhtml.TestRequestBuilder.java
@Test public void testBuildsAGetRequestIfFormMethodSaysSo() throws Exception { Element form = new Element("form", XhtmlParser.XHTML_NS_URI); form.setAttribute("method", "get"); form.setAttribute("action", "http://foo.example.com/"); buildDocument(form);/*from ww w. j av a 2s . co m*/ URL context = new URL("http://www.example.com/"); HttpUriRequest result = impl.submitForm(form, context, args); Assert.assertEquals("GET", result.getMethod()); }