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:org.dasein.cloud.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java

@Test
public void addServersShouldPostCorrectRequest() throws CloudException, InternalException {
    final String ROLE_NAME_2 = "TESTROLENAME2";
    final String VM_ID_2 = String.format("%s:%s:%s", SERVICE_NAME, DEPLOYMENT_NAME, ROLE_NAME_2);

    final AtomicInteger postCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock//ww  w .  ja va 2  s .c o m
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if ("GET".equals(request.getMethod()) && DEFINITION_URL.equals(request.getURI().toString())) {
                assertGet(request, DEFINITION_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                        createDefinitionModel("Failover", "Enabled", HC_PORT));
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if ("POST".equals(request.getMethod())
                    && DEFINITIONS_URL.equals(request.getURI().toString())) {
                postCount.incrementAndGet();
                assertPost(request, DEFINITIONS_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        createDefinitionModelWithAnotherServer("Failover", "Enabled", ROLE_NAME_2));

                DefinitionModel definitionModel = new DefinitionModel();
                definitionModel.setVersion("2");
                DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                        definitionModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    loadBalancerSupport.addServers(LB_NAME, ROLE_NAME_2);
    assertEquals("LoadBalancerSupport.addServers() ", 1, postCount.get());
}

From source file:org.dasein.cloud.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java

@Test
public void removeServersShouldPostCorrectRequest() throws CloudException, InternalException {
    final String ROLE_NAME_2 = "TESTROLENAME2";
    final String VM_ID_2 = String.format("%s:%s:%s", SERVICE_NAME, DEPLOYMENT_NAME, ROLE_NAME_2);

    final AtomicInteger postCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock//w  w  w.  j a v  a 2  s  . c  om
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if ("GET".equals(request.getMethod()) && DEFINITION_URL.equals(request.getURI().toString())) {
                assertGet(request, DEFINITION_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                DefinitionModel definitionModel = createDefinitionModelWithAnotherServer("Failover", "Enabled",
                        ROLE_NAME_2);

                DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                        createDefinitionModel("Failover", "Enabled", HC_PORT));
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if ("POST".equals(request.getMethod())
                    && DEFINITIONS_URL.equals(request.getURI().toString())) {
                postCount.incrementAndGet();
                assertPost(request, DEFINITIONS_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        createDefinitionModel("Failover", "Enabled", HC_PORT));

                DefinitionModel definitionModel = new DefinitionModel();
                definitionModel.setVersion("2");
                DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                        definitionModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    loadBalancerSupport.removeServers(LB_NAME, ROLE_NAME_2);
    assertEquals("LoadBalancerSupport.addServers() post count doesn't match", 1, postCount.get());
}

From source file:org.dasein.cloud.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java

@Test
public void modifyHealthCheckShouldPostCorrectRequest() throws CloudException, InternalException {
    final int portChangeTo = 8080;
    final AtomicInteger getCount = new AtomicInteger(0);
    final AtomicInteger postCount = new AtomicInteger(0);

    new MockUp<CloseableHttpClient>() {
        @Mock//from www.ja v a2s  . c  o m
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if ("GET".equals(request.getMethod()) && DEFINITION_URL.equals(request.getURI().toString())) {
                getCount.incrementAndGet();
                assertGet(request, DEFINITION_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });

                if (getCount.get() == 1) {
                    DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                            createDefinitionModel("Failover", "Enabled", HC_PORT));
                    return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                            new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
                } else {
                    DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                            createDefinitionModel("Failover", "Enabled", portChangeTo));
                    return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                            new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
                }
            } else if ("POST".equals(request.getMethod())
                    && DEFINITIONS_URL.equals(request.getURI().toString())) {
                postCount.incrementAndGet();
                assertPost(request, DEFINITIONS_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        createDefinitionModel("Failover", "Enabled", portChangeTo));

                DefinitionModel definitionModel = new DefinitionModel();
                definitionModel.setVersion("2");
                DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                        definitionModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };

    LoadBalancerHealthCheck loadBalancerHealthCheck = loadBalancerSupport.modifyHealthCheck(LB_NAME,
            HealthCheckOptions.getInstance(LB_NAME, HC_DESCRIPTION, LB_NAME, null, HC_PROTOCOL, 8080, HC_PATH,
                    9, 9, 9, 9));
    assertEquals("LoadBalancerSupport.modifyHealthCheck() post count doesn't match", 1, postCount.get());
    assertLoadBalancerHealthCheck(loadBalancerHealthCheck, portChangeTo);
}

From source file:com.joyent.manta.http.StandardHttpHelper.java

/**
 * Attempts to construct a {@link InputStreamContinuator} for the initial request-response exchange. If the request
 * cannot be resumed (either because the exchange is malformed or the request does not support resuming) we will
 * return null, otherwise the continuator receives our client, the initial request (which it will clone) and the
 * marker we created.//from   w w  w. ja v  a  2s  .  c o  m
 *
 * @see HttpDownloadContinuationMarker#validateInitialExchange
 *
 * @param request the initial request, etag and range headers will be used as hints for the first argument to
 * {@link HttpDownloadContinuationMarker#validateInitialExchange(Pair, int, Pair)}
 * @param response the initial response which will be validated against any hints
 * @return the continuator which can be used to resume this request
 */
private InputStreamContinuator constructContinuatorForCompatibleRequest(final HttpUriRequest request,
        final CloseableHttpResponse response) {
    if (this.maxDownloadContinuations == DOWNLOAD_CONTINUATIONS_DISABLED
            || !HttpGet.METHOD_NAME.equalsIgnoreCase(request.getMethod())
            || !(this.connectionContext instanceof MantaApacheHttpClientContext)
            || !(request instanceof HttpGet)) {
        return null;
    }

    final HttpGet get = (HttpGet) request;
    final HttpDownloadContinuationMarker marker;
    try {
        // if we can't build a marker the request:
        // - uses a combination of headers we don't support (e.g. multi-part range)
        // - the request/response pair exhibits unexpected behavior we are not prepared to follow
        marker = validateInitialExchange(extractDownloadRequestFingerprint(get),
                response.getStatusLine().getStatusCode(), extractDownloadResponseFingerprint(response, true));
    } catch (final ProtocolException pe) {
        LOGGER.debug("HTTP download cannot be automatically continued: {}", pe.getMessage());
        return null;
    }

    try {
        return new ApacheHttpGetResponseEntityContentContinuator(
                (MantaApacheHttpClientContext) this.connectionContext, get, marker,
                this.maxDownloadContinuations);
    } catch (final HttpDownloadContinuationException rde) {
        LOGGER.debug(String.format("Expected to build a continuator but an exception occurred: %s",
                rde.getMessage()));
    }

    return null;
}

From source file:geotag.core.HttpHelper.java

private void checkForRequestError(HttpUriRequest request) throws Exception {
    HttpResponse serverResponse = client.execute(request);
    HttpEntity entity = serverResponse.getEntity();

    if (entity != null) {
        entity.consumeContent();//  w w  w  . ja v  a 2s. c o m
    }

    Header headers[] = serverResponse.getAllHeaders();
    String ignoreCase = Properties.getUrlIndex().substring(0, Properties.getUrlIndex().length() - 1);

    for (Header h : headers) {
        if (h.getName().equalsIgnoreCase("Location")) {
            if (h.getValue().equalsIgnoreCase(ignoreCase)
                    || h.getValue().equalsIgnoreCase(Properties.getUrl() + "/index.html#section_wo")) {
                return;
            }
        }
    }

    throw new Exception(
            "HttpHelper -> checkForRequestError: " + request.getMethod().toString() + " request failed");
}

From source file:es.auth.plugin.JestHttpClient.java

public Tuple<JestResult, HttpResponse> executeE(final Action clientRequest) throws IOException {
    final String elasticSearchRestUrl = getRequestURL(getElasticSearchServer(), clientRequest.getURI());
    final HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(), elasticSearchRestUrl,
            clientRequest.getData(gson));
    log.debug("reqeust method and restUrl - " + clientRequest.getRestMethodName() + " " + elasticSearchRestUrl);
    // add headers added to action
    if (!clientRequest.getHeaders().isEmpty()) {
        for (final Iterator<Entry> it = clientRequest.getHeaders().entrySet().iterator(); it.hasNext();) {
            final Entry header = it.next();
            request.addHeader((String) header.getKey(), header.getValue().toString());
        }//from   ww w  .j  a va  2s.  co  m
    }
    final HttpResponse response = httpClient.execute(request);
    // If head method returns no content, it is added according to response code thanks to https://github.com/hlassiege
    if (request.getMethod().equalsIgnoreCase("HEAD")) {
        if (response.getEntity() == null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                response.setEntity(new StringEntity("{\"ok\" : true, \"found\" : true}"));
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                response.setEntity(new StringEntity("{\"ok\" : false, \"found\" : false}"));
            }
        }
    }
    return new Tuple(deserializeResponse(response, clientRequest), response);
}

