Search in sources :

Example 1 with ElasticEndpoint

use of org.sagacity.sqltoy.config.model.ElasticEndpoint 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 2 with ElasticEndpoint

use of org.sagacity.sqltoy.config.model.ElasticEndpoint in project sagacity-sqltoy by chenrenfei.

the class SqlToyContext method setElasticEndpoints.

/**
 * @param elasticConfigs
 *            the elasticConfigs to set
 */
public void setElasticEndpoints(List<ElasticEndpoint> elasticEndpointList) {
    if (elasticEndpointList != null && !elasticEndpointList.isEmpty()) {
        // 第一个作为默认值
        defaultElastic = elasticEndpointList.get(0).getId();
        for (ElasticEndpoint config : elasticEndpointList) {
            // 初始化restClient
            config.initRestClient();
            elasticEndpoints.put(config.getId().toLowerCase(), config);
        }
    }
}
Also used : ElasticEndpoint(org.sagacity.sqltoy.config.model.ElasticEndpoint)

Aggregations

ElasticEndpoint (org.sagacity.sqltoy.config.model.ElasticEndpoint)2 JSONObject (com.alibaba.fastjson.JSONObject)1 HttpEntity (org.apache.http.HttpEntity)1 HttpResponse (org.apache.http.HttpResponse)1 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)1 CredentialsProvider (org.apache.http.client.CredentialsProvider)1 HttpPost (org.apache.http.client.methods.HttpPost)1 StringEntity (org.apache.http.entity.StringEntity)1 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)1 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)1 Response (org.elasticsearch.client.Response)1 RestClient (org.elasticsearch.client.RestClient)1