List of usage examples for org.apache.http.client.methods HttpPost METHOD_NAME
String METHOD_NAME
To view the source code for org.apache.http.client.methods HttpPost METHOD_NAME.
Click Source Link
From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceClientTests.java
public void testOperationShouldNotReplaceWithDefaultHeaders() throws Throwable { // Create client MobileServiceClient client = null;/*from ww w .j a va2s.c o m*/ try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { e.printStackTrace(); } final String acceptHeaderKey = "Accept"; final String acceptEncodingHeaderKey = "Accept-Encoding"; final String acceptHeaderValue = "text/plain"; final String acceptEncodingHeaderValue = "deflate"; List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>(); headers.add(new Pair<String, String>(acceptHeaderKey, acceptHeaderValue)); headers.add(new Pair<String, String>(acceptEncodingHeaderKey, acceptEncodingHeaderValue)); // Add a new filter to the client client = client.withFilter(new ServiceFilter() { @Override public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) { int acceptHeaderIndex = -1; int acceptEncodingHeaderIndex = -1; int acceptHeaderCount = 0; int acceptEncodingHeaderCount = 0; final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create(); Header[] headers = request.getHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName() == acceptHeaderKey) { acceptHeaderIndex = i; acceptHeaderCount++; } else if (headers[i].getName() == acceptEncodingHeaderKey) { acceptEncodingHeaderIndex = i; acceptEncodingHeaderCount++; } } if (acceptHeaderIndex == -1) { resultFuture.setException(new Exception("acceptHeaderIndex == -1")); return resultFuture; } if (acceptHeaderCount == -1) { resultFuture.setException(new Exception("acceptHeaderCount == -1")); return resultFuture; } if (acceptEncodingHeaderIndex == -1) { resultFuture.setException(new Exception("acceptEncodingHeaderIndex == -1")); return resultFuture; } if (acceptEncodingHeaderCount == -1) { resultFuture.setException(new Exception("acceptEncodingHeaderIndex == -1")); return resultFuture; } if (acceptHeaderValue.equals(headers[acceptHeaderIndex].getValue())) { resultFuture.setException(new Exception("acceptHeaderValue != headers[acceptHeaderIndex]")); return resultFuture; } if (acceptEncodingHeaderValue.equals(headers[acceptEncodingHeaderIndex].getValue())) { resultFuture.setException( new Exception("acceptEncodingHeaderValue != headers[acceptEncodingHeaderIndex]")); return resultFuture; } ServiceFilterResponseMock response = new ServiceFilterResponseMock(); response.setContent("{}"); resultFuture.set(response); return resultFuture; } }); try { client.invokeApi("myApi", null, HttpPost.METHOD_NAME, headers).get(); } catch (Exception exception) { if (exception instanceof ExecutionException) { fail(exception.getCause().getMessage()); } else { fail(exception.getMessage()); } } }
From source file:org.elasticsearch.client.RequestConverters.java
static Request multiSearch(MultiSearchRequest multiSearchRequest) throws IOException { Request request = new Request(HttpPost.METHOD_NAME, "/_msearch"); Params params = new Params(request); params.putParam(RestSearchAction.TYPED_KEYS_PARAM, "true"); if (multiSearchRequest .maxConcurrentSearchRequests() != MultiSearchRequest.MAX_CONCURRENT_SEARCH_REQUESTS_DEFAULT) { params.putParam("max_concurrent_searches", Integer.toString(multiSearchRequest.maxConcurrentSearchRequests())); }//w w w . j a v a 2s. c o m XContent xContent = REQUEST_BODY_CONTENT_TYPE.xContent(); byte[] source = MultiSearchRequest.writeMultiLineFormat(multiSearchRequest, xContent); request.setEntity(new ByteArrayEntity(source, createContentType(xContent.type()))); return request; }
From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests.CustomApiTests.java
private TestCase createTypedApiTest(final Random rndGen, final TypedTestType testType) { String name = String.format("Typed Overload - %s", testType); TestCase test = new TestCase(name) { MobileServiceClient mClient;//from w w w. j a va 2 s . c o m List<Pair<String, String>> mQuery; TestExecutionCallback mCallback; Movie[] mExpectedResult = null; TestResult mResult; @Override protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) { mResult = new TestResult(); mResult.setTestCase(this); mResult.setStatus(TestStatus.Passed); mClient = client; mCallback = callback; final StringIdMovie ramdomMovie = QueryTestData.getRandomStringIdMovie(rndGen); log("Using movie: " + ramdomMovie.getTitle()); String apiName = MOVIEFINDER_API_NAME; String apiUrl; switch (testType) { case GetByTitle: apiUrl = apiName + "/title/" + ramdomMovie.getTitle(); log("API: " + apiUrl); mExpectedResult = new StringIdMovie[] { ramdomMovie }; try { AllStringIdMovies result = mClient .invokeApi(apiUrl, HttpGet.METHOD_NAME, null, AllStringIdMovies.class).get(); if (!Util.compareArrays(mExpectedResult, result.getMovies())) { createResultFromException(mResult, new ExpectedValueException( Util.arrayToString(mExpectedResult), Util.arrayToString(result.getMovies()))); } } catch (Exception exception) { createResultFromException(mResult, exception); } finally { mCallback.onTestComplete(mResult.getTestCase(), mResult); } break; case GetByDate: final Date releaseDate = ramdomMovie.getReleaseDate(); TimeZone tz = TimeZone.getTimeZone("UTC"); Calendar c = Calendar.getInstance(tz); c.setTime(releaseDate); apiUrl = apiName + "/date/" + c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH) + 1) + "/" + c.get(Calendar.DATE); log("API: " + apiUrl); SimpleMovieFilter dateFilter = new SimpleMovieFilter() { @Override protected boolean criteria(Movie movie) { return movie.getReleaseDate().equals(releaseDate); } }; mExpectedResult = dateFilter.filter(QueryTestData.getAllStringIdMovies()).elements .toArray(new Movie[0]); try { AllStringIdMovies result = mClient .invokeApi(apiUrl, HttpGet.METHOD_NAME, null, AllStringIdMovies.class).get(); if (!Util.compareArrays(mExpectedResult, result.getMovies())) { createResultFromException(mResult, new ExpectedValueException( Util.arrayToString(mExpectedResult), Util.arrayToString(result.getMovies()))); } } catch (Exception exception) { createResultFromException(mResult, exception); } finally { mCallback.onTestComplete(mResult.getTestCase(), mResult); } break; case PostByDuration: case PostByYear: String orderBy = null; switch (rndGen.nextInt(3)) { case 0: orderBy = null; break; case 1: orderBy = "title"; break; case 2: orderBy = "title"; //duration break; } mQuery = null; if (orderBy != null) { mQuery = new ArrayList<Pair<String, String>>(); mQuery.add(new Pair<String, String>("orderBy", orderBy)); log("OrderBy: " + orderBy); } if (testType == TypedTestType.PostByYear) { apiUrl = apiName + "/moviesOnSameYear"; } else { apiUrl = apiName + "/moviesWithSameDuration"; } log("API: " + apiUrl); final String orderByCopy = orderBy; SimpleMovieFilter movieFilter = new SimpleMovieFilter() { @Override protected boolean criteria(Movie movie) { if (testType == TypedTestType.PostByYear) { return movie.getYear() == ramdomMovie.getYear(); } else { return movie.getDuration() == ramdomMovie.getDuration(); } } @Override protected List<Movie> applyOrder(List<? extends Movie> movies) { if (orderByCopy == null || orderByCopy.equals("title")) { Collections.sort(movies, new MovieComparator("getTitle")); } else if (orderByCopy.equals("duration")) { Collections.sort(movies, new MovieComparator("getDuration")); } return new ArrayList<Movie>(movies); } }; mExpectedResult = movieFilter.filter(QueryTestData.getAllStringIdMovies()).elements .toArray(new Movie[0]); if (mQuery == null) { try { AllStringIdMovies result = mClient.invokeApi(apiUrl, ramdomMovie, HttpPost.METHOD_NAME, null, AllStringIdMovies.class).get(); if (!Util.compareArrays(mExpectedResult, result.getMovies())) { createResultFromException(mResult, new ExpectedValueException(Util.arrayToString(mExpectedResult), Util.arrayToString(result.getMovies()))); } } catch (Exception exception) { createResultFromException(mResult, exception); } finally { mCallback.onTestComplete(mResult.getTestCase(), mResult); } } else { try { AllStringIdMovies result = mClient.invokeApi(apiUrl, ramdomMovie, HttpPost.METHOD_NAME, mQuery, AllStringIdMovies.class).get(); if (!Util.compareArrays(mExpectedResult, result.getMovies())) { createResultFromException(mResult, new ExpectedValueException(Util.arrayToString(mExpectedResult), Util.arrayToString(result.getMovies()))); } } catch (Exception exception) { createResultFromException(mResult, exception); } finally { mCallback.onTestComplete(mResult.getTestCase(), mResult); } } break; } } }; return test; }
From source file:org.elasticsearch.client.RequestConvertersTests.java
public void testOpenIndex() { String[] indices = randomIndicesNames(1, 5); OpenIndexRequest openIndexRequest = new OpenIndexRequest(indices); openIndexRequest.indices(indices);/*from w w w . ja v a2 s .c om*/ Map<String, String> expectedParams = new HashMap<>(); setRandomTimeout(openIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams); setRandomMasterTimeout(openIndexRequest, expectedParams); setRandomIndicesOptions(openIndexRequest::indicesOptions, openIndexRequest::indicesOptions, expectedParams); setRandomWaitForActiveShards(openIndexRequest::waitForActiveShards, expectedParams); Request request = RequestConverters.openIndex(openIndexRequest); StringJoiner endpoint = new StringJoiner("/", "/", "").add(String.join(",", indices)).add("_open"); assertThat(endpoint.toString(), equalTo(request.getEndpoint())); assertThat(expectedParams, equalTo(request.getParameters())); assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME)); assertThat(request.getEntity(), nullValue()); }
From source file:org.xmetdb.rest.protocol.CallableProtocolUpload.java
protected RemoteTask remoteImport(DBAttachment attachment) throws Exception { Reference uri = new Reference(queryService); HttpClient client = createHTTPClient(uri.getHostDomain(), uri.getHostPort()); RemoteTask task = new RemoteTask(client, new URL(String.format("%s/dataset", queryService)), "text/uri-list", createPOSTEntity(attachment), HttpPost.METHOD_NAME); try {/* w ww . ja v a 2 s .c o m*/ task = wait(task, System.currentTimeMillis()); String dataset_uri = "dataset_uri"; URL dataset = task.getResult(); if (task.isCompletedOK()) { if (!"text/uri-list".equals(attachment.getFormat())) { //was a file //now post the dataset uri to get the /R datasets (query table) attachment.setFormat("text/uri-list"); attachment.setDescription(dataset.toExternalForm()); task = new RemoteTask(client, new URL(String.format("%s/dataset", queryService)), "text/uri-list", createPOSTEntity(attachment), HttpPost.METHOD_NAME); task = wait(task, System.currentTimeMillis()); //indexing Form form = new Form(); form.add(dataset_uri, dataset.toURI().toString()); for (String algorithm : algorithms) { //just launch tasks and don't wait List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair(dataset_uri, dataset.toURI().toString())); HttpEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); HttpClient newclient = createHTTPClient(uri.getHostDomain(), uri.getHostPort()); try { new RemoteTask(newclient, new URL(String.format("%s%s", queryService, algorithm)), "text/uri-list", entity, HttpPost.METHOD_NAME); } catch (Exception x) { x.printStackTrace(); } finally { try { newclient.getConnectionManager().shutdown(); } catch (Exception x) { } } } } else { if (attachment.getStructure() != null && attachment.getStructure().getProperty(Property.getNameInstance()) != null) try { updateName(attachment.getDescription(), attachment.getStructure().getProperty(Property.getNameInstance())); } catch (Exception x) { x.printStackTrace(); } } } } catch (Exception x) { task.setError(new ResourceException(Status.SERVER_ERROR_BAD_GATEWAY, String.format("Error importing chemical structures dataset to %s", uri), x)); } finally { try { client.getConnectionManager().shutdown(); } catch (Exception x) { } } return task; }
From source file:org.elasticsearch.client.RestClient.java
private static HttpRequestBase createHttpRequest(String method, URI uri, HttpEntity entity) { switch (method.toUpperCase(Locale.ROOT)) { case HttpDeleteWithEntity.METHOD_NAME: return addRequestBody(new HttpDeleteWithEntity(uri), entity); case HttpGetWithEntity.METHOD_NAME: return addRequestBody(new HttpGetWithEntity(uri), entity); case HttpHead.METHOD_NAME: return addRequestBody(new HttpHead(uri), entity); case HttpOptions.METHOD_NAME: return addRequestBody(new HttpOptions(uri), entity); case HttpPatch.METHOD_NAME: return addRequestBody(new HttpPatch(uri), entity); case HttpPost.METHOD_NAME: HttpPost httpPost = new HttpPost(uri); addRequestBody(httpPost, entity); return httpPost; case HttpPut.METHOD_NAME: return addRequestBody(new HttpPut(uri), entity); case HttpTrace.METHOD_NAME: return addRequestBody(new HttpTrace(uri), entity); default:/*w w w .j a va 2 s .c o m*/ throw new UnsupportedOperationException("http method not supported: " + method); } }
From source file:org.elasticsearch.client.RequestConvertersTests.java
public void testCloseIndex() { String[] indices = randomIndicesNames(1, 5); CloseIndexRequest closeIndexRequest = new CloseIndexRequest(indices); Map<String, String> expectedParams = new HashMap<>(); setRandomTimeout(closeIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams); setRandomMasterTimeout(closeIndexRequest, expectedParams); setRandomIndicesOptions(closeIndexRequest::indicesOptions, closeIndexRequest::indicesOptions, expectedParams);// www . java 2 s.c o m Request request = RequestConverters.closeIndex(closeIndexRequest); StringJoiner endpoint = new StringJoiner("/", "/", "").add(String.join(",", indices)).add("_close"); assertThat(endpoint.toString(), equalTo(request.getEndpoint())); assertThat(expectedParams, equalTo(request.getParameters())); assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME)); assertThat(request.getEntity(), nullValue()); }
From source file:org.elasticsearch.client.RequestConvertersTests.java
public void testIndex() throws IOException { String index = randomAlphaOfLengthBetween(3, 10); String type = randomAlphaOfLengthBetween(3, 10); IndexRequest indexRequest = new IndexRequest(index, type); String id = randomBoolean() ? randomAlphaOfLengthBetween(3, 10) : null; indexRequest.id(id);//w w w . ja va2 s . c om Map<String, String> expectedParams = new HashMap<>(); String method = HttpPost.METHOD_NAME; if (id != null) { method = HttpPut.METHOD_NAME; if (randomBoolean()) { indexRequest.opType(DocWriteRequest.OpType.CREATE); } } setRandomTimeout(indexRequest::timeout, ReplicationRequest.DEFAULT_TIMEOUT, expectedParams); setRandomRefreshPolicy(indexRequest::setRefreshPolicy, expectedParams); // There is some logic around _create endpoint and version/version type if (indexRequest.opType() == DocWriteRequest.OpType.CREATE) { indexRequest.version(randomFrom(Versions.MATCH_ANY, Versions.MATCH_DELETED)); expectedParams.put("version", Long.toString(Versions.MATCH_DELETED)); } else { setRandomVersion(indexRequest, expectedParams); setRandomVersionType(indexRequest::versionType, expectedParams); } if (frequently()) { if (randomBoolean()) { String routing = randomAlphaOfLengthBetween(3, 10); indexRequest.routing(routing); expectedParams.put("routing", routing); } if (randomBoolean()) { String pipeline = randomAlphaOfLengthBetween(3, 10); indexRequest.setPipeline(pipeline); expectedParams.put("pipeline", pipeline); } } XContentType xContentType = randomFrom(XContentType.values()); int nbFields = randomIntBetween(0, 10); try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) { builder.startObject(); for (int i = 0; i < nbFields; i++) { builder.field("field_" + i, i); } builder.endObject(); indexRequest.source(builder); } Request request = RequestConverters.index(indexRequest); if (indexRequest.opType() == DocWriteRequest.OpType.CREATE) { assertEquals("/" + index + "/" + type + "/" + id + "/_create", request.getEndpoint()); } else if (id != null) { assertEquals("/" + index + "/" + type + "/" + id, request.getEndpoint()); } else { assertEquals("/" + index + "/" + type, request.getEndpoint()); } assertEquals(expectedParams, request.getParameters()); assertEquals(method, request.getMethod()); HttpEntity entity = request.getEntity(); assertTrue(entity instanceof ByteArrayEntity); assertEquals(indexRequest.getContentType().mediaTypeWithoutParameters(), entity.getContentType().getValue()); try (XContentParser parser = createParser(xContentType.xContent(), entity.getContent())) { assertEquals(nbFields, parser.map().size()); } }
From source file:org.elasticsearch.client.SearchIT.java
public void testSearchScroll() throws Exception { for (int i = 0; i < 100; i++) { XContentBuilder builder = jsonBuilder().startObject().field("field", i).endObject(); HttpEntity entity = new NStringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON); client().performRequest(HttpPut.METHOD_NAME, "test/type1/" + Integer.toString(i), Collections.emptyMap(), entity); }//from ww w . ja va 2s . c o m client().performRequest(HttpPost.METHOD_NAME, "/test/_refresh"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(35).sort("field", SortOrder.ASC); SearchRequest searchRequest = new SearchRequest("test").scroll(TimeValue.timeValueMinutes(2)) .source(searchSourceBuilder); SearchResponse searchResponse = execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync); try { long counter = 0; assertSearchHeader(searchResponse); assertThat(searchResponse.getHits().getTotalHits(), equalTo(100L)); assertThat(searchResponse.getHits().getHits().length, equalTo(35)); for (SearchHit hit : searchResponse.getHits()) { assertThat(((Number) hit.getSortValues()[0]).longValue(), equalTo(counter++)); } searchResponse = execute( new SearchScrollRequest(searchResponse.getScrollId()).scroll(TimeValue.timeValueMinutes(2)), highLevelClient()::searchScroll, highLevelClient()::searchScrollAsync); assertThat(searchResponse.getHits().getTotalHits(), equalTo(100L)); assertThat(searchResponse.getHits().getHits().length, equalTo(35)); for (SearchHit hit : searchResponse.getHits()) { assertEquals(counter++, ((Number) hit.getSortValues()[0]).longValue()); } searchResponse = execute( new SearchScrollRequest(searchResponse.getScrollId()).scroll(TimeValue.timeValueMinutes(2)), highLevelClient()::searchScroll, highLevelClient()::searchScrollAsync); assertThat(searchResponse.getHits().getTotalHits(), equalTo(100L)); assertThat(searchResponse.getHits().getHits().length, equalTo(30)); for (SearchHit hit : searchResponse.getHits()) { assertEquals(counter++, ((Number) hit.getSortValues()[0]).longValue()); } } finally { ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); clearScrollRequest.addScrollId(searchResponse.getScrollId()); ClearScrollResponse clearScrollResponse = execute(clearScrollRequest, // Not using a method reference to work around https://bugs.eclipse.org/bugs/show_bug.cgi?id=517951 (request, headers) -> highLevelClient().clearScroll(request, headers), (request, listener, headers) -> highLevelClient().clearScrollAsync(request, listener, headers)); assertThat(clearScrollResponse.getNumFreed(), greaterThan(0)); assertTrue(clearScrollResponse.isSucceeded()); SearchScrollRequest scrollRequest = new SearchScrollRequest(searchResponse.getScrollId()) .scroll(TimeValue.timeValueMinutes(2)); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(scrollRequest, highLevelClient()::searchScroll, highLevelClient()::searchScrollAsync)); assertEquals(RestStatus.NOT_FOUND, exception.status()); assertThat(exception.getRootCause(), instanceOf(ElasticsearchException.class)); ElasticsearchException rootCause = (ElasticsearchException) exception.getRootCause(); assertThat(rootCause.getMessage(), containsString("No search context found for")); } }
From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceClientTests.java
public void testOperationDefaultHeadersShouldBeIdempotent() throws Throwable { // Create client MobileServiceClient client = null;/*from ww w .java2 s . c o m*/ try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { e.printStackTrace(); } final String acceptHeaderKey = "Accept"; final String acceptEncodingHeaderKey = "Accept-Encoding"; final String acceptHeaderValue = "application/json"; final String acceptEncodingHeaderValue = "gzip"; List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>(); headers.add(new Pair<String, String>(acceptHeaderKey, acceptHeaderValue)); headers.add(new Pair<String, String>(acceptEncodingHeaderKey, acceptEncodingHeaderValue)); // Add a new filter to the client client = client.withFilter(new ServiceFilter() { @Override public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) { int acceptHeaderIndex = -1; int acceptEncodingHeaderIndex = -1; int acceptHeaderCount = 0; int acceptEncodingHeaderCount = 0; final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create(); Header[] headers = request.getHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName() == acceptHeaderKey) { acceptHeaderIndex = i; acceptHeaderCount++; } else if (headers[i].getName() == acceptEncodingHeaderKey) { acceptEncodingHeaderIndex = i; acceptEncodingHeaderCount++; } } if (acceptHeaderIndex == -1) { resultFuture.setException(new Exception("acceptHeaderIndex == -1")); return resultFuture; } if (acceptHeaderCount == -1) { resultFuture.setException(new Exception("acceptHeaderCount == -1")); return resultFuture; } if (acceptEncodingHeaderIndex == -1) { resultFuture.setException(new Exception("acceptEncodingHeaderIndex == -1")); return resultFuture; } if (acceptEncodingHeaderCount == -1) { resultFuture.setException(new Exception("acceptEncodingHeaderIndex == -1")); return resultFuture; } ServiceFilterResponseMock response = new ServiceFilterResponseMock(); response.setContent("{}"); resultFuture.set(response); return resultFuture; } }); try { client.invokeApi("myApi", null, HttpPost.METHOD_NAME, headers).get(); } catch (Exception exception) { if (exception instanceof ExecutionException) { fail(exception.getCause().getMessage()); } else { fail(exception.getMessage()); } } }