Java Code Examples for org.apache.http.nio.entity.NStringEntity
The following examples show how to use
org.apache.http.nio.entity.NStringEntity. These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: presto Source File: TestPasswordAuthentication.java License: Apache License 2.0 | 6 votes |
@Test public void test() throws IOException { String json = new ObjectMapper().writeValueAsString(ImmutableMap.<String, Object>builder() .put("value", 42L) .build()); client.getLowLevelClient() .performRequest( "POST", "/test/_doc?refresh", ImmutableMap.of(), new NStringEntity(json, ContentType.APPLICATION_JSON), new BasicHeader("Authorization", format("Basic %s", Base64.encodeAsString(format("%s:%s", USER, PASSWORD).getBytes(StandardCharsets.UTF_8))))); assertThat(assertions.query("SELECT * FROM test")) .matches("VALUES BIGINT '42'"); }
Example 2
Source Project: ProjectStudy Source File: LowLevelRestController.java License: MIT License | 6 votes |
/** * 添加ES对象, Book的ID就是ES中存储的Document的ID,ES的POST和PUT可以看下面这个文章 * https://blog.csdn.net/z457181562/article/details/93470152 * * @param bookDto * @return org.springframework.http.ResponseEntity<java.lang.String> * @throws IOException * @author wliduo[[email protected]] * @date 2019/8/8 17:46 */ @PostMapping("/book") public ResponseBean add(@RequestBody BookDto bookDto) throws IOException { // Endpoint直接指定为Index/Type的形式 /*Request request = new Request("POST", new StringBuilder("/book/book/").toString());*/ // 防重复新增数据 bookDto.setId(System.currentTimeMillis()); Request request = new Request("PUT", new StringBuilder("/book/book/") .append(bookDto.getId()).append("/_create").toString()); // 设置其他一些参数比如美化Json request.addParameter("pretty", "true"); // 设置请求体并指定ContentType,如果不指定会乱码 request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON)); // 发送HTTP请求 Response response = restClient.performRequest(request); // 获取响应体 String responseBody = EntityUtils.toString(response.getEntity()); return new ResponseBean(HttpStatus.OK.value(), "添加成功", JSON.parseObject(responseBody)); }
Example 3
Source Project: ProjectStudy Source File: LowLevelRestController.java License: MIT License | 6 votes |
/** * 根据Id更新Book,ES的POST和PUT可以看下面这个文章 * * https://blog.csdn.net/z457181562/article/details/93470152 * @param bookDto * @return org.springframework.http.ResponseEntity<java.lang.String> * @throws IOException * @author wliduo[[email protected]] * @date 2019/8/9 10:04 */ @PutMapping("/book") public ResponseBean update(@RequestBody BookDto bookDto) throws IOException { // 构造HTTP请求 /*Request request = new Request("POST", new StringBuilder("/book/book/") .append(bookDto.getId()).append("/_update").toString());*/ Request request = new Request("PUT", new StringBuilder("/book/book/") .append(bookDto.getId()).toString()); // 设置其他一些参数比如美化Json request.addParameter("pretty", "true"); /*// 将数据丢进去,这里一定要外包一层'doc',否则内部不能识别 JSONObject jsonObject = new JSONObject(); jsonObject.put("doc", new JSONObject(bookDto));*/ // 设置请求体并指定ContentType,如果不指定会乱码 request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON)); // 执行HTTP请求 Response response = restClient.performRequest(request); // 获取返回的内容 String responseBody = EntityUtils.toString(response.getEntity()); return new ResponseBean(HttpStatus.OK.value(), "更新成功", JSON.parseObject(responseBody)); }
Example 4
Source Project: ProjectStudy Source File: LowLevelRestController.java License: MIT License | 6 votes |
/** * 使用脚本更新Name * * @param id * @param bookDto * @return org.springframework.http.ResponseEntity<java.lang.String> * @throws IOException * @author wliduo[[email protected]] * @date 2019/8/9 11:37 */ @PutMapping("/book/{id}") public ResponseEntity<String> update2(@PathVariable("id") String id, @RequestBody BookDto bookDto) throws IOException { // 构造HTTP请求 Request request = new Request("POST", new StringBuilder("/book/book/") .append(id).append("/_update").toString()); // 设置其他一些参数比如美化Json request.addParameter("pretty", "true"); JSONObject jsonObject = new JSONObject(); // 创建脚本语言,如果是字符变量,必须加单引号 StringBuilder op1 = new StringBuilder("ctx._source.name=").append("'" + bookDto.getName() + "'"); jsonObject.put("script", op1); request.setEntity(new NStringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON)); // 执行HTTP请求 Response response = restClient.performRequest(request); // 获取返回的内容 String responseBody = EntityUtils.toString(response.getEntity()); return new ResponseEntity<>(responseBody, HttpStatus.OK); }
Example 5
Source Project: ProjectStudy Source File: LowLevelRestController.java License: MIT License | 6 votes |
/** * 添加ES对象, Book的ID就是ES中存储的Document的ID,ES的POST和PUT可以看下面这个文章 * https://blog.csdn.net/z457181562/article/details/93470152 * * @param bookDto * @return org.springframework.http.ResponseEntity<java.lang.String> * @throws IOException * @author wliduo[[email protected]] * @date 2019/8/8 17:46 */ @PostMapping("/book") public ResponseBean add(@RequestBody BookDto bookDto) throws IOException { // Endpoint直接指定为Index/Type的形式 /*Request request = new Request("POST", new StringBuilder("/book/book/").toString());*/ // 防重复新增数据 bookDto.setId(System.currentTimeMillis()); Request request = new Request("PUT", new StringBuilder("/book/book/") .append(bookDto.getId()).append("/_create").toString()); // 设置其他一些参数比如美化Json request.addParameter("pretty", "true"); // 设置请求体并指定ContentType,如果不指定会乱码 request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON)); // 发送HTTP请求 Response response = restClient.performRequest(request); // 获取响应体 String responseBody = EntityUtils.toString(response.getEntity()); return new ResponseBean(HttpStatus.OK.value(), "添加成功", JSON.parseObject(responseBody)); }
Example 6
Source Project: ProjectStudy Source File: LowLevelRestController.java License: MIT License | 6 votes |
/** * 根据Id更新Book,ES的POST和PUT可以看下面这个文章 * * https://blog.csdn.net/z457181562/article/details/93470152 * @param bookDto * @return org.springframework.http.ResponseEntity<java.lang.String> * @throws IOException * @author wliduo[[email protected]] * @date 2019/8/9 10:04 */ @PutMapping("/book") public ResponseBean update(@RequestBody BookDto bookDto) throws IOException { // 构造HTTP请求 /*Request request = new Request("POST", new StringBuilder("/book/book/") .append(bookDto.getId()).append("/_update").toString());*/ Request request = new Request("PUT", new StringBuilder("/book/book/") .append(bookDto.getId()).toString()); // 设置其他一些参数比如美化Json request.addParameter("pretty", "true"); /*// 将数据丢进去,这里一定要外包一层'doc',否则内部不能识别 JSONObject jsonObject = new JSONObject(); jsonObject.put("doc", new JSONObject(bookDto));*/ // 设置请求体并指定ContentType,如果不指定会乱码 request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON)); // 执行HTTP请求 Response response = restClient.performRequest(request); // 获取返回的内容 String responseBody = EntityUtils.toString(response.getEntity()); return new ResponseBean(HttpStatus.OK.value(), "更新成功", JSON.parseObject(responseBody)); }
Example 7
Source Project: ProjectStudy Source File: LowLevelRestController.java License: MIT License | 6 votes |
/** * 使用脚本更新Name * * @param id * @param bookDto * @return org.springframework.http.ResponseEntity<java.lang.String> * @throws IOException * @author wliduo[[email protected]] * @date 2019/8/9 11:37 */ @PutMapping("/book/{id}") public ResponseEntity<String> update2(@PathVariable("id") String id, @RequestBody BookDto bookDto) throws IOException { // 构造HTTP请求 Request request = new Request("POST", new StringBuilder("/book/book/") .append(id).append("/_update").toString()); // 设置其他一些参数比如美化Json request.addParameter("pretty", "true"); JSONObject jsonObject = new JSONObject(); // 创建脚本语言,如果是字符变量,必须加单引号 StringBuilder op1 = new StringBuilder("ctx._source.name=").append("'" + bookDto.getName() + "'"); jsonObject.put("script", op1); request.setEntity(new NStringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON)); // 执行HTTP请求 Response response = restClient.performRequest(request); // 获取返回的内容 String responseBody = EntityUtils.toString(response.getEntity()); return new ResponseEntity<>(responseBody, HttpStatus.OK); }
Example 8
Source Project: griffin Source File: MetricStoreImpl.java License: Apache License 2.0 | 6 votes |
private HttpEntity getHttpEntityForSearch(String metricName, int from, int size, long tmst) throws JsonProcessingException { Map<String, Object> map = new HashMap<>(); Map<String, Object> queryParam = new HashMap<>(); Map<String, Object> termQuery = Collections.singletonMap("name.keyword", metricName); queryParam.put("filter", Collections.singletonMap("term", termQuery)); Map<String, Object> sortParam = Collections .singletonMap("tmst", Collections.singletonMap("order", "desc")); map.put("query", Collections.singletonMap("bool", queryParam)); map.put("sort", sortParam); map.put("from", from); map.put("size", size); return new NStringEntity(JsonUtil.toJson(map), ContentType.APPLICATION_JSON); }
Example 9
Source Project: beam Source File: ElasticsearchIO.java License: Apache License 2.0 | 6 votes |
@Override public boolean advance() throws IOException { if (batchIterator.hasNext()) { current = batchIterator.next(); return true; } else { String requestBody = String.format( "{\"scroll\" : \"%s\",\"scroll_id\" : \"%s\"}", source.spec.getScrollKeepalive(), scrollId); HttpEntity scrollEntity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON); Request request = new Request("GET", "/_search/scroll"); request.addParameters(Collections.emptyMap()); request.setEntity(scrollEntity); Response response = restClient.performRequest(request); JsonNode searchResult = parseResponse(response.getEntity()); updateScrollId(searchResult); return readNextBatchAndReturnFirstDocument(searchResult); } }
Example 10
Source Project: beam Source File: ElasticsearchIO.java License: Apache License 2.0 | 6 votes |
@Override public void close() throws IOException { // remove the scroll String requestBody = String.format("{\"scroll_id\" : [\"%s\"]}", scrollId); HttpEntity entity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON); try { Request request = new Request("DELETE", "/_search/scroll"); request.addParameters(Collections.emptyMap()); request.setEntity(entity); restClient.performRequest(request); } finally { if (restClient != null) { restClient.close(); } } }
Example 11
Source Project: skywalking Source File: ElasticSearchClient.java License: Apache License 2.0 | 6 votes |
public boolean createTemplate(String indexName, Map<String, Object> settings, Map<String, Object> mapping) throws IOException { indexName = formatIndexName(indexName); String[] patterns = new String[] {indexName + "-*"}; Map<String, Object> aliases = new HashMap<>(); aliases.put(indexName, new JsonObject()); Map<String, Object> template = new HashMap<>(); template.put("index_patterns", patterns); template.put("aliases", aliases); template.put("settings", settings); template.put("mappings", mapping); HttpEntity entity = new NStringEntity(new Gson().toJson(template), ContentType.APPLICATION_JSON); Response response = client.getLowLevelClient() .performRequest( HttpPut.METHOD_NAME, "/_template/" + indexName, Collections.emptyMap(), entity); return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; }
Example 12
Source Project: metron Source File: ElasticsearchBulkDocumentWriterIntegrationTest.java License: Apache License 2.0 | 6 votes |
@BeforeEach public void setup() throws Exception { client = ElasticsearchClientFactory.create(globals()); retrieveDao = new ElasticsearchRetrieveLatestDao(client); writer = new ElasticsearchBulkDocumentWriter<>(client) .withRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); // add bro template JSONObject broTemplate = JSONUtils.INSTANCE.load(new File(broTemplatePath), JSONObject.class); String broTemplateJson = JSONUtils.INSTANCE.toJSON(broTemplate, true); HttpEntity broEntity = new NStringEntity(broTemplateJson, ContentType.APPLICATION_JSON); Response response = client .getLowLevelClient() .performRequest("PUT", "/_template/bro_template", Collections.emptyMap(), broEntity); assertThat(response.getStatusLine().getStatusCode(), CoreMatchers.equalTo(200)); }
Example 13
Source Project: karaf-decanter Source File: ElasticsearchCollectorTest.java License: Apache License 2.0 | 6 votes |
@Test(timeout = 60000L) public void testAll() throws Exception { HttpHost host = new HttpHost(HOST, HTTP_PORT, "http"); RestClient client = RestClient.builder(new HttpHost[]{ host }).build(); HttpEntity entity = new NStringEntity("{\"foo\":\"bar\"}", ContentType.APPLICATION_JSON); Request request = new Request("POST", "/test/_doc/"); request.setEntity(entity); client.performRequest(request); MockDispatcher dispatcher = new MockDispatcher(); ElasticsearchCollector collector = new ElasticsearchCollector(); collector.setDispatcher(dispatcher); Hashtable<String, Object> configuration = new Hashtable<>(); configuration.put("addresses", "http://localhost:" + HTTP_PORT); configuration.put("index", "test"); collector.activate(configuration); collector.run(); Assert.assertEquals(1, dispatcher.postedEvents.size()); Assert.assertEquals("elasticsearch", dispatcher.postedEvents.get(0).getProperty("type")); Assert.assertEquals("decanter/collect/elasticsearch", dispatcher.postedEvents.get(0).getTopic()); }
Example 14
Source Project: jframe Source File: WeikePath.java License: Apache License 2.0 | 6 votes |
private void bulkIndexMember(List<?> memList) throws Exception { StringBuilder buf = new StringBuilder(1024); for (Object mem : memList) { buf.append("{\"index\": {}}"); buf.append("\n"); buf.append(Gson.toJson(mem)); buf.append("\n"); } long startTime = System.currentTimeMillis(); RestClient client = Plugin.client; HttpEntity entity = new NStringEntity(buf.toString(), ContentType.APPLICATION_JSON); Response indexResponse = client.performRequest("POST", "/weike/member/_bulk", Collections.<String, String>emptyMap(), entity); if (LOG.isDebugEnabled()) { LOG.debug("indexMember {}ms", System.currentTimeMillis() - startTime); LOG.debug("indexResponse {}", indexResponse.toString()); } }
Example 15
Source Project: jframe Source File: WeikePath.java License: Apache License 2.0 | 6 votes |
private void indexMember(String sellerId, Object mem) throws IOException { if (sellerId == null) sellerId = ""; long startTime = System.currentTimeMillis(); RestClient client = Plugin.client; String json = Gson.toJson(mem); HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON); String path = "/weike/member"; if (!"".equals(sellerId)) { path += "?routing=" + sellerId; } Response indexResponse = client.performRequest("POST", path, Collections.<String, String>emptyMap(), entity); if (LOG.isDebugEnabled()) { LOG.debug("indexMember {}ms", System.currentTimeMillis() - startTime); LOG.debug("indexResponse {}", indexResponse.toString()); } }
Example 16
Source Project: jframe Source File: TestQuery.java License: Apache License 2.0 | 6 votes |
@Test @Ignore public void testSearch() throws Exception { // JsonObject json = new JsonObject(); // json.addProperty("from", "0"); // json.addProperty("size", "10"); // json.addProperty("explain", true); // JsonObject query = new JsonObject(); // query.add // json.add("query", query); String json = "{\"explain\":false,\"from\":0,\"size\":1,\"query\":{\"range\":{\"tradeAmount\":{\"gte\":10,\"lte\":2000}}}}"; long startTime = System.currentTimeMillis(); HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON); Response response = client.performRequest("GET", "/weike/member/_search", Collections.singletonMap("pretty", "true"), entity); LOG.info("search-{} {}ms", EntityUtils.toString(response.getEntity()), System.currentTimeMillis() - startTime); }
Example 17
Source Project: nifi Source File: ElasticSearchClientServiceImpl.java License: Apache License 2.0 | 6 votes |
private Response runQuery(String endpoint, String query, String index, String type) { StringBuilder sb = new StringBuilder() .append("/") .append(index); if (type != null && !type.equals("")) { sb.append("/") .append(type); } sb.append(String.format("/%s", endpoint)); HttpEntity queryEntity = new NStringEntity(query, ContentType.APPLICATION_JSON); try { return client.performRequest("POST", sb.toString(), Collections.emptyMap(), queryEntity); } catch (Exception e) { throw new ElasticsearchError(e); } }
Example 18
Source Project: nifi Source File: ElasticSearchClientServiceImpl.java License: Apache License 2.0 | 6 votes |
@Override public DeleteOperationResponse deleteById(String index, String type, List<String> ids) { try { StringBuilder sb = new StringBuilder(); for (int idx = 0; idx < ids.size(); idx++) { String header = buildBulkHeader("delete", index, type, ids.get(idx)); sb.append(header).append("\n"); } HttpEntity entity = new NStringEntity(sb.toString(), ContentType.APPLICATION_JSON); StopWatch watch = new StopWatch(); watch.start(); Response response = client.performRequest("POST", "/_bulk", Collections.emptyMap(), entity); watch.stop(); if (getLogger().isDebugEnabled()) { getLogger().debug(String.format("Response for bulk delete: %s", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8))); } DeleteOperationResponse dor = new DeleteOperationResponse(watch.getDuration(TimeUnit.MILLISECONDS)); return dor; } catch (Exception ex) { throw new RuntimeException(ex); } }
Example 19
Source Project: presto Source File: BaseElasticsearchSmokeTest.java License: Apache License 2.0 | 5 votes |
private void createIndex(String indexName, @Language("JSON") String properties) throws IOException { String mappings = indexMapping(properties); client.getLowLevelClient() .performRequest("PUT", "/" + indexName, ImmutableMap.of(), new NStringEntity(mappings, ContentType.APPLICATION_JSON)); }
Example 20
Source Project: ProjectStudy Source File: LowLevelRestController.java License: MIT License | 5 votes |
/** * 分词分页查询列表 * * @param page * @param rows * @param keyword * @return com.example.common.ResponseBean * @author wliduo[[email protected]] * @date 2019/8/9 15:32 */ @GetMapping("/book") public ResponseBean getBookList(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows, String keyword) { Request request = new Request("POST", new StringBuilder("/_search").toString()); // 添加Json返回优化 request.addParameter("pretty", "true"); // 拼接查询Json IndexRequest indexRequest = new IndexRequest(); XContentBuilder builder = null; Response response = null; String responseBody = null; try { builder = JsonXContent.contentBuilder() .startObject() .startObject("query") .startObject("multi_match") .field("query", keyword) .array("fields", new String[]{"name", "desc"}) .endObject() .endObject() .startObject("sort") .startObject("id") .field("order", "desc") .endObject() .endObject() .endObject(); indexRequest.source(builder); // 设置请求体并指定ContentType,如果不指定会乱码 request.setEntity(new NStringEntity(indexRequest.source().utf8ToString(), ContentType.APPLICATION_JSON)); // 执行HTTP请求 response = restClient.performRequest(request); responseBody = EntityUtils.toString(response.getEntity()); } catch (IOException e) { return new ResponseBean(HttpStatus.NOT_FOUND.value(), "can not found the book by your id", null); } return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody)); }
Example 21
Source Project: ProjectStudy Source File: LowLevelRestController.java License: MIT License | 5 votes |
/** * 分词分页查询列表 * * @param page * @param rows * @param keyword * @return com.example.common.ResponseBean * @author wliduo[[email protected]] * @date 2019/8/9 15:32 */ @GetMapping("/book") public ResponseBean getBookList(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows, String keyword) { Request request = new Request("POST", new StringBuilder("/_search").toString()); // 添加Json返回优化 request.addParameter("pretty", "true"); // 拼接查询Json IndexRequest indexRequest = new IndexRequest(); XContentBuilder builder = null; Response response = null; String responseBody = null; try { builder = JsonXContent.contentBuilder() .startObject() .startObject("query") .startObject("multi_match") .field("query", keyword) .array("fields", new String[]{"name", "desc"}) .endObject() .endObject() .startObject("sort") .startObject("id") .field("order", "desc") .endObject() .endObject() .endObject(); indexRequest.source(builder); // 设置请求体并指定ContentType,如果不指定会乱码 request.setEntity(new NStringEntity(indexRequest.source().utf8ToString(), ContentType.APPLICATION_JSON)); // 执行HTTP请求 response = restClient.performRequest(request); responseBody = EntityUtils.toString(response.getEntity()); } catch (IOException e) { return new ResponseBean(HttpStatus.NOT_FOUND.value(), "can not found the book by your id", null); } return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody)); }
Example 22
Source Project: anomaly-detection Source File: AnomalyDetectorRestApiIT.java License: Apache License 2.0 | 5 votes |
public void testSearchAnomalyDetector() throws Exception { AnomalyDetector detector = createRandomAnomalyDetector(true, true); SearchSourceBuilder search = (new SearchSourceBuilder()).query(QueryBuilders.termQuery("_id", detector.getDetectorId())); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, false); Exception ex = expectThrows( ResponseException.class, () -> TestHelpers .makeRequest( client(), "GET", TestHelpers.AD_BASE_DETECTORS_URI + "/_search", ImmutableMap.of(), new NStringEntity(search.toString(), ContentType.APPLICATION_JSON), null ) ); assertThat(ex.getMessage(), containsString(CommonErrorMessages.DISABLED_ERR_MSG)); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, true); Response searchResponse = TestHelpers .makeRequest( client(), "GET", TestHelpers.AD_BASE_DETECTORS_URI + "/_search", ImmutableMap.of(), new NStringEntity(search.toString(), ContentType.APPLICATION_JSON), null ); assertEquals("Search anomaly detector failed", RestStatus.OK, restStatus(searchResponse)); }
Example 23
Source Project: anomaly-detection Source File: TestHelpers.java License: Apache License 2.0 | 5 votes |
public static Response makeRequest( RestClient client, String method, String endpoint, Map<String, String> params, String jsonEntity, List<Header> headers ) throws IOException { HttpEntity httpEntity = Strings.isBlank(jsonEntity) ? null : new NStringEntity(jsonEntity, ContentType.APPLICATION_JSON); return makeRequest(client, method, endpoint, params, httpEntity, headers); }
Example 24
Source Project: java-specialagent Source File: ElasticsearchITest.java License: Apache License 2.0 | 5 votes |
private static void runRestClient() throws IOException, InterruptedException { try (final RestClient restClient = RestClient.builder(new HttpHost("localhost", HTTP_PORT, "http")).build()) { final HttpEntity entity = new NStringEntity( "{\n" + " \"user\": \"user\",\n" + " \"post_date\": \"2009-11-15T14:12:12\",\n" + " \"message\": \"trying out Elasticsearch\"\n" + "}", ContentType.APPLICATION_JSON); final Request request1 = new Request("PUT", "/twitter/tweet/1"); request1.setEntity(entity); final Response indexResponse = restClient.performRequest(request1); System.out.println(indexResponse); final Request request2 = new Request("PUT", "/twitter/tweet/2"); request2.setEntity(entity); final CountDownLatch latch = new CountDownLatch(1); restClient.performRequestAsync(request2, new ResponseListener() { @Override public void onSuccess(final Response response) { latch.countDown(); } @Override public void onFailure(final Exception e) { latch.countDown(); } }); latch.await(30, TimeUnit.SECONDS); } }
Example 25
Source Project: Groza Source File: ElasticsearchAuditLogSink.java License: Apache License 2.0 | 5 votes |
@Override public void logAction(AuditLog auditLogEntry) { String jsonContent = createElasticJsonRecord(auditLogEntry); HttpEntity entity = new NStringEntity( jsonContent, ContentType.APPLICATION_JSON); restClient.performRequestAsync( HttpMethod.POST.name(), String.format("/%s/%s", getIndexName(auditLogEntry.getTenantId()), INDEX_TYPE), Collections.emptyMap(), entity, responseListener); }
Example 26
Source Project: newblog Source File: HttpHelper.java License: Apache License 2.0 | 5 votes |
public String doPost(String url, String data, String charset) { if (StringUtils.isBlank(url)) { return null; } log.info(" post url=" + url); try { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new NStringEntity(data, charset)); CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, charset); } EntityUtils.consume(entity); response.close(); return result; } catch (Exception e) { log.error("to request addr=" + url + ", " + e.getMessage()); e.printStackTrace(); } return null; }
Example 27
Source Project: griffin Source File: MetricStoreImpl.java License: Apache License 2.0 | 5 votes |
@Override public ResponseEntity<?> addMetricValues(List<MetricValue> metricValues) throws IOException { String bulkRequestBody = getBulkRequestBody(metricValues); HttpEntity entity = new NStringEntity(bulkRequestBody, ContentType.APPLICATION_JSON); Response response = client.performRequest("POST", urlPost, Collections.emptyMap(), entity); return getResponseEntityFromResponse(response); }
Example 28
Source Project: griffin Source File: MetricStoreImpl.java License: Apache License 2.0 | 5 votes |
@Override public ResponseEntity<?> deleteMetricValues(String metricName) throws IOException { Map<String, Object> param = Collections.singletonMap("query", Collections.singletonMap("term", Collections.singletonMap("name.keyword", metricName))); HttpEntity entity = new NStringEntity( JsonUtil.toJson(param), ContentType.APPLICATION_JSON); Response response = client.performRequest("POST", urlDelete, Collections.emptyMap(), entity); return getResponseEntityFromResponse(response); }
Example 29
Source Project: Tenable.io-SDK-for-Java Source File: AsyncHttpService.java License: MIT License | 5 votes |
/** * Makes an HTTP POST request using the given URI and optional body. * * @param uri the URI to use for the POST call * @param json Optional, can be null. the JSON to POST * @return the resulting HttpFuture instance */ public HttpFuture doPost( URI uri, JsonNode json ) { HttpPost httpPost = new HttpPost( uri ); String body = null; if( json != null ) { body = jsonHelper.serialize( json ); httpPost.setEntity( new NStringEntity( body, ContentType.create( "application/json", "UTF-8" ) ) ); } return new HttpFuture( this, httpPost, asyncClient.execute( httpPost, null ), body ); }
Example 30
Source Project: Tenable.io-SDK-for-Java Source File: AsyncHttpService.java License: MIT License | 5 votes |
/** * Makes an HTTP PUT request using the given URI and optional body. * * @param uri the URI to use for the PUT call * @param json Optional, can be null. the JSON to PUT * @return the resulting HttpFuture instance */ public HttpFuture doPut( URI uri, JsonNode json ) { HttpPut httpPut = new HttpPut( uri ); String body = null; if( json != null ) { body = jsonHelper.serialize( json ); httpPut.setEntity( new NStringEntity( body, ContentType.create( "application/json", "UTF-8" ) ) ); } return new HttpFuture( this, httpPut, asyncClient.execute( httpPut, null ), body ); }