[ISSUE #2842]Replace Fastjson with Jackson for nacos-api and nacos-client
This commit is contained in:
yanlinly 2020-05-26 22:41:02 +08:00 committed by GitHub
commit a07b0c530f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 654 additions and 109 deletions

View File

@ -0,0 +1,57 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception.runtime;
/**
* Nacos deserialization exception.
*
* @author yangyi
*/
public class NacosDeserializationException extends NacosRuntimeException {
public static final int ERROR_CODE = 101;
private static final long serialVersionUID = -2742350751684273728L;
private static final String DEFAULT_MSG = "Nacos deserialize failed. ";
private static final String MSG_FOR_SPECIFIED_CLASS = "Nacos deserialize for class [%s] failed. ";
private Class<?> targetClass;
public NacosDeserializationException() {
super(ERROR_CODE);
}
public NacosDeserializationException(Class<?> targetClass) {
super(ERROR_CODE, String.format(MSG_FOR_SPECIFIED_CLASS, targetClass.getName()));
this.targetClass = targetClass;
}
public NacosDeserializationException(Throwable throwable) {
super(ERROR_CODE, DEFAULT_MSG, throwable);
}
public NacosDeserializationException(Class<?> targetClass, Throwable throwable) {
super(ERROR_CODE, String.format(MSG_FOR_SPECIFIED_CLASS, targetClass.getName()), throwable);
this.targetClass = targetClass;
}
public Class<?> getTargetClass() {
return targetClass;
}
}

View File

@ -0,0 +1,59 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception.runtime;
/**
* Nacos runtime exception.
*
* @author yangyi
*/
public class NacosRuntimeException extends RuntimeException {
private static final long serialVersionUID = 3513491993982293262L;
public static final String ERROR_MESSAGE_FORMAT = "errCode: %d, errMsg: %s ";
private int errCode;
public NacosRuntimeException(int errCode) {
super();
this.errCode = errCode;
}
public NacosRuntimeException(int errCode, String errMsg) {
super(String.format(ERROR_MESSAGE_FORMAT, errCode, errMsg));
this.errCode = errCode;
}
public NacosRuntimeException(int errCode, Throwable throwable) {
super(throwable);
this.errCode = errCode;
}
public NacosRuntimeException(int errCode, String errMsg, Throwable throwable) {
super(String.format(ERROR_MESSAGE_FORMAT, errCode, errMsg), throwable);
this.errCode = errCode;
}
public int getErrCode() {
return errCode;
}
public void setErrCode(int errCode) {
this.errCode = errCode;
}
}

View File

@ -0,0 +1,57 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.exception.runtime;
/**
* Nacos serialization exception.
*
* @author yangyi
*/
public class NacosSerializationException extends NacosRuntimeException {
public static final int ERROR_CODE = 100;
private static final long serialVersionUID = -4308536346316915612L;
private static final String DEFAULT_MSG = "Nacos serialize failed. ";
private static final String MSG_FOR_SPECIFIED_CLASS = "Nacos serialize for class [%s] failed. ";
private Class<?> serializedClass;
public NacosSerializationException() {
super(ERROR_CODE);
}
public NacosSerializationException(Class<?> serializedClass) {
super(ERROR_CODE, String.format(MSG_FOR_SPECIFIED_CLASS, serializedClass.getName()));
this.serializedClass = serializedClass;
}
public NacosSerializationException(Throwable throwable) {
super(ERROR_CODE, DEFAULT_MSG, throwable);
}
public NacosSerializationException(Class<?> serializedClass, Throwable throwable) {
super(ERROR_CODE, String.format(MSG_FOR_SPECIFIED_CLASS, serializedClass.getName()), throwable);
this.serializedClass = serializedClass;
}
public Class<?> getSerializedClass() {
return serializedClass;
}
}

View File

@ -19,9 +19,6 @@ import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
@ -179,13 +176,18 @@ public class Instance {
@Override
public String toString() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
try {
return objectMapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
throw new RuntimeException("Instance toJson failed", e);
}
return "Instance{" +
"instanceId='" + instanceId + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", weight=" + weight +
", healthy=" + healthy +
", enabled=" + enabled +
", ephemeral=" + ephemeral +
", clusterName='" + clusterName + '\'' +
", serviceName='" + serviceName + '\'' +
", metadata=" + metadata +
'}';
}
public String toInetAddr() {

View File

@ -15,8 +15,6 @@
*/
package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.fastjson.JSON;
import java.util.List;
/**
@ -47,6 +45,9 @@ public class ListView<T> {
@Override
public String toString() {
return JSON.toJSONString(this);
return "ListView{" +
"data=" + data +
", count=" + count +
'}';
}
}

View File

@ -15,8 +15,10 @@
*/
package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.nacos.api.common.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@ -29,10 +31,12 @@ import java.util.List;
*
* @author nkorange
*/
@JsonInclude(Include.NON_NULL)
public class ServiceInfo {
@JSONField(serialize = false)
@JsonIgnore
private String jsonFromServer = EMPTY;
public static final String SPLITER = "@@";
private String name;
@ -43,7 +47,6 @@ public class ServiceInfo {
private long cacheMillis = 1000L;
@JSONField(name = "hosts")
private List<Instance> hosts = new ArrayList<Instance>();
private long lastRefTime = 0L;
@ -162,7 +165,7 @@ public class ServiceInfo {
return true;
}
@JSONField(serialize = false)
@JsonIgnore
public String getJsonFromServer() {
return jsonFromServer;
}
@ -171,12 +174,12 @@ public class ServiceInfo {
this.jsonFromServer = jsonFromServer;
}
@JSONField(serialize = false)
@JsonIgnore
public String getKey() {
return getKey(name, clusters);
}
@JSONField(serialize = false)
@JsonIgnore
public String getKeyEncoded() {
try {
return getKey(URLEncoder.encode(name, "UTF-8"), clusters);
@ -185,7 +188,6 @@ public class ServiceInfo {
}
}
@JSONField(serialize = false)
public static ServiceInfo fromKey(String key) {
ServiceInfo serviceInfo = new ServiceInfo();
int maxSegCount = 3;
@ -201,7 +203,7 @@ public class ServiceInfo {
return serviceInfo;
}
@JSONField(serialize = false)
@JsonIgnore
public static String getKey(String name, String clusters) {
if (!isEmpty(clusters)) {

View File

@ -15,7 +15,6 @@
*/
package com.alibaba.nacos.api.annotation;
import com.alibaba.fastjson.JSON;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.env.MockEnvironment;

View File

@ -0,0 +1,71 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class ServiceInfoTest {
private ObjectMapper mapper;
private ServiceInfo serviceInfo;
@Before
public void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
serviceInfo = new ServiceInfo("testName", "testClusters");
}
@Test
public void testSerialize() throws JsonProcessingException {
String actual = mapper.writeValueAsString(serviceInfo);
assertTrue(actual.contains("\"name\":\"testName\""));
assertTrue(actual.contains("\"clusters\":\"testClusters\""));
assertTrue(actual.contains("\"cacheMillis\":1000"));
assertTrue(actual.contains("\"hosts\":[]"));
assertTrue(actual.contains("\"lastRefTime\":0"));
assertTrue(actual.contains("\"checksum\":\"\""));
assertTrue(actual.contains("\"valid\":true"));
assertTrue(actual.contains("\"allIPs\":false"));
assertFalse(actual.contains("jsonFromServer"));
assertFalse(actual.contains("key"));
assertFalse(actual.contains("keyEncoded"));
}
@Test
public void testDeserialize() throws IOException {
String example = "{\"name\":\"testName\",\"clusters\":\"testClusters\",\"cacheMillis\":1000,\"hosts\":[],\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"valid\":true,\"groupName\":\"\"}";
ServiceInfo actual = mapper.readValue(example, ServiceInfo.class);
assertEquals("testName", actual.getName());
assertEquals("testClusters", actual.getClusters());
assertEquals("", actual.getChecksum());
assertEquals("", actual.getGroupName());
assertEquals(1000, actual.getCacheMillis());
assertEquals(0, actual.getLastRefTime());
assertTrue(actual.getHosts().isEmpty());
assertTrue(actual.isValid());
assertFalse(actual.isAllIPs());
}
}

View File

@ -34,7 +34,6 @@ import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.InitUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.client.security.SecurityProxy;
import com.alibaba.nacos.client.utils.ValidatorUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
@ -44,7 +43,6 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
/**
* Nacos Naming Service

View File

@ -15,13 +15,14 @@
*/
package com.alibaba.nacos.client.naming.backups;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.naming.cache.ConcurrentDiskUtil;
import com.alibaba.nacos.client.naming.cache.DiskCache;
import com.alibaba.nacos.client.naming.core.HostReactor;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.common.utils.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
@ -180,7 +181,7 @@ public class FailoverReactor {
String json;
if ((json = reader.readLine()) != null) {
try {
dom = JSON.parseObject(json, ServiceInfo.class);
dom = JacksonUtils.toObj(json, ServiceInfo.class);
} catch (Exception e) {
NAMING_LOGGER.error("[NA] error while parsing cached dom : " + json, e);
}

View File

@ -15,8 +15,6 @@
*/
package com.alibaba.nacos.client.naming.beat;
import com.alibaba.fastjson.JSON;
import java.util.Map;
/**
@ -36,7 +34,17 @@ public class BeatInfo {
@Override
public String toString() {
return JSON.toJSONString(this);
return "BeatInfo{" +
"port=" + port +
", ip='" + ip + '\'' +
", weight=" + weight +
", serviceName='" + serviceName + '\'' +
", cluster='" + cluster + '\'' +
", metadata=" + metadata +
", scheduled=" + scheduled +
", period=" + period +
", stopped=" + stopped +
'}';
}
public String getServiceName() {

View File

@ -15,8 +15,6 @@
*/
package com.alibaba.nacos.client.naming.beat;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.CommonParams;
@ -26,6 +24,8 @@ import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Map;
import java.util.concurrent.*;
@ -43,7 +43,7 @@ public class BeatReactor {
private boolean lightBeatEnabled = false;
public final Map<String, BeatInfo> dom2Beat = new ConcurrentHashMap<String, BeatInfo>();
public final Map<String, BeatInfo> dom2Beat = new ConcurrentHashMap<>();
public BeatReactor(NamingProxy serverProxy) {
this(serverProxy, UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT);
@ -105,19 +105,19 @@ public class BeatReactor {
}
long nextTime = beatInfo.getPeriod();
try {
JSONObject result = serverProxy.sendBeat(beatInfo, BeatReactor.this.lightBeatEnabled);
long interval = result.getIntValue("clientBeatInterval");
JsonNode result = serverProxy.sendBeat(beatInfo, BeatReactor.this.lightBeatEnabled);
long interval = result.get("clientBeatInterval").asInt();
boolean lightBeatEnabled = false;
if (result.containsKey(CommonParams.LIGHT_BEAT_ENABLED)) {
lightBeatEnabled = result.getBooleanValue(CommonParams.LIGHT_BEAT_ENABLED);
if (result.has(CommonParams.LIGHT_BEAT_ENABLED)) {
lightBeatEnabled = result.get(CommonParams.LIGHT_BEAT_ENABLED).asBoolean();
}
BeatReactor.this.lightBeatEnabled = lightBeatEnabled;
if (interval > 0) {
nextTime = interval;
}
int code = NamingResponseCode.OK;
if (result.containsKey(CommonParams.CODE)) {
code = result.getIntValue(CommonParams.CODE);
if (result.has(CommonParams.CODE)) {
code = result.get(CommonParams.CODE).asInt();
}
if (code == NamingResponseCode.RESOURCE_NOT_FOUND) {
Instance instance = new Instance();
@ -137,7 +137,7 @@ public class BeatReactor {
}
} catch (NacosException ne) {
NAMING_LOGGER.error("[CLIENT-BEAT] failed to send beat: {}, code: {}, msg: {}",
JSON.toJSONString(beatInfo), ne.getErrCode(), ne.getErrMsg());
JacksonUtils.toJson(beatInfo), ne.getErrCode(), ne.getErrMsg());
}
executorService.schedule(new BeatTask(beatInfo), nextTime, TimeUnit.MILLISECONDS);

View File

@ -15,11 +15,12 @@
*/
package com.alibaba.nacos.client.naming.cache;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
@ -58,7 +59,7 @@ public class DiskCache {
String json = dom.getJsonFromServer();
if (StringUtils.isEmpty(json)) {
json = JSON.toJSONString(dom);
json = JacksonUtils.toJson(dom);
}
keyContentBuffer.append(json);
@ -112,10 +113,10 @@ public class DiskCache {
continue;
}
newFormat = JSON.parseObject(json, ServiceInfo.class);
newFormat = JacksonUtils.toObj(json, ServiceInfo.class);
if (StringUtils.isEmpty(newFormat.getName())) {
ips.add(JSON.parseObject(json, Instance.class));
ips.add(JacksonUtils.toObj(json, Instance.class));
}
} catch (Throwable e) {
NAMING_LOGGER.error("[NA] error while parsing cache file: " + json, e);

View File

@ -15,7 +15,6 @@
*/
package com.alibaba.nacos.client.naming.core;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
@ -24,6 +23,8 @@ import com.alibaba.nacos.client.naming.backups.FailoverReactor;
import com.alibaba.nacos.client.naming.cache.DiskCache;
import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.common.utils.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
@ -98,7 +99,7 @@ public class HostReactor {
}
public ServiceInfo processServiceJSON(String json) {
ServiceInfo serviceInfo = JSON.parseObject(json, ServiceInfo.class);
ServiceInfo serviceInfo = JacksonUtils.toObj(json, ServiceInfo.class);
ServiceInfo oldService = serviceInfoMap.get(serviceInfo.getKey());
if (serviceInfo.getHosts() == null || !serviceInfo.validate()) {
//empty or error push, just ignore
@ -162,19 +163,19 @@ public class HostReactor {
if (newHosts.size() > 0) {
changed = true;
NAMING_LOGGER.info("new ips(" + newHosts.size() + ") service: "
+ serviceInfo.getKey() + " -> " + JSON.toJSONString(newHosts));
+ serviceInfo.getKey() + " -> " + JacksonUtils.toJson(newHosts));
}
if (remvHosts.size() > 0) {
changed = true;
NAMING_LOGGER.info("removed ips(" + remvHosts.size() + ") service: "
+ serviceInfo.getKey() + " -> " + JSON.toJSONString(remvHosts));
+ serviceInfo.getKey() + " -> " + JacksonUtils.toJson(remvHosts));
}
if (modHosts.size() > 0) {
changed = true;
NAMING_LOGGER.info("modified ips(" + modHosts.size() + ") service: "
+ serviceInfo.getKey() + " -> " + JSON.toJSONString(modHosts));
+ serviceInfo.getKey() + " -> " + JacksonUtils.toJson(modHosts));
}
serviceInfo.setJsonFromServer(json);
@ -186,8 +187,8 @@ public class HostReactor {
} else {
changed = true;
NAMING_LOGGER.info("init new ips(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getKey() + " -> " + JSON
.toJSONString(serviceInfo.getHosts()));
NAMING_LOGGER.info("init new ips(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getKey() + " -> " +
JacksonUtils.toJson(serviceInfo.getHosts()));
serviceInfoMap.put(serviceInfo.getKey(), serviceInfo);
eventDispatcher.serviceChanged(serviceInfo);
serviceInfo.setJsonFromServer(json);
@ -198,7 +199,7 @@ public class HostReactor {
if (changed) {
NAMING_LOGGER.info("current ips:(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getKey() +
" -> " + JSON.toJSONString(serviceInfo.getHosts()));
" -> " + JacksonUtils.toJson(serviceInfo.getHosts()));
}
return serviceInfo;
@ -214,7 +215,7 @@ public class HostReactor {
public ServiceInfo getServiceInfoDirectlyFromServer(final String serviceName, final String clusters) throws NacosException {
String result = serverProxy.queryList(serviceName, clusters, 0, false);
if (StringUtils.isNotEmpty(result)) {
return JSON.parseObject(result, ServiceInfo.class);
return JacksonUtils.toObj(result, ServiceInfo.class);
}
return null;
}

View File

@ -15,7 +15,7 @@
*/
package com.alibaba.nacos.client.naming.core;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.IoUtils;
@ -75,7 +75,7 @@ public class PushReceiver implements Runnable {
String json = new String(IoUtils.tryDecompress(packet.getData()), "UTF-8").trim();
NAMING_LOGGER.info("received push data: " + json + " from " + packet.getAddress().toString());
PushPacket pushPacket = JSON.parseObject(json, PushPacket.class);
PushPacket pushPacket = JacksonUtils.toObj(json, PushPacket.class);
String ack;
if ("dom".equals(pushPacket.type) || "service".equals(pushPacket.type)) {
hostReactor.processServiceJSON(pushPacket.data);
@ -89,7 +89,7 @@ public class PushReceiver implements Runnable {
ack = "{\"type\": \"dump-ack\""
+ ", \"lastRefTime\": \"" + pushPacket.lastRefTime
+ "\", \"data\":" + "\""
+ StringUtils.escapeJavaScript(JSON.toJSONString(hostReactor.getServiceInfoMap()))
+ StringUtils.escapeJavaScript(JacksonUtils.toJson(hostReactor.getServiceInfoMap()))
+ "\"}";
} else {
// do nothing send ack only

View File

@ -15,9 +15,6 @@
*/
package com.alibaba.nacos.client.naming.net;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
@ -42,8 +39,12 @@ import com.alibaba.nacos.client.utils.TemplateUtils;
import com.alibaba.nacos.common.constant.HttpHeaderConsts;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.alibaba.nacos.common.utils.VersionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
@ -207,7 +208,7 @@ public class NamingProxy {
params.put("enable", String.valueOf(instance.isEnabled()));
params.put("healthy", String.valueOf(instance.isHealthy()));
params.put("ephemeral", String.valueOf(instance.isEphemeral()));
params.put("metadata", JSON.toJSONString(instance.getMetadata()));
params.put("metadata", JacksonUtils.toJson(instance.getMetadata()));
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.POST);
@ -243,7 +244,7 @@ public class NamingProxy {
params.put("weight", String.valueOf(instance.getWeight()));
params.put("enabled", String.valueOf(instance.isEnabled()));
params.put("ephemeral", String.valueOf(instance.isEphemeral()));
params.put("metadata", JSON.toJSONString(instance.getMetadata()));
params.put("metadata", JacksonUtils.toJson(instance.getMetadata()));
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.PUT);
}
@ -258,8 +259,7 @@ public class NamingProxy {
params.put(CommonParams.GROUP_NAME, groupName);
String result = reqAPI(UtilAndComs.NACOS_URL_SERVICE, params, HttpMethod.GET);
JSONObject jsonObject = JSON.parseObject(result);
return jsonObject.toJavaObject(Service.class);
return JacksonUtils.toObj(result, Service.class);
}
public void createService(Service service, AbstractSelector selector) throws NacosException {
@ -272,8 +272,8 @@ public class NamingProxy {
params.put(CommonParams.SERVICE_NAME, service.getName());
params.put(CommonParams.GROUP_NAME, service.getGroupName());
params.put("protectThreshold", String.valueOf(service.getProtectThreshold()));
params.put("metadata", JSON.toJSONString(service.getMetadata()));
params.put("selector", JSON.toJSONString(selector));
params.put("metadata", JacksonUtils.toJson(service.getMetadata()));
params.put("selector", JacksonUtils.toJson(selector));
reqAPI(UtilAndComs.NACOS_URL_SERVICE, params, HttpMethod.POST);
@ -301,8 +301,8 @@ public class NamingProxy {
params.put(CommonParams.SERVICE_NAME, service.getName());
params.put(CommonParams.GROUP_NAME, service.getGroupName());
params.put("protectThreshold", String.valueOf(service.getProtectThreshold()));
params.put("metadata", JSON.toJSONString(service.getMetadata()));
params.put("selector", JSON.toJSONString(selector));
params.put("metadata", JacksonUtils.toJson(service.getMetadata()));
params.put("selector", JacksonUtils.toJson(selector));
reqAPI(UtilAndComs.NACOS_URL_SERVICE, params, HttpMethod.PUT);
}
@ -321,7 +321,7 @@ public class NamingProxy {
return reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/list", params, HttpMethod.GET);
}
public JSONObject sendBeat(BeatInfo beatInfo, boolean lightBeatEnabled) throws NacosException {
public JsonNode sendBeat(BeatInfo beatInfo, boolean lightBeatEnabled) throws NacosException {
if (NAMING_LOGGER.isDebugEnabled()) {
NAMING_LOGGER.debug("[BEAT] {} sending beat to server: {}", namespaceId, beatInfo.toString());
@ -330,7 +330,7 @@ public class NamingProxy {
String body = StringUtils.EMPTY;
if (!lightBeatEnabled) {
try {
body = "beat=" + URLEncoder.encode(JSON.toJSONString(beatInfo), "UTF-8");
body = "beat=" + URLEncoder.encode(JacksonUtils.toJson(beatInfo), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new NacosException(NacosException.SERVER_ERROR, "encode beatInfo error", e);
}
@ -341,7 +341,7 @@ public class NamingProxy {
params.put("ip", beatInfo.getIp());
params.put("port", String.valueOf(beatInfo.getPort()));
String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/beat", params, body, HttpMethod.PUT);
return JSON.parseObject(result);
return JacksonUtils.toObj(result);
}
public boolean serverHealthy() {
@ -349,8 +349,8 @@ public class NamingProxy {
try {
String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/operator/metrics",
new HashMap<String, String>(2), HttpMethod.GET);
JSONObject json = JSON.parseObject(result);
String serverStatus = json.getString("status");
JsonNode json = JacksonUtils.toObj(result);
String serverStatus = json.get("status").asText();
return "UP".equals(serverStatus);
} catch (Exception e) {
return false;
@ -375,7 +375,7 @@ public class NamingProxy {
break;
case label:
ExpressionSelector expressionSelector = (ExpressionSelector) selector;
params.put("selector", JSON.toJSONString(expressionSelector));
params.put("selector", JacksonUtils.toJson(expressionSelector));
break;
default:
break;
@ -384,11 +384,10 @@ public class NamingProxy {
String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/service/list", params, HttpMethod.GET);
JSONObject json = JSON.parseObject(result);
ListView<String> listView = new ListView<String>();
listView.setCount(json.getInteger("count"));
listView.setData(JSON.parseObject(json.getString("doms"), new TypeReference<List<String>>() {
}));
JsonNode json = JacksonUtils.toObj(result);
ListView<String> listView = new ListView<>();
listView.setCount(json.get("count").asInt());
listView.setData(JacksonUtils.toObj(json.get("doms").asText(), new TypeReference<List<String>>() {}));
return listView;
}

View File

@ -15,13 +15,13 @@
*/
package com.alibaba.nacos.client.security;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.naming.net.HttpClient;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@ -122,14 +122,14 @@ public class SecurityProxy {
params, body, Charsets.UTF_8.name(), HttpMethod.POST);
if (result.code != HttpURLConnection.HTTP_OK) {
SECURITY_LOGGER.error("login failed: {}", JSON.toJSONString(result));
SECURITY_LOGGER.error("login failed: {}", JacksonUtils.toJson(result));
return false;
}
JSONObject obj = JSON.parseObject(result.content);
if (obj.containsKey(Constants.ACCESS_TOKEN)) {
accessToken = obj.getString(Constants.ACCESS_TOKEN);
tokenTtl = obj.getIntValue(Constants.TOKEN_TTL);
JsonNode obj = JacksonUtils.toObj(result.content);
if (obj.has(Constants.ACCESS_TOKEN)) {
accessToken = obj.get(Constants.ACCESS_TOKEN).asText();
tokenTtl = obj.get(Constants.TOKEN_TTL).asInt();
tokenRefreshWindow = tokenTtl / 10;
}
}

View File

@ -0,0 +1,95 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.cache;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
public class DiskCacheTest {
private static final String CACHE_DIR = DiskCacheTest.class.getResource("/").getPath() + "cache/";
private ServiceInfo serviceInfo;
private Instance instance;
@Before
public void setUp() throws Exception {
System.out.println(CACHE_DIR);
serviceInfo = new ServiceInfo("testName", "testClusters");
instance = new Instance();
instance.setClusterName("testClusters");
instance.setIp("1.1.1.1");
instance.setPort(1234);
instance.setServiceName("testName");
serviceInfo.setHosts(Collections.singletonList(instance));
}
@After
public void tearDown() {
File file = new File(CACHE_DIR);
if (file.exists() && file.list().length > 0) {
for (File each : file.listFiles()) {
each.delete();
}
}
}
@Test
public void testCache() {
DiskCache.write(serviceInfo, CACHE_DIR);
Map<String, ServiceInfo> actual = DiskCache.read(CACHE_DIR);
assertEquals(1, actual.size());
assertTrue(actual.containsKey(serviceInfo.getKeyEncoded()));
assertServiceInfo(actual.get(serviceInfo.getKeyEncoded()), serviceInfo);
}
private void assertServiceInfo(ServiceInfo actual, ServiceInfo expected) {
assertEquals(actual.getName(), expected.getName());
assertEquals(actual.getGroupName(), expected.getGroupName());
assertEquals(actual.getClusters(), expected.getClusters());
assertEquals(actual.getCacheMillis(), expected.getCacheMillis());
assertEquals(actual.getLastRefTime(), expected.getLastRefTime());
assertEquals(actual.getKey(), expected.getKey());
assertHosts(actual.getHosts(), expected.getHosts());
}
private void assertHosts(List<Instance> actual, List<Instance> expected) {
assertEquals(actual.size(), expected.size());
for (int i = 0; i < expected.size(); i++) {
assertInstance(actual.get(i), expected.get(i));
}
}
private void assertInstance(Instance actual, Instance expected) {
assertEquals(actual.getServiceName(), actual.getServiceName());
assertEquals(actual.getClusterName(), actual.getClusterName());
assertEquals(actual.getIp(), actual.getIp());
assertEquals(actual.getPort(), actual.getPort());
}
}

View File

@ -0,0 +1,108 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.core;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.naming.net.NamingProxy;
@RunWith(MockitoJUnitRunner.class)
public class HostReactorTest {
private static final String CACHE_DIR = HostReactorTest.class.getResource("/").getPath() + "cache/";
@Mock
private NamingProxy namingProxy;
@Mock
private EventDispatcher eventDispatcher;
private HostReactor hostReactor;
@Before
public void setUp() throws Exception {
hostReactor = new HostReactor(eventDispatcher, namingProxy, CACHE_DIR);
}
@Test
public void testProcessServiceJSON() {
ServiceInfo actual = hostReactor.processServiceJSON(EXAMPLE);
assertServiceInfo(actual);
}
@Test
public void testGetServiceInfoDirectlyFromServer() throws NacosException {
when(namingProxy.queryList("testName", "testClusters", 0, false)).thenReturn(EXAMPLE);
ServiceInfo actual = hostReactor.getServiceInfoDirectlyFromServer("testName", "testClusters");
assertServiceInfo(actual);
}
private void assertServiceInfo(ServiceInfo actual) {
assertEquals("testName", actual.getName());
assertEquals("testClusters", actual.getClusters());
assertEquals("", actual.getChecksum());
assertEquals(1000, actual.getCacheMillis());
assertEquals(0, actual.getLastRefTime());
assertNull(actual.getGroupName());
assertTrue(actual.isValid());
assertFalse(actual.isAllIPs());
assertEquals(1, actual.getHosts().size());
assertInstance(actual.getHosts().get(0));
}
private void assertInstance(Instance actual) {
assertEquals("1.1.1.1", actual.getIp());
assertEquals("testClusters", actual.getClusterName());
assertEquals("testName", actual.getServiceName());
assertEquals(1234, actual.getPort());
}
private static final String EXAMPLE = "{\n"
+ "\t\"name\": \"testName\",\n"
+ "\t\"clusters\": \"testClusters\",\n"
+ "\t\"cacheMillis\": 1000,\n"
+ "\t\"hosts\": [{\n"
+ "\t\t\"ip\": \"1.1.1.1\",\n"
+ "\t\t\"port\": 1234,\n"
+ "\t\t\"weight\": 1.0,\n"
+ "\t\t\"healthy\": true,\n"
+ "\t\t\"enabled\": true,\n"
+ "\t\t\"ephemeral\": true,\n"
+ "\t\t\"clusterName\": \"testClusters\",\n"
+ "\t\t\"serviceName\": \"testName\",\n"
+ "\t\t\"metadata\": {},\n"
+ "\t\t\"instanceHeartBeatInterval\": 5000,\n"
+ "\t\t\"instanceHeartBeatTimeOut\": 15000,\n"
+ "\t\t\"ipDeleteTimeout\": 30000,\n"
+ "\t\t\"instanceIdGenerator\": \"simple\"\n"
+ "\t}],\n"
+ "\t\"lastRefTime\": 0,\n"
+ "\t\"checksum\": \"\",\n"
+ "\t\"allIPs\": false,\n"
+ "\t\"valid\": true\n"
+ "}";
}

View File

@ -0,0 +1,44 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.security;
import org.junit.Test;
import static org.junit.Assert.*;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.fasterxml.jackson.databind.JsonNode;
public class SecurityProxyTest {
/**
* Just test for replace fastjson with jackson.
*
*/
@Test
public void testLogin() {
String example = "{\"accessToken\":\"ttttttttttttttttt\",\"tokenTtl\":1000}";
JsonNode obj = JacksonUtils.toObj(example);
if (obj.has(Constants.ACCESS_TOKEN)) {
if (obj.has(Constants.ACCESS_TOKEN)) {
assertEquals("ttttttttttttttttt", obj.get(Constants.ACCESS_TOKEN).asText());
assertEquals(1000, obj.get(Constants.TOKEN_TTL).asInt());
}
}
}
}

View File

@ -16,10 +16,16 @@
package com.alibaba.nacos.common.utils;
import com.alibaba.nacos.api.exception.runtime.NacosDeserializationException;
import com.alibaba.nacos.api.exception.runtime.NacosSerializationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import java.io.IOException;
import java.lang.reflect.Type;
/**
@ -33,31 +39,71 @@ public final class JacksonUtils {
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
public static String toJson(Object obj) throws Exception {
return mapper.writeValueAsString(obj);
}
public static String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new NacosSerializationException(obj.getClass(), e);
}
}
public static byte[] toJsonBytes(Object obj) throws Exception {
return ByteUtils.toBytes(mapper.writeValueAsString(obj));
}
public static byte[] toJsonBytes(Object obj) {
try {
return ByteUtils.toBytes(mapper.writeValueAsString(obj));
} catch (JsonProcessingException e) {
throw new NacosSerializationException(obj.getClass(), e);
}
}
public static <T> T toObj(byte[] json, Class<T> cls) throws Exception {
return toObj(StringUtils.newString4UTF8(json), cls);
}
public static <T> T toObj(byte[] json, Class<T> cls) {
try {
return toObj(StringUtils.newString4UTF8(json), cls);
} catch (Exception e) {
throw new NacosDeserializationException(cls, e);
}
}
public static <T> T toObj(byte[] json, Type cls) throws Exception {
return toObj(StringUtils.newString4UTF8(json), cls);
}
public static <T> T toObj(byte[] json, Type cls) {
try {
return toObj(StringUtils.newString4UTF8(json), cls);
} catch (Exception e) {
throw new NacosDeserializationException(e);
}
}
public static <T> T toObj(String json, Class<T> cls) throws Exception {
return mapper.readValue(json, cls);
}
public static <T> T toObj(String json, TypeReference<T> typeReference) {
try {
return mapper.readValue(json, typeReference);
} catch (IOException e) {
throw new NacosDeserializationException(typeReference.getClass(), e);
}
}
public static <T> T toObj(String json, Type type) throws Exception {
return mapper.readValue(json, mapper.constructType(type));
}
public static <T> T toObj(String json, Class<T> cls) {
try {
return mapper.readValue(json, cls);
} catch (IOException e) {
throw new NacosDeserializationException(cls, e);
}
}
public static void registerSubtype(Class<?> clz, String type) {
public static <T> T toObj(String json, Type type) {
try {
return mapper.readValue(json, mapper.constructType(type));
} catch (IOException e) {
throw new NacosDeserializationException(e);
}
}
public static JsonNode toObj(String json) {
try {
return mapper.readTree(json);
} catch (IOException e) {
throw new NacosDeserializationException(e);
}
}
public static void registerSubtype(Class<?> clz, String type) {
mapper.registerSubtypes(new NamedType(clz, type));
}
}

View File

@ -177,11 +177,7 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
}
public String toJSON() {
try {
return JacksonUtils.toJson(this);
} catch (Exception e) {
throw new RuntimeException("Instance toJSON failed", e);
}
return JacksonUtils.toJson(this);
}