Skip to content

Commit

Permalink
Merge pull request #2904 from KomachiSion/develop-issue#2842
Browse files Browse the repository at this point in the history
[ISSUE #2842] Replace Fastjson with Jackson except nacos-test module
  • Loading branch information
yanlinly committed May 27, 2020
2 parents a07b0c5 + 0b1a58e commit cb1ef7e
Show file tree
Hide file tree
Showing 51 changed files with 767 additions and 523 deletions.
4 changes: 0 additions & 4 deletions api/pom.xml
Expand Up @@ -44,10 +44,6 @@
</properties>

<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
Expand Down
Expand Up @@ -387,7 +387,7 @@ public ListView<String> getServiceList(int pageNo, int pageSize, String groupNam
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>>() {}));
listView.setData(JacksonUtils.toObj(json.get("doms").toString(), new TypeReference<List<String>>() {}));

return listView;
}
Expand Down
Expand Up @@ -15,7 +15,6 @@
*/
package com.alibaba.nacos.cmdb.memory;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.cmdb.spi.CmdbService;
import com.alibaba.nacos.api.cmdb.pojo.Entity;
import com.alibaba.nacos.api.cmdb.pojo.EntityEvent;
Expand All @@ -26,6 +25,8 @@
import com.alibaba.nacos.cmdb.service.CmdbWriter;
import com.alibaba.nacos.cmdb.utils.Loggers;
import com.alibaba.nacos.cmdb.utils.UtilsAndCommons;
import com.alibaba.nacos.common.utils.JacksonUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

Expand Down Expand Up @@ -166,7 +167,7 @@ public void run() {
}

if (Loggers.MAIN.isDebugEnabled()) {
Loggers.MAIN.debug("LABEL-TASK {}", "got label map:" + JSON.toJSONString(tmpLabelMap));
Loggers.MAIN.debug("LABEL-TASK {}", "got label map:" + JacksonUtils.toJson(tmpLabelMap));
}

