List of usage examples for org.apache.http.client.methods HttpPut METHOD_NAME
String METHOD_NAME
To view the source code for org.apache.http.client.methods HttpPut METHOD_NAME.
Click Source Link
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.j ava 2 s . co m*/ 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); }/*w w w.j a v a 2 s . 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.zumoe2etestapp.tests.CustomApiTests.java
private TestCase createJsonApiTest(final ApiPermissions permission, final boolean isAuthenticated, final Random rndGen, int testNumber) { String name = String.format("Json Overload - %s - authenticated=%s - Instance=%s", permission.toString(), isAuthenticated, testNumber + 1); TestCase test = new TestCase(name) { MobileServiceClient mClient;//w w w .j a va 2 s . c o m List<Pair<String, String>> mQuery; boolean mExpected401; TestResult mResult; @Override protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) { mResult = new TestResult(); mResult.setTestCase(this); mResult.setStatus(TestStatus.Passed); if (permission == ApiPermissions.Public) { client = client.withFilter(new RemoveAuthenticationServiceFilter()); } mExpected401 = permission == ApiPermissions.Admin || (permission == ApiPermissions.User && !isAuthenticated); mClient = client; String method = createHttpMethod(rndGen); log("Method = " + method); JsonElement body = null; if (!method.equals(HttpGet.METHOD_NAME) && !method.equals(HttpDelete.METHOD_NAME)) { if (method.equals(PATCH_METHOD_NAME) || method.equals(HttpPut.METHOD_NAME)) { body = createJson(rndGen, 0, false); } else { body = createJson(rndGen, 0, true); } } if (body == null) { log("Body: NULL"); } else { log("Body: " + body.toString()); } mQuery = createQuery(rndGen); JsonElement queryJson = createQueryObject(mQuery); log("Query: " + queryJson.toString()); String api = apiNames.get(permission); log("API: " + api); if (body == null && method.equals(HttpPost.METHOD_NAME) && mQuery == null) { try { JsonElement jsonElement = client.invokeApi(api).get(); JsonObject expectedResult = new JsonObject(); expectedResult.add("user", createUserObject(mClient)); if (mQuery != null && mQuery.size() > 0) { expectedResult.add("query", createQueryObject(mQuery)); } if (!Util.compareJson(expectedResult, jsonElement)) { createResultFromException(mResult, new ExpectedValueException(expectedResult, jsonElement)); } } catch (Exception exception) { MobileServiceException cause = (MobileServiceException) exception.getCause(); ServiceFilterResponse response = cause.getResponse(); if (mExpected401) { if (response == null || response.getStatus().getStatusCode() != 401) { mResult.setStatus(TestStatus.Failed); mResult.setException(exception); mResult.getTestCase().log("Expected 401"); } } else { if (exception != null) { createResultFromException(mResult, exception); } } } } else if (body != null && method.equals(HttpPost.METHOD_NAME) && mQuery == null) { try { JsonElement jsonElement = client.invokeApi(api, body).get(); JsonObject expectedResult = new JsonObject(); expectedResult.add("user", createUserObject(mClient)); if (mQuery != null && mQuery.size() > 0) { expectedResult.add("query", createQueryObject(mQuery)); } if (!Util.compareJson(expectedResult, jsonElement)) { createResultFromException(mResult, new ExpectedValueException(expectedResult, jsonElement)); } } catch (Exception exception) { if (mExpected401) { MobileServiceException cause = (MobileServiceException) exception.getCause(); ServiceFilterResponse response = cause.getResponse(); if (response == null || response.getStatus().getStatusCode() != 401) { mResult.setStatus(TestStatus.Failed); mResult.setException(exception); mResult.getTestCase().log("Expected 401"); } } else { if (exception != null) { createResultFromException(mResult, exception); } } } } else if (body == null) { try { JsonElement jsonElement = client.invokeApi(api, method, mQuery).get(); JsonObject expectedResult = new JsonObject(); expectedResult.add("user", createUserObject(mClient)); if (mQuery != null && mQuery.size() > 0) { expectedResult.add("query", createQueryObject(mQuery)); } if (!Util.compareJson(expectedResult, jsonElement)) { createResultFromException(mResult, new ExpectedValueException(expectedResult, jsonElement)); } } catch (Exception exception) { if (mExpected401) { MobileServiceException cause = (MobileServiceException) exception.getCause(); ServiceFilterResponse response = cause.getResponse(); if (response == null || response.getStatus().getStatusCode() != 401) { mResult.setStatus(TestStatus.Failed); mResult.setException(exception); mResult.getTestCase().log("Expected 401"); } } else { if (exception != null) { createResultFromException(mResult, (Exception) exception.getCause()); } } } } else { try { JsonElement jsonElement = client.invokeApi(api, body, method, mQuery).get(); JsonObject expectedResult = new JsonObject(); expectedResult.add("user", createUserObject(mClient)); if (mQuery != null && mQuery.size() > 0) { expectedResult.add("query", createQueryObject(mQuery)); } if (!Util.compareJson(expectedResult, jsonElement)) { createResultFromException(mResult, new ExpectedValueException(expectedResult, jsonElement)); } } catch (Exception exception) { if (mExpected401) { MobileServiceException cause = (MobileServiceException) exception.getCause(); ServiceFilterResponse response = cause.getResponse(); if (response == null || response.getStatus().getStatusCode() != 401) { mResult.setStatus(TestStatus.Failed); mResult.setException(exception); mResult.getTestCase().log("Expected 401"); } } else { if (exception != null) { createResultFromException(mResult, (Exception) exception.getCause()); } } } } if (callback != null) callback.onTestComplete(this, mResult); } }; return test; }
From source file:org.deviceconnect.android.manager.setting.ReqResDebugActivity.java
/** * Http?.//from www . jav a 2 s .c om * @param method HTTP * @param uri ?URI * @param listener Http???? */ private void executeHttpRequest(final String method, final URI uri, final HttpListener listener) { HttpUriRequest req = null; if (HttpGet.METHOD_NAME.equals(method)) { req = new HttpGet(uri.toString()); } else if (HttpPost.METHOD_NAME.equals(method)) { req = new HttpPost(uri.toString()); } else if (HttpPut.METHOD_NAME.equals(method)) { req = new HttpPut(uri.toString()); } else if (HttpDelete.METHOD_NAME.equals(method)) { req = new HttpDelete(uri.toString()); } else if ("?".equals(method)) { AssetManager manager = getAssets(); try { // TODO ?????? String name = "test.png"; MultipartEntity entity = new MultipartEntity(); InputStream in = manager.open(name); // ?? ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; byte[] buf = new byte[4096]; while ((len = in.read(buf)) > 0) { baos.write(buf, 0, len); } // ? entity.addPart(FileProfileConstants.PARAM_DATA, new BinaryBody(baos.toByteArray(), name)); req = new HttpPost(uri.toString()); ((HttpPost) req).setEntity(entity); } catch (UnsupportedEncodingException e) { return; } catch (IOException e) { return; } } else { return; } if (req != null) { executeHttpRequest(req, listener); } }
From source file:org.elasticsearch.client.RequestConverters.java
private static Request resize(ResizeRequest resizeRequest) throws IOException { String endpoint = new EndpointBuilder().addPathPart(resizeRequest.getSourceIndex()) .addPathPartAsIs("_" + resizeRequest.getResizeType().name().toLowerCase(Locale.ROOT)) .addPathPart(resizeRequest.getTargetIndexRequest().index()).build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); Params params = new Params(request); params.withTimeout(resizeRequest.timeout()); params.withMasterTimeout(resizeRequest.masterNodeTimeout()); params.withWaitForActiveShards(resizeRequest.getTargetIndexRequest().waitForActiveShards()); request.setEntity(createEntity(resizeRequest, REQUEST_BODY_CONTENT_TYPE)); return request; }
From source file:org.elasticsearch.client.RequestConverters.java
static Request clusterPutSettings(ClusterUpdateSettingsRequest clusterUpdateSettingsRequest) throws IOException { Request request = new Request(HttpPut.METHOD_NAME, "/_cluster/settings"); Params parameters = new Params(request); parameters.withTimeout(clusterUpdateSettingsRequest.timeout()); parameters.withMasterTimeout(clusterUpdateSettingsRequest.masterNodeTimeout()); request.setEntity(createEntity(clusterUpdateSettingsRequest, REQUEST_BODY_CONTENT_TYPE)); return request; }
From source file:org.elasticsearch.client.RequestConverters.java
static Request putPipeline(PutPipelineRequest putPipelineRequest) throws IOException { String endpoint = new EndpointBuilder().addPathPartAsIs("_ingest/pipeline") .addPathPart(putPipelineRequest.getId()).build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); Params parameters = new Params(request); parameters.withTimeout(putPipelineRequest.timeout()); parameters.withMasterTimeout(putPipelineRequest.masterNodeTimeout()); request.setEntity(createEntity(putPipelineRequest, REQUEST_BODY_CONTENT_TYPE)); return request; }
From source file:org.elasticsearch.client.IndicesClientIT.java
public void testExistsAlias() throws IOException { GetAliasesRequest getAliasesRequest = new GetAliasesRequest("alias"); assertFalse(execute(getAliasesRequest, highLevelClient().indices()::existsAlias, highLevelClient().indices()::existsAliasAsync)); createIndex("index", Settings.EMPTY); client().performRequest(HttpPut.METHOD_NAME, "/index/_alias/alias"); assertTrue(execute(getAliasesRequest, highLevelClient().indices()::existsAlias, highLevelClient().indices()::existsAliasAsync)); GetAliasesRequest getAliasesRequest2 = new GetAliasesRequest(); getAliasesRequest2.aliases("alias"); getAliasesRequest2.indices("index"); assertTrue(execute(getAliasesRequest2, highLevelClient().indices()::existsAlias, highLevelClient().indices()::existsAliasAsync)); getAliasesRequest2.indices("does_not_exist"); assertFalse(execute(getAliasesRequest2, highLevelClient().indices()::existsAlias, highLevelClient().indices()::existsAliasAsync)); }
From source file:org.elasticsearch.client.RequestConverters.java
static Request indexPutSettings(UpdateSettingsRequest updateSettingsRequest) throws IOException { String[] indices = updateSettingsRequest.indices() == null ? Strings.EMPTY_ARRAY : updateSettingsRequest.indices(); Request request = new Request(HttpPut.METHOD_NAME, endpoint(indices, "_settings")); Params parameters = new Params(request); parameters.withTimeout(updateSettingsRequest.timeout()); parameters.withMasterTimeout(updateSettingsRequest.masterNodeTimeout()); parameters.withIndicesOptions(updateSettingsRequest.indicesOptions()); parameters.withPreserveExisting(updateSettingsRequest.isPreserveExisting()); request.setEntity(createEntity(updateSettingsRequest, REQUEST_BODY_CONTENT_TYPE)); return request; }
From source file:org.elasticsearch.client.RequestConverters.java
static Request createRepository(PutRepositoryRequest putRepositoryRequest) throws IOException { String endpoint = new EndpointBuilder().addPathPart("_snapshot").addPathPart(putRepositoryRequest.name()) .build();// w w w . ja v a2 s . c om Request request = new Request(HttpPut.METHOD_NAME, endpoint); Params parameters = new Params(request); parameters.withMasterTimeout(putRepositoryRequest.masterNodeTimeout()); parameters.withTimeout(putRepositoryRequest.timeout()); parameters.withVerify(putRepositoryRequest.verify()); request.setEntity(createEntity(putRepositoryRequest, REQUEST_BODY_CONTENT_TYPE)); return request; }