use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.Response in project janusgraph by JanusGraph.
the class RestElasticSearchClient method performRequest.
private Response performRequest(String method, String path, byte[] requestData) throws IOException {
final HttpEntity entity = requestData != null ? new ByteArrayEntity(requestData, ContentType.APPLICATION_JSON) : null;
final Response response = delegate.performRequest(method, path, Collections.emptyMap(), entity);
if (response.getStatusLine().getStatusCode() >= 400) {
throw new IOException("Error executing request: " + response.getStatusLine().getReasonPhrase());
}
return response;
}
use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.Response in project janusgraph by JanusGraph.
the class RestElasticSearchClient method search.
@Override
public RestSearchResponse search(String indexName, String type, Map<String, Object> request, boolean useScroll) throws IOException {
final StringBuilder path = new StringBuilder(REQUEST_SEPARATOR).append(indexName);
if (!Strings.isNullOrEmpty(type)) {
path.append(REQUEST_SEPARATOR).append(type);
}
path.append(REQUEST_SEPARATOR).append("_search");
if (useScroll)
path.append(REQUEST_PARAM_BEGINNING).append("scroll=").append(scrollKeepAlive);
final byte[] requestData = mapper.writeValueAsBytes(request);
if (log.isDebugEnabled()) {
log.debug("Elasticsearch request: " + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request));
}
final Response response = performRequest(REQUEST_TYPE_POST, path.toString(), requestData);
try (final InputStream inputStream = response.getEntity().getContent()) {
return mapper.readValue(inputStream, RestSearchResponse.class);
}
}
use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.Response in project components by Talend.
the class ElasticsearchDatastoreRuntime method doHealthChecks.
@Override
public Iterable<ValidationResult> doHealthChecks(RuntimeContainer container) {
ValidationResult validationResult;
try (RestClient client = ElasticsearchConnection.createClient(properties)) {
Response response = client.performRequest("GET", "/_cluster/health", new HashMap<String, String>(), new BasicHeader("", ""));
ElasticsearchResponse esResponse = new ElasticsearchResponse(response);
if (esResponse.isOk()) {
JsonNode entity = esResponse.getEntity();
String status = entity.path("status").asText();
if (status != "red") {
validationResult = ValidationResult.OK;
} else {
validationResult = new ValidationResult(TalendRuntimeException.createUnexpectedException(String.format("Cluster %s status is red", entity.path("cluster_name").asText())));
}
} else {
validationResult = new ValidationResult(TalendRuntimeException.createUnexpectedException(esResponse.getStatusLine().toString()));
}
} catch (IOException e) {
validationResult = new ValidationResult(TalendRuntimeException.createUnexpectedException(e.getMessage()));
}
return Arrays.asList(validationResult);
}
use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.Response in project sagacity-sqltoy by chenrenfei.
the class HttpClientUtils method doPost.
/**
* @todo 执行post请求
* @param sqltoyContext
* @param nosqlConfig
* @param url
* @param jsonObject
* @return
* @throws Exception
*/
public static JSONObject doPost(SqlToyContext sqltoyContext, NoSqlConfigModel nosqlConfig, Object postValue) throws Exception {
ElasticEndpoint esConfig = sqltoyContext.getElasticEndpoint(nosqlConfig.getUrl());
if (esConfig.getUrl() == null)
throw new Exception("请正确配置sqltoyContext elasticConfigs 指定es的服务地址!");
String charset = (nosqlConfig.getCharset() == null) ? CHARSET : nosqlConfig.getCharset();
HttpEntity httpEntity = new StringEntity(nosqlConfig.isSqlMode() ? postValue.toString() : JSON.toJSONString(postValue), charset);
((StringEntity) httpEntity).setContentEncoding(charset);
((StringEntity) httpEntity).setContentType(CONTENT_TYPE);
String realUrl;
// 返回结果
HttpEntity reponseEntity = null;
if (esConfig.getRestClient() != null) {
realUrl = wrapUrl(esConfig.getPath(), nosqlConfig);
if (sqltoyContext.isDebug())
logger.debug("esRestClient执行:URL=[{}],Path={},执行的JSON=[{}]", esConfig.getUrl(), realUrl, JSON.toJSONString(postValue));
// 默认采用post请求
RestClient restClient = null;
try {
restClient = esConfig.getRestClient();
Response response = restClient.performRequest("POST", realUrl, Collections.<String, String>emptyMap(), httpEntity);
reponseEntity = response.getEntity();
} catch (Exception e) {
throw e;
} finally {
if (restClient != null)
restClient.close();
}
} else {
realUrl = wrapUrl(esConfig.getUrl(), nosqlConfig);
HttpPost httpPost = new HttpPost(realUrl);
if (sqltoyContext.isDebug())
logger.debug("httpClient执行URL=[{}],执行的JSON=[{}]", realUrl, JSON.toJSONString(postValue));
httpPost.setEntity(httpEntity);
// 设置connection是否自动关闭
httpPost.setHeader("Connection", "close");
// 自定义超时
if (nosqlConfig.getRequestTimeout() != 30000 || nosqlConfig.getConnectTimeout() != 10000 || nosqlConfig.getSocketTimeout() != 180000) {
httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(nosqlConfig.getRequestTimeout()).setConnectTimeout(nosqlConfig.getConnectTimeout()).setSocketTimeout(nosqlConfig.getSocketTimeout()).build());
} else
httpPost.setConfig(requestConfig);
CloseableHttpClient client = null;
try {
if (StringUtil.isNotBlank(esConfig.getUsername()) && StringUtil.isNotBlank(esConfig.getPassword())) {
// 凭据提供器
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, // 认证用户名和密码
new UsernamePasswordCredentials(esConfig.getUsername(), esConfig.getPassword()));
client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
} else
client = HttpClients.createDefault();
HttpResponse response = client.execute(httpPost);
reponseEntity = response.getEntity();
} catch (Exception e) {
throw e;
}
}
String result = null;
if (reponseEntity != null) {
result = EntityUtils.toString(reponseEntity, nosqlConfig.getCharset());
if (sqltoyContext.isDebug())
logger.debug("result={}", result);
}
if (StringUtil.isBlank(result))
return null;
// 将结果转换为JSON对象
JSONObject json = JSON.parseObject(result);
// 存在错误
if (json.containsKey("error")) {
String errorMessage = JSON.toJSONString(json.getJSONObject("error").getJSONArray("root_cause").get(0));
logger.error("elastic查询失败,URL:[{}],错误信息:[{}]", nosqlConfig.getUrl(), errorMessage);
throw new Exception("ElasticSearch查询失败,错误信息:" + errorMessage);
}
return json;
}
use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.Response in project legendarybot by greatman.
the class WoWUtils method getRealmInformation.
/**
* Retrieve the informatoin of a realm
* @param bot The bot instance.
* @param region The region the realm is in
* @param realm The realm name
* @return A Json string containing information about the realm. Returns null if no realm is found.
*/
public static String getRealmInformation(LegendaryBot bot, String region, String realm) {
JSONObject search = new JSONObject();
JSONObject query = new JSONObject();
JSONArray fields = new JSONArray();
fields.add("name");
fields.add("slug");
JSONObject multi_match = new JSONObject();
multi_match.put("query", realm);
multi_match.put("fields", fields);
query.put("multi_match", multi_match);
search.put("query", query);
HttpEntity entity = new NStringEntity(search.toJSONString(), ContentType.APPLICATION_JSON);
try {
Response response = bot.getElasticSearch().performRequest("POST", "/wow/realm_" + region.toLowerCase() + "/_search", Collections.emptyMap(), entity);
String jsonResponse = EntityUtils.toString(response.getEntity());
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(jsonResponse);
JSONArray hit = (JSONArray) ((JSONObject) obj.get("hits")).get("hits");
if (hit.size() == 0) {
return null;
}
JSONObject firstItem = (JSONObject) hit.get(0);
JSONObject source = (JSONObject) firstItem.get("_source");
return source.toJSONString();
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return null;
}
Aggregations