Search in sources :

Example 1 with Query

use of com.alibaba.nacos.common.http.param.Query in project nacos by alibaba.

the class ServerHttpAgent method httpDelete.

@Override
public HttpRestResult<String> httpDelete(String path, Map<String, String> headers, Map<String, String> paramValues, String encode, long readTimeoutMs) throws Exception {
    final long endTime = System.currentTimeMillis() + readTimeoutMs;
    String currentServerAddr = serverListMgr.getCurrentServerAddr();
    int maxRetry = this.maxRetry;
    HttpClientConfig httpConfig = HttpClientConfig.builder().setReadTimeOutMillis(Long.valueOf(readTimeoutMs).intValue()).setConTimeOutMillis(ConfigHttpClientManager.getInstance().getConnectTimeoutOrDefault(100)).build();
    do {
        try {
            Header newHeaders = Header.newInstance();
            if (headers != null) {
                newHeaders.addAll(headers);
            }
            Query query = Query.newInstance().initParams(paramValues);
            HttpRestResult<String> result = NACOS_RESTTEMPLATE.delete(getUrl(currentServerAddr, path), httpConfig, newHeaders, query, String.class);
            if (isFail(result)) {
                LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}", serverListMgr.getCurrentServerAddr(), result.getCode());
            } else {
                // Update the currently available server addr
                serverListMgr.updateCurrentServerAddr(currentServerAddr);
                return result;
            }
        } catch (ConnectException connectException) {
            LOGGER.error("[NACOS ConnectException httpDelete] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), ExceptionUtil.getStackTrace(connectException));
        } catch (SocketTimeoutException stoe) {
            LOGGER.error("[NACOS SocketTimeoutException httpDelete] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), ExceptionUtil.getStackTrace(stoe));
        } catch (Exception ex) {
            LOGGER.error("[NACOS Exception httpDelete] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ex);
            throw ex;
        }
        if (serverListMgr.getIterator().hasNext()) {
            currentServerAddr = serverListMgr.getIterator().next();
        } else {
            maxRetry--;
            if (maxRetry < 0) {
                throw new ConnectException("[NACOS HTTP-DELETE] The maximum number of tolerable server reconnection errors has been reached");
            }
            serverListMgr.refreshCurrentServerAddr();
        }
    } while (System.currentTimeMillis() <= endTime);
    LOGGER.error("no available server");
    throw new ConnectException("no available server");
}
Also used : HttpClientConfig(com.alibaba.nacos.common.http.HttpClientConfig) SocketTimeoutException(java.net.SocketTimeoutException) Header(com.alibaba.nacos.common.http.param.Header) Query(com.alibaba.nacos.common.http.param.Query) SocketTimeoutException(java.net.SocketTimeoutException) NacosException(com.alibaba.nacos.api.exception.NacosException) ConnectException(java.net.ConnectException) ConnectException(java.net.ConnectException)

Example 2 with Query

use of com.alibaba.nacos.common.http.param.Query in project nacos by alibaba.

the class ServerHttpAgent method httpGet.

@Override
public HttpRestResult<String> httpGet(String path, Map<String, String> headers, Map<String, String> paramValues, String encode, long readTimeoutMs) throws Exception {
    final long endTime = System.currentTimeMillis() + readTimeoutMs;
    String currentServerAddr = serverListMgr.getCurrentServerAddr();
    int maxRetry = this.maxRetry;
    HttpClientConfig httpConfig = HttpClientConfig.builder().setReadTimeOutMillis(Long.valueOf(readTimeoutMs).intValue()).setConTimeOutMillis(ConfigHttpClientManager.getInstance().getConnectTimeoutOrDefault(100)).build();
    do {
        try {
            Header newHeaders = Header.newInstance();
            if (headers != null) {
                newHeaders.addAll(headers);
            }
            Query query = Query.newInstance().initParams(paramValues);
            HttpRestResult<String> result = NACOS_RESTTEMPLATE.get(getUrl(currentServerAddr, path), httpConfig, newHeaders, query, String.class);
            if (isFail(result)) {
                LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}", serverListMgr.getCurrentServerAddr(), result.getCode());
            } else {
                // Update the currently available server addr
                serverListMgr.updateCurrentServerAddr(currentServerAddr);
                return result;
            }
        } catch (ConnectException connectException) {
            LOGGER.error("[NACOS ConnectException httpGet] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), connectException.getMessage());
        } catch (SocketTimeoutException socketTimeoutException) {
            LOGGER.error("[NACOS SocketTimeoutException httpGet] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), socketTimeoutException.getMessage());
        } catch (Exception ex) {
            LOGGER.error("[NACOS Exception httpGet] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ex);
            throw ex;
        }
        if (serverListMgr.getIterator().hasNext()) {
            currentServerAddr = serverListMgr.getIterator().next();
        } else {
            maxRetry--;
            if (maxRetry < 0) {
                throw new ConnectException("[NACOS HTTP-GET] The maximum number of tolerable server reconnection errors has been reached");
            }
            serverListMgr.refreshCurrentServerAddr();
        }
    } while (System.currentTimeMillis() <= endTime);
    LOGGER.error("no available server");
    throw new ConnectException("no available server");
}
Also used : HttpClientConfig(com.alibaba.nacos.common.http.HttpClientConfig) SocketTimeoutException(java.net.SocketTimeoutException) Header(com.alibaba.nacos.common.http.param.Header) Query(com.alibaba.nacos.common.http.param.Query) SocketTimeoutException(java.net.SocketTimeoutException) NacosException(com.alibaba.nacos.api.exception.NacosException) ConnectException(java.net.ConnectException) ConnectException(java.net.ConnectException)

Example 3 with Query

use of com.alibaba.nacos.common.http.param.Query in project nacos by alibaba.

the class HttpClient method request.

/**
 * Do http request.
 *
 * @param url            request url
 * @param headers        request headers
 * @param paramValues    request params
 * @param body           request body
 * @param connectTimeout timeout of connection
 * @param readTimeout    timeout of request
 * @param encoding       charset of request
 * @param method         http method
 * @return {@link RestResult} as response
 */
public static RestResult<String> request(String url, List<String> headers, Map<String, String> paramValues, String body, int connectTimeout, int readTimeout, String encoding, String method) {
    Header header = Header.newInstance();
    if (CollectionUtils.isNotEmpty(headers)) {
        header.addAll(headers);
    }
    header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    header.addParam(HttpHeaderConsts.CLIENT_VERSION_HEADER, VersionUtils.version);
    header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, UtilsAndCommons.SERVER_VERSION);
    header.addParam(HttpHeaderConsts.REQUEST_SOURCE_HEADER, EnvUtil.getLocalAddress());
    header.addParam(HttpHeaderConsts.ACCEPT_CHARSET, encoding);
    AuthHeaderUtil.addIdentityToHeader(header);
    HttpClientConfig httpClientConfig = HttpClientConfig.builder().setConTimeOutMillis(connectTimeout).setReadTimeOutMillis(readTimeout).build();
    Query query = Query.newInstance().initParams(paramValues);
    query.addParam(FieldsConstants.ENCODING, ENCODING);
    query.addParam(FieldsConstants.NOFIX, NOFIX);
    try {
        return APACHE_SYNC_NACOS_REST_TEMPLATE.exchange(url, httpClientConfig, header, query, body, method, String.class);
    } catch (Exception e) {
        Loggers.SRV_LOG.warn("Exception while request: {}, caused: {}", url, e);
        return RestResult.<String>builder().withCode(500).withMsg(e.toString()).build();
    }
}
Also used : HttpClientConfig(com.alibaba.nacos.common.http.HttpClientConfig) Header(com.alibaba.nacos.common.http.param.Header) Query(com.alibaba.nacos.common.http.param.Query)

Example 4 with Query

use of com.alibaba.nacos.common.http.param.Query in project nacos by alibaba.

the class ConfigDerbyRaft_DITCase method test_e_derby_ops.

@Test
public void test_e_derby_ops() throws Exception {
    String url = "http://127.0.0.1:8848/nacos/v1/cs/ops/derby";
    Query query = Query.newInstance().addParam("sql", "select * from users");
    RestResult<List<Map<String, Object>>> result = NACOS_REST_TEMPLATE.get(url, Header.EMPTY, query, new GenericType<RestResult<List<Map<String, Object>>>>() {
    }.getType());
    System.out.println(result.getData());
    Assert.assertTrue(result.ok());
    List<Map<String, Object>> list = result.getData();
    Assert.assertEquals(1, list.size());
    Assert.assertEquals("nacos", list.get(0).get("USERNAME"));
}
Also used : GenericType(com.alibaba.nacos.core.utils.GenericType) Query(com.alibaba.nacos.common.http.param.Query) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test) BaseClusterTest(com.alibaba.nacos.test.base.BaseClusterTest)

Example 5 with Query

use of com.alibaba.nacos.common.http.param.Query in project nacos by alibaba.

the class ConfigDerbyRaft_DITCase method test_g_derby_ops_no_select.

@Test
public void test_g_derby_ops_no_select() throws Exception {
    String url = "http://127.0.0.1:8848/nacos/v1/cs/ops/derby";
    Query query = Query.newInstance().addParam("sql", "update users set username='nacos'");
    RestResult<Object> result = NACOS_REST_TEMPLATE.get(url, Header.EMPTY, query, new GenericType<RestResult<Object>>() {
    }.getType());
    System.out.println(result);
    Assert.assertFalse(result.ok());
    Assert.assertEquals("Only query statements are allowed to be executed", result.getMessage());
}
Also used : GenericType(com.alibaba.nacos.core.utils.GenericType) Query(com.alibaba.nacos.common.http.param.Query) Test(org.junit.Test) BaseClusterTest(com.alibaba.nacos.test.base.BaseClusterTest)

Aggregations

Query (com.alibaba.nacos.common.http.param.Query)13 Test (org.junit.Test)7 Header (com.alibaba.nacos.common.http.param.Header)5 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 NacosException (com.alibaba.nacos.api.exception.NacosException)3 HttpClientConfig (com.alibaba.nacos.common.http.HttpClientConfig)3 GenericType (com.alibaba.nacos.core.utils.GenericType)3 BaseClusterTest (com.alibaba.nacos.test.base.BaseClusterTest)2 ConnectException (java.net.ConnectException)2 SocketTimeoutException (java.net.SocketTimeoutException)2 NacosLoadException (com.alibaba.nacos.api.exception.runtime.NacosLoadException)1 NacosAsyncRestTemplate (com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate)1 ConfigInfo4Beta (com.alibaba.nacos.config.server.model.ConfigInfo4Beta)1 Member (com.alibaba.nacos.core.cluster.Member)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 IOException (java.io.IOException)1 StringReader (java.io.StringReader)1 ArrayList (java.util.ArrayList)1