Example usage for org.apache.http.client.methods HttpPost METHOD_NAME

List of usage examples for org.apache.http.client.methods HttpPost METHOD_NAME

Introduction

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

Prototype

String METHOD_NAME

To view the source code for org.apache.http.client.methods HttpPost METHOD_NAME.

Click Source Link

Usage

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceClient.java

/**
 * Invokes a custom API using POST HTTP method
 *
 * @param apiName The API name/* ww w . jav a 2  s. com*/
 * @param clazz   The API result class
 */
public <E> ListenableFuture<E> invokeApi(String apiName, Class<E> clazz) {
    return invokeApi(apiName, null, HttpPost.METHOD_NAME, null, clazz);
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

public void testClearCache() {
    String[] indices = randomBoolean() ? null : randomIndicesNames(0, 5);
    ClearIndicesCacheRequest clearIndicesCacheRequest;
    if (randomBoolean()) {
        clearIndicesCacheRequest = new ClearIndicesCacheRequest(indices);
    } else {/*from  w w w  . ja  v a  2  s .c om*/
        clearIndicesCacheRequest = new ClearIndicesCacheRequest();
        clearIndicesCacheRequest.indices(indices);
    }
    Map<String, String> expectedParams = new HashMap<>();
    setRandomIndicesOptions(clearIndicesCacheRequest::indicesOptions, clearIndicesCacheRequest::indicesOptions,
            expectedParams);
    if (randomBoolean()) {
        clearIndicesCacheRequest.queryCache(randomBoolean());
    }
    expectedParams.put("query", Boolean.toString(clearIndicesCacheRequest.queryCache()));
    if (randomBoolean()) {
        clearIndicesCacheRequest.fieldDataCache(randomBoolean());
    }
    expectedParams.put("fielddata", Boolean.toString(clearIndicesCacheRequest.fieldDataCache()));
    if (randomBoolean()) {
        clearIndicesCacheRequest.requestCache(randomBoolean());
    }
    expectedParams.put("request", Boolean.toString(clearIndicesCacheRequest.requestCache()));
    if (randomBoolean()) {
        clearIndicesCacheRequest.fields(randomIndicesNames(1, 5));
        expectedParams.put("fields", String.join(",", clearIndicesCacheRequest.fields()));
    }

    Request request = RequestConverters.clearCache(clearIndicesCacheRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "");
    if (indices != null && indices.length > 0) {
        endpoint.add(String.join(",", indices));
    }
    endpoint.add("_cache/clear");
    assertThat(request.getEndpoint(), equalTo(endpoint.toString()));
    assertThat(request.getParameters(), equalTo(expectedParams));
    assertThat(request.getEntity(), nullValue());
    assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME));
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceClient.java

/**
 * Invokes a custom API using POST HTTP method
 *
 * @param apiName The API name//from  w  ww .ja v a  2 s . c  om
 * @param body    The object to send as the request body
 * @param clazz   The API result class
 */
public <E> ListenableFuture<E> invokeApi(String apiName, Object body, Class<E> clazz) {
    return invokeApi(apiName, body, HttpPost.METHOD_NAME, null, clazz);
}

From source file:com.codeim.coxin.fanfou.Weibo.java

/**
 *?//from   w  w  w .  j ava  2  s  . c om
 */
public User updateAvatar(File imageFile) throws HttpException {
    return new User(http.httpRequestImage(getBaseURL() + "account/upload_profile_image.php",
            createParams(new BasicNameValuePair("source", source)), imageFile, false, HttpPost.METHOD_NAME));
}

From source file:org.elasticsearch.client.RequestConverters.java

