Skip to content

Commit

Permalink
issue #451: modularize json serialization logic (#483)
Browse files Browse the repository at this point in the history
  • Loading branch information
saintping authored Mar 5, 2020
2 parents 00c5210 + 58695ae commit 53ec688
Show file tree
Hide file tree
Showing 45 changed files with 288 additions and 1,229 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,23 @@ public static ObjectMapper getObjectMapper() {
return OBJECT_MAPPER;
}

public static Map<String, String> json2Map(String json) {
if (StringUtils.isBlank(json)) {
return null;
}
public static Map<String, String> json2Map(String json) throws BrokerException {
try {
MapLikeType mapLikeType = OBJECT_MAPPER.getTypeFactory().constructMapLikeType(Map.class, String.class, String.class);
return OBJECT_MAPPER.readValue(json, mapLikeType);
} catch (Exception e) {
log.error("parse extensions failed");
return null;
throw new BrokerException(ErrorCode.JSON_ENCODE_EXCEPTION);
}
}

public static Map<String, Object> object2Map(String json) throws BrokerException {
try {
MapLikeType mapLikeType = OBJECT_MAPPER.getTypeFactory().constructMapLikeType(Map.class, String.class, Object.class);
return OBJECT_MAPPER.readValue(json, mapLikeType);
} catch (Exception e) {
log.error("parse extensions failed");
throw new BrokerException(ErrorCode.JSON_ENCODE_EXCEPTION);
}
}

Expand Down Expand Up @@ -154,4 +161,16 @@ public static <T> List<T> object2List(Object obj, Class<T> valueType) {
return OBJECT_MAPPER.convertValue(obj, new TypeReference<T>() {
});
}

public static boolean isValid(String jsonString) {
if (StringUtils.isBlank(jsonString)) {
return false;
}
try {
OBJECT_MAPPER.readTree(jsonString);
return true;
} catch (IOException e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ public static CompletableFuture<TransactionInfo> executeTransactionAsync(HFClien
return completableFuture;
}

public static List<WeEvent> getBlockChainInfo(Channel channel, Long blockNumber) throws ProposalException, InvalidArgumentException {
public static List<WeEvent> getBlockChainInfo(Channel channel, Long blockNumber) throws ProposalException, InvalidArgumentException, BrokerException {
List<WeEvent> weEventList = new ArrayList<>();
BlockInfo returnedBlock = channel.queryBlockByNumber(blockNumber);
for (BlockInfo.EnvelopeInfo envelopeInfo : returnedBlock.getEnvelopeInfos()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public static boolean flushData(Web3j web3j, Credentials credentials, Map<Long,
return true;
}

public static WeEvent decodeWeEvent(TransactionReceipt receipt, int version, Map<String, Contract> historyTopic) {
public static WeEvent decodeWeEvent(TransactionReceipt receipt, int version, Map<String, Contract> historyTopic) throws BrokerException {
// support version list
switch (version) {
case 10:
Expand Down
1 change: 1 addition & 0 deletions weevent-governance/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ dependencyManagement {
}

dependencies {
implementation project(path: ":weevent-client")
// spring boot
implementation("org.springframework.boot:spring-boot-starter")
implementation("org.springframework.boot:spring-boot-starter-web")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

import com.webank.weevent.governance.common.ConstantCode;
import com.webank.weevent.governance.entity.BaseResponse;
import com.webank.weevent.governance.utils.JsonUtil;
import com.webank.weevent.client.BrokerException;
import com.webank.weevent.client.JsonHelper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
Expand All @@ -26,7 +27,11 @@ public void handle(HttpServletRequest request, HttpServletResponse response,
BaseResponse baseResponse = new BaseResponse(ConstantCode.ACCESS_DENIED);

response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JsonUtil.toJSONString(baseResponse));
try {
response.getWriter().write(JsonHelper.object2Json(baseResponse));
} catch (BrokerException e) {
log.error("Code: " + e.getCode() + ", " + e.getMessage());
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

import com.webank.weevent.governance.common.ConstantCode;
import com.webank.weevent.governance.entity.BaseResponse;
import com.webank.weevent.governance.utils.JsonUtil;
import com.webank.weevent.client.BrokerException;
import com.webank.weevent.client.JsonHelper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
Expand All @@ -26,7 +27,11 @@ public void commence(HttpServletRequest request, HttpServletResponse response,
BaseResponse baseResponse = new BaseResponse(ConstantCode.USER_NOT_LOGGED_IN);

response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JsonUtil.toJSONString(baseResponse));
try {
response.getWriter().write(JsonHelper.object2Json(baseResponse));
} catch (BrokerException e) {
log.error("Code: " + e.getCode() + ", " + e.getMessage());
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@

import com.webank.weevent.governance.common.ConstantCode;
import com.webank.weevent.governance.entity.BaseResponse;
import com.webank.weevent.governance.utils.JsonUtil;
import com.webank.weevent.governance.utils.JwtUtils;
import com.webank.weevent.client.BrokerException;
import com.webank.weevent.client.JsonHelper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
Expand All @@ -32,7 +33,11 @@ public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse resp
BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS);

response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JsonUtil.toJSONString(baseResponse));
try {
response.getWriter().write(JsonHelper.object2Json(baseResponse));
} catch (BrokerException e) {
log.error("Code: " + e.getCode() + ", " + e.getMessage());
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@

import com.webank.weevent.governance.common.ConstantCode;
import com.webank.weevent.governance.entity.BaseResponse;
import com.webank.weevent.governance.utils.JsonUtil;
import com.webank.weevent.client.BrokerException;
import com.webank.weevent.client.JsonHelper;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
Expand All @@ -21,12 +21,16 @@ public class LoginFailHandler implements AuthenticationFailureHandler {

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException ex) throws JsonProcessingException, IOException {
AuthenticationException ex) throws IOException {
log.info("login fail", ex);
BaseResponse baseResponse = new BaseResponse(ConstantCode.LOGIN_FAIL);
baseResponse.setMessage(ex.getMessage());
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JsonUtil.toJSONString(baseResponse));
try {
response.getWriter().write(JsonHelper.object2Json(baseResponse));
} catch (BrokerException e) {
log.error("Code: " + e.getCode() + ", " + e.getMessage());
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
import com.webank.weevent.governance.entity.AccountEntity;
import com.webank.weevent.governance.entity.BaseResponse;
import com.webank.weevent.governance.service.AccountService;
import com.webank.weevent.governance.utils.JsonUtil;
import com.webank.weevent.governance.utils.JwtUtils;
import com.webank.weevent.client.BrokerException;
import com.webank.weevent.client.JsonHelper;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
Expand Down Expand Up @@ -45,10 +45,14 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
rsp.put("username", accountEntity.getUsername());
//return
BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS);
baseResponse.setData(JsonUtil.toJSONString(rsp));
baseResponse.setMessage("success");
log.debug("login backInfo:{}", JsonUtil.toJSONString(baseResponse));
response.getWriter().write(JsonUtil.toJSONString(baseResponse));
try {
baseResponse.setData(JsonHelper.object2Json(rsp));
baseResponse.setMessage("success");
log.debug("login backInfo:{}", JsonHelper.object2Json(baseResponse));
response.getWriter().write(JsonHelper.object2Json(baseResponse));
} catch (BrokerException e) {
log.error("Code: " + e.getCode() + ", " + e.getMessage());
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import com.webank.weevent.governance.repository.RuleEngineRepository;
import com.webank.weevent.governance.repository.TopicHistoricalRepository;
import com.webank.weevent.governance.repository.TopicRepository;
import com.webank.weevent.governance.utils.JsonUtil;
import com.webank.weevent.client.JsonHelper;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
Expand Down Expand Up @@ -291,7 +291,7 @@ private void checkUrl(String url, String afterUrl, HttpServletRequest request) t
try {
CloseableHttpResponse response = client.execute(get);
String responseResult = EntityUtils.toString(response.getEntity());
jsonObject = JsonUtil.parseObject(responseResult, Map.class);
jsonObject = JsonHelper.json2Object(responseResult, Map.class);
} catch (Exception e) {
log.error("url {}, connect fail,error:{}", headUrl, e.getMessage());
throw new GovernanceException("url:{}" + headUrl + " connect fail", e);
Expand All @@ -308,7 +308,7 @@ public String getVersion(HttpServletRequest request, String brokerUrl) throws Go
try {
CloseableHttpResponse versionResponse = commonService.getCloseResponse(request, versionUrl);
String mes = EntityUtils.toString(versionResponse.getEntity());
Map map = JsonUtil.parseObject(mes, Map.class);
Map map = JsonHelper.json2Object(mes, Map.class);
return map.get("weEventVersion") == null ? null : map.get("weEventVersion").toString();
} catch (Exception e) {
log.error("get version fail,error:", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
import com.webank.weevent.governance.repository.RuleDatabaseRepository;
import com.webank.weevent.governance.repository.RuleEngineRepository;
import com.webank.weevent.governance.utils.DAGDetectUtil;
import com.webank.weevent.governance.utils.JsonUtil;
import com.webank.weevent.governance.utils.Utils;
import com.webank.weevent.client.JsonHelper;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
Expand Down Expand Up @@ -89,7 +89,7 @@ public List<RuleEngineEntity> getRuleEngines(HttpServletRequest request, RuleEng
for (RuleEngineEntity it : ruleEngineEntities) {
it.setCreateDateStr(simpleDateFormat.format(it.getCreateDate()));
String payload = it.getPayload();
it.setPayloadMap(payload == null ? new HashMap<>() : JsonUtil.parseObject(payload, Map.class));
it.setPayloadMap(payload == null ? new HashMap<>() : JsonHelper.json2Object(payload, Map.class));
}
}
return ruleEngineEntities;
Expand All @@ -107,7 +107,7 @@ public RuleEngineEntity addRuleEngine(RuleEngineEntity ruleEngineEntity, HttpSer
try {
ruleEngineEntity.setSystemTag(false);
ruleEngineEntity.setStatus(ConstantProperties.NOT_STARTED);
String payload = JsonUtil.toJSONString(ruleEngineEntity.getPayloadMap());
String payload = JsonHelper.object2Json(ruleEngineEntity.getPayloadMap());
ruleEngineEntity.setPayload(payload);
if (ruleEngineEntity.getPayloadType() == null || ruleEngineEntity.getPayloadType() == 0) {
ruleEngineEntity.setPayloadType(ConstantProperties.JSON);
Expand Down Expand Up @@ -169,7 +169,7 @@ public void deleteProcessRule(HttpServletRequest request, RuleEngineEntity engin
throw new GovernanceException(ErrorCode.PROCESS_CONNECT_ERROR);
}

Map jsonObject = JsonUtil.parseObject(mes, Map.class);
Map jsonObject = JsonHelper.json2Object(mes, Map.class);
Integer code = Integer.valueOf(jsonObject.get("errorCode").toString());
if (PROCESSOR_SUCCESS_CODE != code) {
String msg = jsonObject.get("errorMsg").toString();
Expand All @@ -189,7 +189,7 @@ public boolean updateRuleEngine(RuleEngineEntity ruleEngineEntity, HttpServletRe
//check rule
this.checkRule(ruleEngineEntity);
//set payload
String payload = JsonUtil.toJSONString(ruleEngineEntity.getPayloadMap());
String payload = JsonHelper.object2Json(ruleEngineEntity.getPayloadMap());
ruleEngineEntity.setPayload(payload);
ruleEngineEntity.setLastUpdate(new Date());
// check sql condition
Expand Down Expand Up @@ -256,21 +256,21 @@ private void updateProcessRule(HttpServletRequest request, RuleEngineEntity rule
return;
}
String url = new StringBuffer(this.getProcessorUrl()).append(ConstantProperties.PROCESSOR_UPDATE_CEP_RULE).toString();
String jsonString = JsonUtil.toJSONString(ruleEngineEntity);
Map map = JsonUtil.parseObject(jsonString, Map.class);
String jsonString = JsonHelper.object2Json(ruleEngineEntity);
Map map = JsonHelper.json2Object(jsonString, Map.class);
map.put("updatedTime", ruleEngineEntity.getLastUpdate());
map.put("createdTime", oldRule.getCreateDate());
//updateCEPRuleById
log.info("update rule begin====map:{}", JsonUtil.toJSONString(map));
CloseableHttpResponse closeResponse = commonService.getCloseResponse(request, url, JsonUtil.toJSONString(map));
log.info("update rule begin====map:{}", JsonHelper.object2Json(map));
CloseableHttpResponse closeResponse = commonService.getCloseResponse(request, url, JsonHelper.object2Json(map));
String updateMes = EntityUtils.toString(closeResponse.getEntity());
log.info("update rule end====result:{}", updateMes);
//deal processor result
int statusCode = closeResponse.getStatusLine().getStatusCode();
if (200 != statusCode) {
throw new GovernanceException(ErrorCode.PROCESS_CONNECT_ERROR);
}
Map jsonObject = JsonUtil.parseObject(updateMes, Map.class);
Map jsonObject = JsonHelper.json2Object(updateMes, Map.class);
Integer code = Integer.valueOf(jsonObject.get("errorCode").toString());
if (PROCESSOR_SUCCESS_CODE != code) {
String msg = jsonObject.get("errorMsg").toString();
Expand Down Expand Up @@ -317,13 +317,13 @@ private void stopProcessRule(HttpServletRequest request, RuleEngineEntity ruleEn
BrokerEntity broker = brokerService.getBroker(oldRule.getBrokerId());
ruleEngineEntity.setBrokerUrl(broker.getBrokerUrl());
String url = new StringBuffer(this.getProcessorUrl()).append(ConstantProperties.PROCESSOR_STOP_CEP_RULE).toString();
String jsonString = JsonUtil.toJSONString(ruleEngineEntity);
Map map = JsonUtil.parseObject(jsonString, Map.class);
String jsonString = JsonHelper.object2Json(ruleEngineEntity);
Map map = JsonHelper.json2Object(jsonString, Map.class);
map.put("updatedTime", ruleEngineEntity.getLastUpdate());
map.put("createdTime", oldRule.getCreateDate());
//updateCEPRuleById
log.info("stop rule begin====map:{}", JsonUtil.toJSONString(map));
CloseableHttpResponse closeResponse = commonService.getCloseResponse(request, url, JsonUtil.toJSONString(map));
log.info("stop rule begin====map:{}", JsonHelper.object2Json(map));
CloseableHttpResponse closeResponse = commonService.getCloseResponse(request, url, JsonHelper.object2Json(map));
String stopMsg = EntityUtils.toString(closeResponse.getEntity());
log.info("stop rule end====result:{}", stopMsg);
//deal processor result
Expand All @@ -332,7 +332,7 @@ private void stopProcessRule(HttpServletRequest request, RuleEngineEntity ruleEn
throw new GovernanceException(ErrorCode.PROCESS_CONNECT_ERROR);
}

Map jsonObject = JsonUtil.parseObject(stopMsg, Map.class);
Map jsonObject = JsonHelper.json2Object(stopMsg, Map.class);
Integer code = Integer.valueOf(jsonObject.get("errorCode").toString());
if (PROCESSOR_SUCCESS_CODE != code) {
String msg = jsonObject.get("errorMsg").toString();
Expand Down Expand Up @@ -388,14 +388,14 @@ private void startProcessRule(HttpServletRequest request, RuleEngineEntity rule)
if (!this.checkProcessorExist(request)) {
return;
}
String jsonString = JsonUtil.toJSONString(rule);
Map map = JsonUtil.parseObject(jsonString, Map.class);
String jsonString = JsonHelper.object2Json(rule);
Map map = JsonHelper.json2Object(jsonString, Map.class);
map.put("updatedTime", rule.getLastUpdate());
map.put("createdTime", rule.getCreateDate());
String url = new StringBuffer(this.getProcessorUrl()).append(ConstantProperties.PROCESSOR_START_CEP_RULE).toString();
map.put("systemTag", rule.getSystemTag() ? "1" : "0");
log.info("start rule begin====map:{}", JsonUtil.toJSONString(map));
CloseableHttpResponse closeResponse = commonService.getCloseResponse(request, url, JsonUtil.toJSONString(map));
log.info("start rule begin====map:{}", JsonHelper.object2Json(map));
CloseableHttpResponse closeResponse = commonService.getCloseResponse(request, url, JsonHelper.object2Json(map));
//deal processor result
String mes = EntityUtils.toString(closeResponse.getEntity());
log.info("start rule end====result:{}", mes);
Expand All @@ -405,7 +405,7 @@ private void startProcessRule(HttpServletRequest request, RuleEngineEntity rule)
throw new GovernanceException(ErrorCode.PROCESS_CONNECT_ERROR);
}

Map jsonObject = JsonUtil.parseObject(mes, Map.class);
Map jsonObject = JsonHelper.json2Object(mes, Map.class);
Integer code = Integer.valueOf(jsonObject.get("errorCode").toString());
String msg = jsonObject.get("errorMsg").toString();
if (PROCESSOR_SUCCESS_CODE != code) {
Expand Down Expand Up @@ -468,7 +468,7 @@ public RuleEngineEntity getRuleEngineDetail(RuleEngineEntity ruleEngineEntity, H
}
try {
String payload = engineEntity.getPayload();
engineEntity.setPayloadMap(payload == null ? new HashMap<>() : JsonUtil.parseObject(payload, Map.class));
engineEntity.setPayloadMap(payload == null ? new HashMap<>() : JsonHelper.json2Object(payload, Map.class));
//get ruleEngineConditionList
String fullSql = parsingDetailSQL(engineEntity);
engineEntity.setFullSQL(fullSql);
Expand Down Expand Up @@ -560,7 +560,7 @@ public boolean validationConditions(HttpServletRequest request, RuleEngineEntity
throw new GovernanceException(ErrorCode.PROCESS_CONNECT_ERROR);
}
String msg = EntityUtils.toString(closeResponse.getEntity());
Map jsonObject = JsonUtil.parseObject(msg, Map.class);
Map jsonObject = JsonHelper.json2Object(msg, Map.class);
Integer code = Integer.valueOf(jsonObject.get("errorCode").toString());
if (PROCESSOR_SUCCESS_CODE != code) {
throw new GovernanceException(msg);
Expand Down
Loading

0 comments on commit 53ec688

Please sign in to comment.