From source file:com.floragunn.searchguard.HeaderAwareJestHttpClient.java

@Override
public <T extends JestResult> T execute(final Action<T> clientRequest) throws IOException {

    final String elasticSearchRestUrl = getRequestURL(getElasticSearchServer(), clientRequest.getURI());

    final HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(), elasticSearchRestUrl,
            clientRequest.getData(gson));

    log.debug("reqeust method and restUrl - " + clientRequest.getRestMethodName() + " " + elasticSearchRestUrl);

    // add headers added to action
    if (!clientRequest.getHeaders().isEmpty()) {
        for (final Entry<String, Object> header : clientRequest.getHeaders().entrySet()) {
            request.addHeader(header.getKey(), header.getValue().toString());
        }//from  w ww .  jav a 2  s .c o  m
    }

    final HttpResponse response = httpClient.execute(request);

    // If head method returns no content, it is added according to response code thanks to https://github.com/hlassiege
    if (request.getMethod().equalsIgnoreCase("HEAD")) {
        if (response.getEntity() == null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                response.setEntity(new StringEntity("{\"ok\" : true, \"found\" : true}"));
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                response.setEntity(new StringEntity("{\"ok\" : false, \"found\" : false}"));
            }
        }
    }
    return deserializeResponse(response, clientRequest);
}

