Example usage for org.apache.http.client.methods HttpUriRequest getMethod

List of usage examples for org.apache.http.client.methods HttpUriRequest getMethod

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest getMethod.

Prototype

String getMethod();

Source Link

Document

Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other.

Usage

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 w ww.  j  a  v a 2  s . com
    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.vmware.photon.controller.client.RestClientTest.java

@Test
public void testPerformPost() {
    String payload = "{name: DUMMY}";
    ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.POST,
            new StringEntity(payload, ContentType.APPLICATION_JSON));

    HttpUriRequest request = argumentCaptor.getValue();
    assertNotNull(request);/*from   w w w.j av a  2  s.  c o  m*/
    assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.POST.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: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//  w  ww.j av  a 2 s  . 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:com.vdisk.net.session.RetryHandler.java

public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    boolean retry = true;

    Log.d("Test", "retry count->" + executionCount);

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b.booleanValue());

    if (executionCount > maxRetries) {
        // Do not retry if over max retry count
        retry = false;/*from  w ww .ja  v a 2s.c o  m*/
    } else if (exceptionBlacklist.contains(exception.getClass())) {
        // immediately cancel retry if the error is blacklisted
        retry = false;
    } else if (exceptionWhitelist.contains(exception.getClass())) {
        // immediately retry if error is whitelisted
        retry = true;
    } else if (!sent) {
        // for most other errors, retry only if request hasn't been fully sent yet
        retry = true;
    }

    if (retry) {
        // resend all idempotent requests
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        Log.d("Test", "HttpUriRequest:" + currentReq);
        if (currentReq != null) {
            String requestType = currentReq.getMethod();
            retry = !requestType.equals("POST") && !requestType.equals("PUT");
        }

    }

    if (retry) {
        SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
    } else {
        exception.printStackTrace();
    }

    return retry;
}

From source file:com.betfair.cougar.client.HttpClientCougarRequestFactoryTest.java

@Test
public void shouldCreateGetRequest() {
    HttpUriRequest httpExchange = factory.create(uri, "GET", mockMessage, mockMarshaller, contentType,
            mockCallContext, mockTimeConstraints);

    assertTrue(httpExchange instanceof HttpGet);
    assertEquals("GET", httpExchange.getMethod());
    assertEquals(uri, httpExchange.getURI().toString());
    assertEquals(5, httpExchange.getAllHeaders().length);
}

From source file:com.cloudmine.api.rest.VolleyAsynchronousHttpClient.java

@Override
public <T> void executeCommand(HttpUriRequest command, final Callback<T> callback,
        final ResponseConstructor<T> constructor) {
    try {//from www .  ja  v a 2s.c  o  m
        String url = command.getURI().toString();
        int method = getMethod(command.getMethod());
        final Map<String, String> headers = getHeadersAsMap(command);
        final byte[] body = getBody(command, callback);
        queue.add(new Request<T>(method, url, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                NetworkResponse response = volleyError.networkResponse;
                if (response != null)
                    callback.onCompletion(
                            constructor.construct(new String(response.data), response.statusCode));
                else
                    callback.onFailure(volleyError, "Volley failed");
            }
        }) {
            @Override
            protected Response parseNetworkResponse(NetworkResponse networkResponse) {
                String messageBody = new String(networkResponse.data);
                int responseCode = networkResponse.statusCode;
                T responseBody = constructor.construct(messageBody, responseCode);
                return Response.success(responseBody, getCacheEntry());
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return headers;
            }

            public byte[] getBody() {
                return body;
            }

            @Override
            protected void deliverResponse(T response) {
                callback.onCompletion(response);
            }

            @Override
            public String getBodyContentType() {
                return "application/json; charset=" + getParamsEncoding();
            }
        });
    } catch (Throwable t) {
        callback.onFailure(t, "Failed creating request");
    }
}

From source file:net.netheos.pcsapi.oauth.OAuth2SessionManager.java

@Override
public CResponse execute(HttpUriRequest request) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("{}: {}", request.getMethod(), PcsUtils.shortenUrl(request.getURI()));
    }//w  w  w. j  a va  2s  .c  om

    if (userCredentials.getCredentials().hasExpired()) {
        refreshToken();
    }

    try {
        request.removeHeaders(HEADER_AUTHORIZATION); // in case we are retrying
        request.addHeader(HEADER_AUTHORIZATION, "Bearer " + userCredentials.getCredentials().getAccessToken());

        HttpResponse httpResponse = httpClient.execute(request);
        return new CResponse(request, httpResponse);

    } catch (IOException ex) {
        // a low level error should be retried :
        throw new CRetriableException(ex);
    }
}

From source file:com.betfair.cougar.client.HttpClientCougarRequestFactoryTest.java

@Test
public void shouldCreatePostRequest() throws Exception {
    HttpUriRequest httpExchange = factory.create(uri, "POST", mockMessage, mockMarshaller, contentType,
            mockCallContext, mockTimeConstraints);

    assertTrue(httpExchange instanceof HttpPost);
    assertEquals("POST", httpExchange.getMethod());
    assertEquals(uri, httpExchange.getURI().toString());
    assertEquals(5, httpExchange.getAllHeaders().length);
    assertEquals(contentType + "; charset=utf-8",
            ((HttpPost) httpExchange).getEntity().getContentType().getValue());
    assertEquals("some post data", IOUtils.toString(((HttpPost) httpExchange).getEntity().getContent()));
}

From source file:com.ab.http.RetryHandler.java

/**
 * ??TODO//from www  .  j a  v a 2  s . c  o  m
 * @see org.apache.http.client.HttpRequestRetryHandler#retryRequest(java.io.IOException, int, org.apache.http.protocol.HttpContext)
 * @author: zhaoqp
 * @date2013-10-22 ?4:23:15
 * @version v1.0
 */
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    boolean retry = true;

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b);

    if (executionCount > maxRetries) {
        // Do not retry if over max retry count
        retry = false;
    } else if (isInList(exceptionBlacklist, exception)) {
        // immediately cancel retry if the error is blacklisted
        retry = false;
    } else if (isInList(exceptionWhitelist, exception)) {
        // immediately retry if error is whitelisted
        retry = true;
    } else if (!sent) {
        // for most other errors, retry only if request hasn't been fully sent yet
        retry = true;
    }

    if (retry) {
        // resend all idempotent requests
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        if (currentReq == null) {
            return false;
        }
        String requestType = currentReq.getMethod();
        retry = !requestType.equals("POST");
    }

    if (retry) {
        SystemClock.sleep(retrySleepTimeMS);
    } else {
        exception.printStackTrace();
    }

    return retry;
}

From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaDispatchTest.java

@Test
public void testConnectivityFailure() throws Exception {
    String serviceName = "RESOURCEMANAGER";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(/*from  ww  w  .  j a v  a 2 s  . c  o m*/
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://unreachable-host");
    URI uri2 = new URI("http://reachable-host");
    ArrayList<String> urlList = new ArrayList<>();
    urlList.add(uri1.toString());
    urlList.add(uri2.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();

    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();
    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    RMHaDispatch dispatch = new RMHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}