labelMap = tmpLabelMap;
Expand Down Expand Up @@ -219,7 +220,7 @@ public void run() {
eventTimestamp = current;

if (Loggers.MAIN.isDebugEnabled()) {
Loggers.MAIN.debug("EVENT-TASK {}", "got events size:" + ", events:" + JSON.toJSONString(events));
Loggers.MAIN.debug("EVENT-TASK {}", "got events size:" + ", events:" + JacksonUtils.toJson(events));
}

if (events != null && !events.isEmpty()) {
Expand Down
Expand Up @@ -18,12 +18,15 @@

import com.alibaba.nacos.api.exception.runtime.NacosDeserializationException;
import com.alibaba.nacos.api.exception.runtime.NacosSerializationException;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
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 com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.lang.reflect.Type;
Expand All @@ -37,6 +40,7 @@ public final class JacksonUtils {

static {
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(Include.NON_NULL);
}

public static String toJson(Object obj) {
Expand Down Expand Up @@ -71,11 +75,11 @@ public static <T> T toObj(byte[] json, Type cls) {
}
}

public static <T> T toObj(String json, TypeReference<T> typeReference) {
public static <T> T toObj(byte[] json, TypeReference<T> typeReference) {
try {
return mapper.readValue(json, typeReference);
} catch (IOException e) {
throw new NacosDeserializationException(typeReference.getClass(), e);
return toObj(StringUtils.newString4UTF8(json), typeReference);
} catch (Exception e) {
throw new NacosDeserializationException(e);
}
}

Expand All @@ -95,6 +99,14 @@ public static <T> T toObj(String json, Type type) {
}
}

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 JsonNode toObj(String json) {
try {
return mapper.readTree(json);
Expand All @@ -106,4 +118,16 @@ public static JsonNode toObj(String json) {
public static void registerSubtype(Class<?> clz, String type) {
mapper.registerSubtypes(new NamedType(clz, type));
}

public static ObjectNode createEmptyJsonNode() {
return new ObjectNode(mapper.getNodeFactory());
}

public static ArrayNode createEmptyArrayNode() {
return new ArrayNode(mapper.getNodeFactory());
}

public static JsonNode transferToJsonNode(Object obj) {
return mapper.valueToTree(obj);
}
}
Expand Up @@ -15,9 +15,9 @@
*/
package com.alibaba.nacos.console.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.config.server.auth.RoleInfo;
import com.alibaba.nacos.config.server.model.User;
import com.alibaba.nacos.console.security.nacos.NacosAuthConfig;
Expand All @@ -28,6 +28,8 @@
import com.alibaba.nacos.console.utils.JwtTokenUtils;
import com.alibaba.nacos.console.utils.PasswordEncoderUtil;
import com.alibaba.nacos.core.auth.*;
import com.fasterxml.jackson.databind.node.ObjectNode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
Expand Down Expand Up @@ -172,7 +174,8 @@ public Object login(@RequestParam String username, @RequestParam String password
response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER,
NacosAuthConfig.TOKEN_PREFIX + user.getToken());

JSONObject result = new JSONObject();
ObjectNode result = JacksonUtils.createEmptyJsonNode();
// JSONObject result = new JSONObject();
result.put(Constants.ACCESS_TOKEN, user.getToken());
result.put(Constants.TOKEN_TTL, authConfigs.getTokenValidityInSeconds());
result.put(Constants.GLOBAL_ADMIN, user.isGlobalAdmin());
Expand Down
Expand Up @@ -16,7 +16,6 @@

package com.alibaba.nacos.console.security.nacos.users;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.core.auth.User;

/**
Expand Down Expand Up @@ -47,6 +46,9 @@ public void setGlobalAdmin(boolean globalAdmin) {

@Override
public String toString() {
return JSON.toJSONString(this);
return "NacosUser{" +
"token='" + token + '\'' +
", globalAdmin=" + globalAdmin +
'}';
}
}
Expand Up @@ -15,9 +15,10 @@
*/
package com.alibaba.nacos.console.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.config.server.service.repository.PersistService;
import com.alibaba.nacos.naming.controllers.OperatorController;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
Expand Down Expand Up @@ -75,7 +76,7 @@ public void testReadiness() throws Exception {
String url = "/v1/console/health/readiness";

Mockito.when(persistService.configInfoCount(any(String.class))).thenReturn(0);
Mockito.when(apiCommands.metrics(any(HttpServletRequest.class))).thenReturn(new JSONObject());
Mockito.when(apiCommands.metrics(any(HttpServletRequest.class))).thenReturn(JacksonUtils.createEmptyJsonNode());
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(url);
Assert.assertEquals(200, mockmvc.perform(builder).andReturn().getResponse().getStatus());

Expand All @@ -92,7 +93,7 @@ public void testReadiness() throws Exception {
// Config is not in readiness
Mockito.when(persistService.configInfoCount(any(String.class))).thenThrow(
new RuntimeException("HealthControllerTest.testReadiness"));
Mockito.when(apiCommands.metrics(any(HttpServletRequest.class))).thenReturn(new JSONObject());
Mockito.when(apiCommands.metrics(any(HttpServletRequest.class))).thenReturn(JacksonUtils.createEmptyJsonNode());
response = mockmvc.perform(builder).andReturn().getResponse();
Assert.assertEquals(500, response.getStatus());
Assert.assertEquals("Config is not in readiness", response.getContentAsString());
Expand Down
@@ -0,0 +1,87 @@
/*
* 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.console.controller;

import com.alibaba.nacos.console.security.nacos.NacosAuthManager;
import com.alibaba.nacos.console.security.nacos.users.NacosUser;
import com.alibaba.nacos.core.auth.AccessException;
import com.alibaba.nacos.core.auth.AuthConfigs;
import com.alibaba.nacos.core.auth.AuthSystemTypes;
import com.fasterxml.jackson.databind.JsonNode;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class UserControllerTest {

@Mock
private HttpServletRequest request;

@Mock
private HttpServletResponse response;

@Mock
private AuthConfigs authConfigs;

@Mock
private NacosAuthManager authManager;

private UserController userController;

private NacosUser user;

@Before
public void setUp() throws Exception {
userController = new UserController();
user = new NacosUser();
user.setUserName("nacos");
user.setGlobalAdmin(true);
user.setToken("1234567890");
injectObject("authConfigs", authConfigs);
injectObject("authManager", authManager);
}

@Test
public void testLoginWithAuthedUser() throws AccessException {
when(authManager.login(request)).thenReturn(user);
when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name());
when(authConfigs.getTokenValidityInSeconds()).thenReturn(18000L);
Object actual = userController.login("nacos", "nacos", response, request);
assertThat(actual, instanceOf(JsonNode.class));
String actualString = actual.toString();
assertTrue(actualString.contains("\"accessToken\":\"1234567890\""));
assertTrue(actualString.contains("\"tokenTtl\":18000"));
assertTrue(actualString.contains("\"globalAdmin\":true"));
}

private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
Field field = UserController.class.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(userController, value);
}
}
Expand Up @@ -15,8 +15,6 @@
*/
package com.alibaba.nacos.core.auth;

import com.alibaba.fastjson.JSON;

import java.io.Serializable;

/**
Expand Down Expand Up @@ -66,6 +64,9 @@ public void setAction(String action) {

@Override
public String toString() {
return JSON.toJSONString(this);
return "Permission{" +
"resource='" + resource + '\'' +
", action='" + action + '\'' +
'}';
}
}
7 changes: 3 additions & 4 deletions core/src/main/java/com/alibaba/nacos/core/auth/Resource.java
Expand Up @@ -15,9 +15,6 @@
*/
package com.alibaba.nacos.core.auth;


import com.alibaba.fastjson.JSON;

import java.io.Serializable;

/**
Expand Down Expand Up @@ -51,6 +48,8 @@ public String parseName() {

@Override
public String toString() {
return JSON.toJSONString(this);
return "Resource{" +
"key='" + key + '\'' +
'}';
}
}
Expand Up @@ -16,8 +16,8 @@

package com.alibaba.nacos.core.distributed.raft;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.LoggerUtils;
import com.alibaba.nacos.consistency.LogProcessor;
import com.alibaba.nacos.consistency.cp.LogProcessor4CP;
Expand Down Expand Up @@ -305,7 +305,7 @@ public boolean onSnapshotLoad(SnapshotReader reader) {
fileMeta = new LocalFileMeta();
}
else {
fileMeta = JSON.parseObject(bytes, LocalFileMeta.class);
fileMeta = JacksonUtils.toObj(bytes, LocalFileMeta.class);
}

metaMap.put(fileName, fileMeta);
Expand Down
4 changes: 0 additions & 4 deletions naming/pom.xml
Expand Up @@ -52,10 +52,6 @@
<artifactId>nacos-api</artifactId>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>

<dependency>
<groupId>io.netty</groupId>
Expand Down

0 comments on commit cb1ef7e

Please sign in to comment.