From source file:com.petalmd.armor.HeaderAwareJestHttpClient.java

@Override
public <T extends JestResult> T execute(final Action<T> clientRequest) throws IOException {

    final String elasticSearchRestUrl = getRequestURL(getNextServer(), clientRequest.getURI());

    final HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(), elasticSearchRestUrl,
            clientRequest.getData(gson));

    log.debug("reqeust method and restUrl - " + clientRequest.getRestMethodName() + " " + elasticSearchRestUrl);

    // add headers added to action
    if (!clientRequest.getHeaders().isEmpty()) {
        for (final Entry<String, Object> header : clientRequest.getHeaders().entrySet()) {
            request.addHeader(header.getKey(), header.getValue().toString());
        }//from  w w w .j av  a  2s  . c  om
    }

    final HttpResponse response = httpClient.execute(request);

    // If head method returns no content, it is added according to response code thanks to https://github.com/hlassiege
    if (request.getMethod().equalsIgnoreCase("HEAD")) {
        if (response.getEntity() == null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                response.setEntity(new StringEntity("{\"ok\" : true, \"found\" : true}"));
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                response.setEntity(new StringEntity("{\"ok\" : false, \"found\" : false}"));
            }
        }
    }
    return deserializeResponse(response, clientRequest);
}

From source file:org.apache.sling.testing.clients.AbstractSlingClient.java

/**
 * <p>Executes an HTTP request, WITHOUT consuming the entity in the response. The caller is responsible for consuming the entity or
 * closing the response's InputStream in order to release the connection.
 * Otherwise, the client might run out of connections and will block</p>
 *
 * <p><b>Use this with caution and only if necessary for streaming</b>, otherwise use the safe method
 * {@link #doRequest(HttpUriRequest, List, int...)}</p>
 *
 * <p>Adds the headers and checks the response against expected status</p>
 *
 * @param request the request to be executed
 * @param headers optional headers to be added to the request
 * @param expectedStatus if passed, the response status is checked against it/them, and has to match at least one of them
 * @return the response, with the entity not consumed
 * @throws ClientException if the request could not be executed
 *///  ww w  .j  a  v  a 2  s .  com
public SlingHttpResponse doStreamRequest(HttpUriRequest request, List<Header> headers, int... expectedStatus)
        throws ClientException {
    // create context from config
    HttpClientContext context = createHttpClientContextFromConfig();

    // add headers
    if (headers != null) {
        request.setHeaders(headers.toArray(new Header[headers.size()]));
    }

    try {
        log.debug("request {} {}", request.getMethod(), request.getURI());
        SlingHttpResponse response = new SlingHttpResponse(this.execute(request, context));
        log.debug("response {}", HttpUtils.getHttpStatus(response));
        // Check the status and throw a ClientException if it doesn't match expectedStatus, but close the entity before
        if (expectedStatus != null && expectedStatus.length > 0) {
            try {
                HttpUtils.verifyHttpStatus(response, expectedStatus);
            } catch (ClientException e) {
                // catch the exception to make sure we close the entity before re-throwing it
                response.close();
                throw e;
            }
        }

        return response;
    } catch (IOException e) {
        throw new ClientException("Could not execute http request", e);
    }
}