static Request verifyRepository(VerifyRepositoryRequest verifyRepositoryRequest) {
    String endpoint = new EndpointBuilder().addPathPartAsIs("_snapshot")
            .addPathPart(verifyRepositoryRequest.name()).addPathPartAsIs("_verify").build();
    Request request = new Request(HttpPost.METHOD_NAME, endpoint);

    Params parameters = new Params(request);
    parameters.withMasterTimeout(verifyRepositoryRequest.masterNodeTimeout());
    parameters.withTimeout(verifyRepositoryRequest.timeout());
    return request;
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

public void testUpdate() throws IOException {
    XContentType xContentType = randomFrom(XContentType.values());

    Map<String, String> expectedParams = new HashMap<>();
    String index = randomAlphaOfLengthBetween(3, 10);
    String type = randomAlphaOfLengthBetween(3, 10);
    String id = randomAlphaOfLengthBetween(3, 10);

    UpdateRequest updateRequest = new UpdateRequest(index, type, id);
    updateRequest.detectNoop(randomBoolean());

    if (randomBoolean()) {
        BytesReference source = RandomObjects.randomSource(random(), xContentType);
        updateRequest.doc(new IndexRequest().source(source, xContentType));

        boolean docAsUpsert = randomBoolean();
        updateRequest.docAsUpsert(docAsUpsert);
        if (docAsUpsert) {
            expectedParams.put("doc_as_upsert", "true");
        }//www  .ja va2  s  . c om
    } else {
        updateRequest.script(mockScript("_value + 1"));
        updateRequest.scriptedUpsert(randomBoolean());
    }
    if (randomBoolean()) {
        BytesReference source = RandomObjects.randomSource(random(), xContentType);
        updateRequest.upsert(new IndexRequest().source(source, xContentType));
    }
    if (randomBoolean()) {
        String routing = randomAlphaOfLengthBetween(3, 10);
        updateRequest.routing(routing);
        expectedParams.put("routing", routing);
    }
    if (randomBoolean()) {
        String timeout = randomTimeValue();
        updateRequest.timeout(timeout);
        expectedParams.put("timeout", timeout);
    } else {
        expectedParams.put("timeout", ReplicationRequest.DEFAULT_TIMEOUT.getStringRep());
    }
    if (randomBoolean()) {
        WriteRequest.RefreshPolicy refreshPolicy = randomFrom(WriteRequest.RefreshPolicy.values());
        updateRequest.setRefreshPolicy(refreshPolicy);
        if (refreshPolicy != WriteRequest.RefreshPolicy.NONE) {
            expectedParams.put("refresh", refreshPolicy.getValue());
        }
    }
    setRandomWaitForActiveShards(updateRequest::waitForActiveShards, expectedParams);
    setRandomVersion(updateRequest, expectedParams);
    setRandomVersionType(updateRequest::versionType, expectedParams);
    if (randomBoolean()) {
        int retryOnConflict = randomIntBetween(0, 5);
        updateRequest.retryOnConflict(retryOnConflict);
        if (retryOnConflict > 0) {
            expectedParams.put("retry_on_conflict", String.valueOf(retryOnConflict));
        }
    }
    if (randomBoolean()) {
        randomizeFetchSourceContextParams(updateRequest::fetchSource, expectedParams);
    }

    Request request = RequestConverters.update(updateRequest);
    assertEquals("/" + index + "/" + type + "/" + id + "/_update", request.getEndpoint());
    assertEquals(expectedParams, request.getParameters());
    assertEquals(HttpPost.METHOD_NAME, request.getMethod());

    HttpEntity entity = request.getEntity();
    assertTrue(entity instanceof ByteArrayEntity);

    UpdateRequest parsedUpdateRequest = new UpdateRequest();

    XContentType entityContentType = XContentType.fromMediaTypeOrFormat(entity.getContentType().getValue());
    try (XContentParser parser = createParser(entityContentType.xContent(), entity.getContent())) {
        parsedUpdateRequest.fromXContent(parser);
    }

    assertEquals(updateRequest.scriptedUpsert(), parsedUpdateRequest.scriptedUpsert());
    assertEquals(updateRequest.docAsUpsert(), parsedUpdateRequest.docAsUpsert());
    assertEquals(updateRequest.detectNoop(), parsedUpdateRequest.detectNoop());
    assertEquals(updateRequest.fetchSource(), parsedUpdateRequest.fetchSource());
    assertEquals(updateRequest.script(), parsedUpdateRequest.script());
    if (updateRequest.doc() != null) {
        assertToXContentEquivalent(updateRequest.doc().source(), parsedUpdateRequest.doc().source(),
                xContentType);
    } else {
        assertNull(parsedUpdateRequest.doc());
    }
    if (updateRequest.upsertRequest() != null) {
        assertToXContentEquivalent(updateRequest.upsertRequest().source(),
                parsedUpdateRequest.upsertRequest().source(), xContentType);
    } else {
        assertNull(parsedUpdateRequest.upsertRequest());
    }
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceClient.java

/**
 * Invokes a custom API using POST HTTP method
 *
 * @param apiName The API name/* w ww  .  ja v a  2s. co  m*/
 * @param body    The json element to send as the request body
 */
public ListenableFuture<JsonElement> invokeApi(String apiName, JsonElement body) {
    return invokeApi(apiName, body, HttpPost.METHOD_NAME, null);
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

public void testBulk() throws IOException {
    Map<String, String> expectedParams = new HashMap<>();

    BulkRequest bulkRequest = new BulkRequest();
    if (randomBoolean()) {
        String timeout = randomTimeValue();
        bulkRequest.timeout(timeout);/*  w w  w . ja v a 2  s.  c om*/
        expectedParams.put("timeout", timeout);
    } else {
        expectedParams.put("timeout", BulkShardRequest.DEFAULT_TIMEOUT.getStringRep());
    }

    setRandomRefreshPolicy(bulkRequest::setRefreshPolicy, expectedParams);

    XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);

    int nbItems = randomIntBetween(10, 100);
    for (int i = 0; i < nbItems; i++) {
        String index = randomAlphaOfLength(5);
        String type = randomAlphaOfLength(5);
        String id = randomAlphaOfLength(5);

        BytesReference source = RandomObjects.randomSource(random(), xContentType);
        DocWriteRequest.OpType opType = randomFrom(DocWriteRequest.OpType.values());

        DocWriteRequest<?> docWriteRequest;
        if (opType == DocWriteRequest.OpType.INDEX) {
            IndexRequest indexRequest = new IndexRequest(index, type, id).source(source, xContentType);
            docWriteRequest = indexRequest;
            if (randomBoolean()) {
                indexRequest.setPipeline(randomAlphaOfLength(5));
            }
        } else if (opType == DocWriteRequest.OpType.CREATE) {
            IndexRequest createRequest = new IndexRequest(index, type, id).source(source, xContentType)
                    .create(true);
            docWriteRequest = createRequest;
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            final UpdateRequest updateRequest = new UpdateRequest(index, type, id)
                    .doc(new IndexRequest().source(source, xContentType));
            docWriteRequest = updateRequest;
            if (randomBoolean()) {
                updateRequest.retryOnConflict(randomIntBetween(1, 5));
            }
            if (randomBoolean()) {
                randomizeFetchSourceContextParams(updateRequest::fetchSource, new HashMap<>());
            }
        } else if (opType == DocWriteRequest.OpType.DELETE) {
            docWriteRequest = new DeleteRequest(index, type, id);
        } else {
            throw new UnsupportedOperationException("optype [" + opType + "] not supported");
        }

        if (randomBoolean()) {
            docWriteRequest.routing(randomAlphaOfLength(10));
        }
        if (randomBoolean()) {
            docWriteRequest.version(randomNonNegativeLong());
        }
        if (randomBoolean()) {
            docWriteRequest.versionType(randomFrom(VersionType.values()));
        }
        bulkRequest.add(docWriteRequest);
    }

    Request request = RequestConverters.bulk(bulkRequest);
    assertEquals("/_bulk", request.getEndpoint());
    assertEquals(expectedParams, request.getParameters());
    assertEquals(HttpPost.METHOD_NAME, request.getMethod());
    assertEquals(xContentType.mediaTypeWithoutParameters(), request.getEntity().getContentType().getValue());
    byte[] content = new byte[(int) request.getEntity().getContentLength()];
    try (InputStream inputStream = request.getEntity().getContent()) {
        Streams.readFully(inputStream, content);
    }

    BulkRequest parsedBulkRequest = new BulkRequest();
    parsedBulkRequest.add(content, 0, content.length, xContentType);
    assertEquals(bulkRequest.numberOfActions(), parsedBulkRequest.numberOfActions());

    for (int i = 0; i < bulkRequest.numberOfActions(); i++) {
        DocWriteRequest<?> originalRequest = bulkRequest.requests().get(i);
        DocWriteRequest<?> parsedRequest = parsedBulkRequest.requests().get(i);

        assertEquals(originalRequest.opType(), parsedRequest.opType());
        assertEquals(originalRequest.index(), parsedRequest.index());
        assertEquals(originalRequest.type(), parsedRequest.type());
        assertEquals(originalRequest.id(), parsedRequest.id());
        assertEquals(originalRequest.routing(), parsedRequest.routing());
        assertEquals(originalRequest.version(), parsedRequest.version());
        assertEquals(originalRequest.versionType(), parsedRequest.versionType());

        DocWriteRequest.OpType opType = originalRequest.opType();
        if (opType == DocWriteRequest.OpType.INDEX) {
            IndexRequest indexRequest = (IndexRequest) originalRequest;
            IndexRequest parsedIndexRequest = (IndexRequest) parsedRequest;

            assertEquals(indexRequest.getPipeline(), parsedIndexRequest.getPipeline());
            assertToXContentEquivalent(indexRequest.source(), parsedIndexRequest.source(), xContentType);
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            UpdateRequest updateRequest = (UpdateRequest) originalRequest;
            UpdateRequest parsedUpdateRequest = (UpdateRequest) parsedRequest;

            assertEquals(updateRequest.retryOnConflict(), parsedUpdateRequest.retryOnConflict());
            assertEquals(updateRequest.fetchSource(), parsedUpdateRequest.fetchSource());
            if (updateRequest.doc() != null) {
                assertToXContentEquivalent(updateRequest.doc().source(), parsedUpdateRequest.doc().source(),
                        xContentType);
            } else {
                assertNull(parsedUpdateRequest.doc());
            }
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests.CustomApiTests.java

@SuppressWarnings("deprecation")
private TestCase invokeTypedApiOverload4WithCallbackTest(final Random rndGen) {

    String name = String.format("Typed With Callback - Overload 4");

    TestCase test = new TestCase(name) {
        TestExecutionCallback mCallback;

        TestResult mResult;//  w w  w .  j a  v a 2 s  .co  m

        @Override
        protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) {
            mResult = new TestResult();
            mResult.setTestCase(this);
            mResult.setStatus(TestStatus.Passed);
            mCallback = callback;

            final StringIdMovie ramdomMovie = QueryTestData.getRandomStringIdMovie(rndGen);

            String apiName = MOVIEFINDER_API_NAME;
            String apiUrl;

            apiUrl = apiName + "/moviesWithSameDuration";

            List<Pair<String, String>> parameters = new ArrayList<Pair<String, String>>();

            try {
                client.invokeApi(apiUrl, ramdomMovie, HttpPost.METHOD_NAME, parameters, AllStringIdMovies.class,
                        typedTestCallback());
            } catch (Exception exception) {
                createResultFromException(mResult, exception);
            }
        }

        private ApiOperationCallback<AllStringIdMovies> typedTestCallback() {
            return new ApiOperationCallback<AllStringIdMovies>() {

                @Override
                public void onCompleted(AllStringIdMovies result, Exception exception,
                        ServiceFilterResponse response) {

                    if (exception != null) {
                        createResultFromException(mResult, exception);
                    }

                    mCallback.onTestComplete(mResult.getTestCase(), mResult);
                }
            };
        }
    };

    return test;
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests.CustomApiTests.java

@SuppressWarnings("deprecation")
private TestCase invokeTypedApiOverload4WithCallbackFailTest(final Random rndGen) {

    String name = String.format("Typed With Callback - Overload 4 - Fail");

    TestCase test = new TestCase(name) {
        TestExecutionCallback mCallback;

        TestResult mResult;/*from w ww.ja  va  2 s  . c  o m*/

        @Override
        protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) {
            mResult = new TestResult();
            mResult.setTestCase(this);
            mResult.setStatus(TestStatus.Passed);
            mCallback = callback;

            final StringIdMovie ramdomMovie = QueryTestData.getRandomStringIdMovie(rndGen);

            String apiName = MOVIEFINDER_API_NAME + "wronguri";
            String apiUrl;

            apiUrl = apiName + "/moviesWithSameDuration";

            List<Pair<String, String>> parameters = new ArrayList<Pair<String, String>>();

            try {
                client.invokeApi(apiUrl, ramdomMovie, HttpPost.METHOD_NAME, parameters, AllStringIdMovies.class,
                        typedTestCallback());
            } catch (Exception exception) {
                createResultFromException(mResult, exception);
            }
        }

        private ApiOperationCallback<AllStringIdMovies> typedTestCallback() {
            return new ApiOperationCallback<AllStringIdMovies>() {

                @Override
                public void onCompleted(AllStringIdMovies result, Exception exception,
                        ServiceFilterResponse response) {

                    if (exception == null) {
                        mResult.setStatus(TestStatus.Failed);
                    }
                    mCallback.onTestComplete(mResult.getTestCase(), mResult);
                }
            };
        }
    };

    return test;
}