Search in sources :

Example 11 with Response

use of 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;
}
Also used : RestBulkItemResponse(org.janusgraph.diskstorage.es.rest.RestBulkResponse.RestBulkItemResponse) Response(org.elasticsearch.client.Response) HttpEntity(org.apache.http.HttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) IOException(java.io.IOException)

Example 12 with Response

use of 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);
    }
}
Also used : RestBulkItemResponse(org.janusgraph.diskstorage.es.rest.RestBulkResponse.RestBulkItemResponse) Response(org.elasticsearch.client.Response) InputStream(java.io.InputStream)

Example 13 with Response

use of 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);
}
Also used : Response(org.elasticsearch.client.Response) RestClient(org.elasticsearch.client.RestClient) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) ValidationResult(org.talend.daikon.properties.ValidationResult) BasicHeader(org.apache.http.message.BasicHeader)

Example 14 with Response

use of 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;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpEntity(org.apache.http.HttpEntity) RestClient(org.elasticsearch.client.RestClient) HttpResponse(org.apache.http.HttpResponse) ElasticEndpoint(org.sagacity.sqltoy.config.model.ElasticEndpoint) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Response(org.elasticsearch.client.Response) HttpResponse(org.apache.http.HttpResponse) StringEntity(org.apache.http.entity.StringEntity) JSONObject(com.alibaba.fastjson.JSONObject)

Example 15 with Response

use of 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;
}
Also used : Response(org.elasticsearch.client.Response) NStringEntity(org.apache.http.nio.entity.NStringEntity) JSONObject(org.json.simple.JSONObject) HttpEntity(org.apache.http.HttpEntity) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) IOException(java.io.IOException) ParseException(org.json.simple.parser.ParseException)

Aggregations

Response (org.elasticsearch.client.Response)75 IOException (java.io.IOException)24 Request (org.elasticsearch.client.Request)19 BasicHeader (org.apache.http.message.BasicHeader)14 NStringEntity (org.apache.http.nio.entity.NStringEntity)14 HttpEntity (org.apache.http.HttpEntity)13 ResponseException (org.elasticsearch.client.ResponseException)10 JsonNode (com.fasterxml.jackson.databind.JsonNode)9 HashMap (java.util.HashMap)9 RestClient (org.elasticsearch.client.RestClient)8 Map (java.util.Map)7 Response (org.graylog.shaded.elasticsearch7.org.elasticsearch.client.Response)7 ArrayList (java.util.ArrayList)6 RestBulkItemResponse (org.janusgraph.diskstorage.es.rest.RestBulkResponse.RestBulkItemResponse)6 JSONArray (org.json.simple.JSONArray)6 JSONObject (org.json.simple.JSONObject)6 JSONParser (org.json.simple.parser.JSONParser)6 ParseException (org.json.simple.parser.ParseException)6 InputStream (java.io.InputStream)5 StringEntity (org.apache.http.entity.StringEntity)5