From f0cc46c7aff656a6add1fd69208763faa67ee620 Mon Sep 17 00:00:00 2001 From: CaiHQ Date: Mon, 1 Nov 2021 18:52:02 +0800 Subject: [PATCH] feat: support requestID auto append in agent websocket --- .../org/bdware/server/action/CMActions.java | 248 +++++++----------- .../bdware/server/action/LedgerActions.java | 14 +- .../bdware/server/action/ManagerActions.java | 140 +++------- .../server/trustedmodel/MasterProxy.java | 13 +- .../ws/ContractManagerFrameHandler.java | 22 +- 5 files changed, 158 insertions(+), 279 deletions(-) diff --git a/src/main/java/org/bdware/server/action/CMActions.java b/src/main/java/org/bdware/server/action/CMActions.java index 7481798..927bc15 100644 --- a/src/main/java/org/bdware/server/action/CMActions.java +++ b/src/main/java/org/bdware/server/action/CMActions.java @@ -34,12 +34,11 @@ import java.util.*; public class CMActions implements OnHashCallback { private static final String PARAM_ACTION = "action"; - private static final String MISSING_ARGUMENT = + private static final JsonObject MISSING_ARGUMENT = JsonUtil.parseString("{\"action\":\"onExecuteResult\",\"executeTime\":-1," + + "\"status\":\"Error\",\"result\":\"missing arguments\"}"); + private static final JsonObject INVALID_DOI = JsonUtil.parseString( "{\"action\":\"onExecuteResult\",\"executeTime\":-1," - + "\"status\":\"Error\",\"result\":\"missing arguments\"}"; - private static final String INVALID_DOI = - "{\"action\":\"onExecuteResult\",\"executeTime\":-1," - + "\"status\":\"Error\",\"result\":\"invalid contract doi\"}"; + + "\"status\":\"Error\",\"result\":\"invalid contract doi\"}"); private static final Logger LOGGER = LogManager.getLogger(CMActions.class); public static ContractManager manager = initManager(); public static FuncInvokeInfo FUNCINVOKEINFO = new FuncInvokeInfo(); // 合约调用时参数和结果 @@ -95,11 +94,8 @@ public class CMActions implements OnHashCallback { public static void listContractProcessWithFirstWithOwner( String owner, String id, ResultCallback resultCallback) { LOGGER.debug("[CMActions listContractProcessWithFirstWithOwner] id=" + id); - - Result ret = new Result(); - ret.action = "onListContractProcess"; - ret.data = manager.listContractsWithOwner(owner, id, 1 << 1); - resultCallback.onResult(JsonUtil.toJson(ret)); + String data = manager.listContractsWithOwner(owner, id, 1 << 1); + ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data); } public static String file2Str(File file) { @@ -202,8 +198,7 @@ public class CMActions implements OnHashCallback { c, new ResultCallback() { @Override - public void onResult(String str) { - JsonObject ret = JsonParser.parseString(str).getAsJsonObject(); + public void onResult(JsonObject ret) { ret.addProperty("responseID", c.getRequestID()); ret.addProperty("action", "onExecuteResult"); String costTime = (System.currentTimeMillis() - start) + ""; @@ -218,9 +213,14 @@ public class CMActions implements OnHashCallback { c.getArg(), ret.has("result") ? ret.get("result").toString() : ""); } - System.out.println(str); + System.out.println(ret.toString()); resultCallback.onResult(ret.toString()); } + + @Override + public void onResult(String str) { + throw new IllegalStateException("Can't reach here"); + } }, hashcb); } @@ -385,16 +385,14 @@ public class CMActions implements OnHashCallback { @Action(async = true) public void ping(JsonObject args, ResultCallback resultCallback) { - resultCallback.onResult("{\"action\":\"pong\"}"); + ReplyUtil.simpleReply(resultCallback, "pong", null); } @Action(async = true) public void getMock(JsonObject args, final ResultCallback resultCallback) { - Result ret = new Result(); String contractID = ""; String operation = ""; - ret.action = "onGetMock"; - ret.responseID = args.get("requestID").getAsString(); + Object data = null; if (args.has("contractID")) { contractID = args.get("contractID").getAsString(); ProjectConfig config = manager.projectRecoder.getProjectConfig(contractID); @@ -405,21 +403,18 @@ public class CMActions implements OnHashCallback { System.out.println(operation); System.out.println("config" + config.getMockConfig().config.get(operation)); - ret.data = config.getMockConfig().config.get(operation); + data = config.getMockConfig().config.get(operation); } else { System.out.println("config" + config.getMockConfig()); - ret.data = config.getMockConfig(); + data = config.getMockConfig(); } } - - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onGetMock", data); } @Action(async = true) public void setMock(JsonObject args, final ResultCallback resultCallback) { - Result ret = new Result(); - ret.action = "onSetMock"; - if (args.has("requestID")) ret.responseID = args.get("requestID").getAsString(); + String data = "failed"; String contractID = ""; String operation = ""; //String mock = ""; @@ -434,26 +429,22 @@ public class CMActions implements OnHashCallback { config.setMock(operation, mock); manager.projectRecoder.updateValue(config); if (client == null) { - ret.data = "failed"; + data = "failed"; } else { manager.loadProjectConfig(client); - ret.data = "success"; + data = "success"; } - } else { - ret.data = "failed"; + data = "failed"; } - - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onSetMock", data); } @Action(async = true) public void getMask(JsonObject args, final ResultCallback resultCallback) { - Result ret = new Result(); String contractID = ""; String operation = ""; - ret.action = "onGetMask"; - ret.responseID = args.get("requestID").getAsString(); + Object data = null; if (args.has("contractID")) { contractID = args.get("contractID").getAsString(); ProjectConfig config = manager.projectRecoder.getProjectConfig(contractID); @@ -464,22 +455,18 @@ public class CMActions implements OnHashCallback { System.out.println(operation); System.out.println("config" + config.getMaskConfig().config.get(operation)); - ret.data = config.getMaskConfig().config.get(operation); + data = config.getMaskConfig().config.get(operation); } else { System.out.println("config" + config.getMaskConfig()); - ret.data = config.getMaskConfig(); + data = config.getMaskConfig(); } } - - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onGetMask", data); } @Action(async = true) public void setMask(JsonObject args, final ResultCallback resultCallback) { - - Result ret = new Result(); - ret.action = "onSetMask"; - if (args.has("requestID")) ret.responseID = args.get("requestID").getAsString(); + String data = "failed"; String contractID = ""; String operation = ""; //JsonElement mask = JsonParser.parseString(""); @@ -498,17 +485,14 @@ public class CMActions implements OnHashCallback { // client.contractMeta.contract.setMask(operation,mask); // client.setMask(operation,mask); // client.get.syncGet("","setMask",""); - if (client == null) { - ret.data = "failed"; - } else { + if (client != null) { manager.loadProjectConfig(client); - ret.data = "success"; + data = "success"; } // System.out.println("clientmask"+client.contractMeta.contract.Mask); } - System.out.println("setMask"); - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onSetMask", data); } // TODO we should support Anonymous contract execution? userPermission = 1 << 13 @@ -529,41 +513,28 @@ public class CMActions implements OnHashCallback { // 节点管理者 @Action(userPermission = 1L << 19) public void listAllContractProcess(JsonObject args, ResultCallback resultCallback) { - Result ret = new Result(); - ret.action = "onListContractProcess"; - ret.data = manager.listContracts(""); - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onListContractProcess", manager.listContracts("")); } // 合约使用者,合约管理者 @Action(userPermission = 1L << 19) public void listContractProcess(JsonObject args, ResultCallback resultCallback) { + String data; if (args.has("verifiedPubKey")) { - Result ret = new Result(); - ret.action = "onListContractProcess"; - ret.data = - manager.listContractsWithOwner( - args.get("verifiedPubKey").getAsString(), - null, - args.has("filters") ? args.get("filters").getAsInt() : 0); - resultCallback.onResult(JsonUtil.toJson(ret)); + data = manager.listContractsWithOwner( + args.get("verifiedPubKey").getAsString(), + null, + args.has("filters") ? args.get("filters").getAsInt() : 0); + ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data); } else { - Result ret = new Result(); - ret.action = "onListContractProcess"; - ret.data = "Failed: Illegal user"; - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onListContractProcess", "Failed: Illegal user"); } } @Action public void listTheContractProcess(JsonObject args, ResultCallback resultCallback) { - Result ret = new Result(); - ret.action = "onListTheContractProcess"; - ret.data = manager.listTheContracts(args.get("contractID").getAsString()); - if (args.has("requestID")) ret.responseID = args.get("requestID").getAsString(); - if (args.has("requestID")) ret.responseID = args.get("requestID").getAsString(); - - resultCallback.onResult(JsonUtil.toJson(ret)); + String data = manager.listTheContracts(args.get("contractID").getAsString()); + ReplyUtil.simpleReply(resultCallback, "onListTheContractProcess", data); } private void setMemInfo(Map lineInfo, Sigar sigar, int pid) { @@ -585,18 +556,12 @@ public class CMActions implements OnHashCallback { @Action(userPermission = 1L << 16) public void queryContractResourceInfo(JsonObject args, ResultCallback resultCallback) { - Result ret = new Result(); - ret.action = "onQueryContractResourceInfo"; - ret.data = manager.getContractResourceInfo(); - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onQueryContractResourceInfo", manager.getContractResourceInfo()); } @Action(userPermission = 1L << 16) public void queryFreeResourceInfo(JsonObject args, ResultCallback resultCallback) { - Result ret = new Result(); - ret.action = "onQueryFreeResourceInfo"; - ret.data = manager.getFreeResourceInfo(); - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onQueryFreeResourceInfo", manager.getFreeResourceInfo()); } // 查看本地合约日志详情 @@ -612,10 +577,9 @@ public class CMActions implements OnHashCallback { String sDate = df.format(date); data2.remove("date"); data2.addProperty("date", sDate); - resultCallback.onResult(data2.toString()); + resultCallback.onResult(data2); } else { - resultCallback.onResult( - "\"action\":\"onQueryContractLogDetail\",\"data\":\"Can't get detail by this key!\"}"); + ReplyUtil.simpleReply(resultCallback, "onQueryContractLogDetail", "Can't get detail by this key!"); } } @@ -637,19 +601,16 @@ public class CMActions implements OnHashCallback { } catch (IOException e) { e.printStackTrace(); } - Result ret = new Result(); - ret.action = "onWriteDyjs"; - ret.data = "success"; - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onWriteDyjs", "success"); } - @Action(userPermission = 1L << 17) // TODO:shujy + @Action(userPermission = 1L << 17) // TODO:shujunyi public void evaluates(JsonObject json, final ResultCallback resultCallback) { String contractName = json.get("contractName").getAsString(); String functionName = json.get("functionName").getAsString(); String args = json.get("args").getAsString(); String test = manager.getGasEvaluates(contractName, functionName, args); - ReplyUtil.simpleReply(resultCallback,"onEvaluates","success"); + ReplyUtil.simpleReply(resultCallback, "onEvaluates", "success"); } @Action(userPermission = 1L << 16) @@ -667,7 +628,6 @@ public class CMActions implements OnHashCallback { public void startContractBatched(JsonObject args, ResultCallback resultCallback) { Map ret = new HashMap<>(); ret.put("action", "onStartContract"); - JsonArray array = JsonParser.parseString(args.get("fileList").getAsString()).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { @@ -701,7 +661,7 @@ public class CMActions implements OnHashCallback { } } LOGGER.debug("startContractBatched ret = " + ret); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); ExecutionManager.instance.updateLocalContractToNodeCenter(); } @@ -798,10 +758,7 @@ public class CMActions implements OnHashCallback { ret.put("data", manager.startContractAndRedirect(c, System.out)); // createPS() ret.put("cid", c.getID()); ret.put("executeTime", System.currentTimeMillis() - start); - if (args.has("requestID")) { - ret.put("responseID", args.get("requestID").getAsString()); - } - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); LOGGER.info("handler is null " + (handler == null)); LOGGER.info(args.get("verifiedPubKey").getAsString()); if (handler != null) { @@ -923,11 +880,7 @@ public class CMActions implements OnHashCallback { ret.put("data", manager.startContractAndRedirect(c, System.out)); // createPS() ret.put("cid", c.getID()); ret.put("executeTime", System.currentTimeMillis() - start); - - if (args.has("requestID")) { - ret.put("responseID", args.get("requestID").getAsString()); - } - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); if (handler != null) { listContractProcessWithFirstWithOwner( args.get("verifiedPubKey").getAsString(), @@ -945,10 +898,7 @@ public class CMActions implements OnHashCallback { manager.changeDumpPeriod(c.getID(), args.get("dumpPeriod").getAsString()); } } else { - Result ret = new Result(); - ret.action = "onStartContract"; - ret.data = "Failed: Illegal user"; - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onStartContract", "Failed: Illegal user"); } ExecutionManager.instance.updateLocalContractToNodeCenter(); } @@ -1056,7 +1006,7 @@ public class CMActions implements OnHashCallback { if (args.has("requestID")) { ret.put("responseID", args.get("requestID").getAsString()); } - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); ExecutionManager.instance.updateLocalContractToNodeCenter(); if (handler != null) { listContractProcessWithFirstWithOwner( @@ -1075,10 +1025,7 @@ public class CMActions implements OnHashCallback { manager.changeDumpPeriod(c.getID(), args.get("dumpPeriod").getAsString()); } } else { - Result ret = new Result(); - ret.action = "onStartContractAsDebug"; - ret.data = "Failed: Illegal user"; - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback, "onStartContractAsDebug", "Failed: Illegal user"); } } @@ -1089,7 +1036,7 @@ public class CMActions implements OnHashCallback { ret.put("action", "onGetDumpPeriod"); ret.put("data", manager.getDumpPeriod(contractName)); ret.put("contractName", contractName); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); } @Action(userPermission = 1L << 25, async = true) @@ -1102,17 +1049,13 @@ public class CMActions implements OnHashCallback { ret.put("action", "onChangeDumpPeriod"); ret.put("data", manager.changeDumpPeriod(contractName, dumpPeriod)); ret.put("executeTime", System.currentTimeMillis() - start); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); } @Action(userPermission = 1L << 17) public void getCodeByID(JsonObject args, ResultCallback resultCallback) { String code = manager.getScriptStrByID(args.get("contractID").getAsString()); - Result r = new Result(); - r.data = code; - r.action = "onCodeResult"; - r.status = true; - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.simpleReply(resultCallback, "onCodeResult", code); } @Action(userPermission = 1L << 23) @@ -1124,7 +1067,7 @@ public class CMActions implements OnHashCallback { if (contractName == null) { ret.put("action", "onListMemoryFiles"); ret.put("data", "failed"); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); return; } File f = new File(String.format("%s/%s", GlobalConf.instance.memoryDir, contractName)); @@ -1139,7 +1082,7 @@ public class CMActions implements OnHashCallback { ret.put("data", dirs); } ret.put("action", "onListMemoryFiles"); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); } @Action(async = true, userPermission = 1L << 25) @@ -1151,7 +1094,7 @@ public class CMActions implements OnHashCallback { String contractName = manager.getContractNameByID(contractID); if (contractName == null) { res.put("data", "failed"); - resultCallback.onResult(JsonUtil.toJson(res)); + resultCallback.onResult(res); return; } @@ -1171,7 +1114,7 @@ public class CMActions implements OnHashCallback { res.put("time", cost + "s"); res.put("data", "success"); res.put("size", ByteUtil.byteTo(f.length())); - resultCallback.onResult(JsonUtil.toJson(res)); + resultCallback.onResult(res); } @Action(async = true, userPermission = 1L << 23) @@ -1197,7 +1140,7 @@ public class CMActions implements OnHashCallback { // ret.data = bo.toString(); res.put("data", bo.toString()); } - resultCallback.onResult(JsonUtil.toJson(res)); + resultCallback.onResult(res); } @Action(async = true, userPermission = 1L << 26) @@ -1209,25 +1152,24 @@ public class CMActions implements OnHashCallback { LOGGER.debug("forContract :"); // strs2.append("[CMActions] forContract :\n"); - resultCallback.onResult(JsonUtil.toJson(r)); + resultCallback.onResult(r); } @Action(userPermission = 1L << 19) public void connectTo(JsonObject args, ResultCallback resultCallback) { + String data; if (!args.has("id")) { - resultCallback.onResult( - "{\"action\":\"onConnectTo\",\"data\":\"missing contract id\"}"); + ReplyUtil.simpleReply(resultCallback,"onConnectTo","missing contract id"); return; } String contractID = args.get("id").getAsString(); LOGGER.info("connectTo:" + contractID); if (contractID == null) { - resultCallback.onResult( - "{\"action\":\"onConnectTo\",\"data\":\"can't find contract id\"}"); + ReplyUtil.simpleReply(resultCallback,"onConnectTo","can't find contract id"); return; } manager.redirect(contractID, createPS(), ""); - resultCallback.onResult("{\"action\":\"onConnectTo\",\"data\":\"success\"}"); + ReplyUtil.simpleReply(resultCallback,"onConnectTo","success"); } private PrintStream createPS() { @@ -1274,7 +1216,7 @@ public class CMActions implements OnHashCallback { r.put("action", "onKillContractProcess"); r.put("data", ret); r.put("executeTime", System.currentTimeMillis() - s); - resultCallback.onResult(JsonUtil.toJson(r)); + resultCallback.onResult(r); ExecutionManager.instance.updateLocalContractToNodeCenter(); return; } @@ -1302,10 +1244,7 @@ public class CMActions implements OnHashCallback { ExecutionManager.instance.updateLocalContractToNodeCenter(); } } else { - Result ret = new Result(); - ret.action = "onKillContractProcess"; - ret.data = "Failed: Illegal parameters"; - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback,"onKillContractProcess","Failed: Illegal parameters"); } } @@ -1325,7 +1264,7 @@ public class CMActions implements OnHashCallback { r.put("action", "onQueryContractInstanceDOI"); r.put("data", ret); r.put("executeTime", System.currentTimeMillis() - s); - resultCallback.onResult(JsonUtil.toJson(r)); + resultCallback.onResult(r); ExecutionManager.instance.updateLocalContractToNodeCenter(); } @@ -1465,7 +1404,7 @@ public class CMActions implements OnHashCallback { r.put("executeTime", System.currentTimeMillis() - start); // GRPCPool.writeToChain(c.getOwner(), privKey, gson.toJson(r), // json.getString("requestID")); - resultCallback.onResult(JsonUtil.toJson(r)); + resultCallback.onResult(r); } public String staticVerify(Contract c) { @@ -1487,7 +1426,7 @@ public class CMActions implements OnHashCallback { Map r = new HashMap<>(); r.put("action", "onGetControlFlow"); r.put("result", manager.getControlFlow(c)); - resultCallback.onResult(JsonUtil.toJson(r)); + resultCallback.onResult(r); } @Action(async = true, userPermission = 1L << 26) @@ -1509,13 +1448,13 @@ public class CMActions implements OnHashCallback { c.setOwner(pubkey); if (!c.verifySignature()) { r.put("data", "verify failed"); - resultCallback.onResult(JsonUtil.toJson(r)); + resultCallback.onResult(r); return; } r.put("data", manager.startContractAndRedirect(c, System.out)); r.put("cid", c.getID()); r.put("executeTime", System.currentTimeMillis() - start); - resultCallback.onResult(JsonUtil.toJson(r)); + resultCallback.onResult(r); if (args.has("dumpPeriod")) { LOGGER.debug("[CMActions]启动后设置dump周期" + args.get("dumpPeriod").getAsString()); @@ -1527,8 +1466,6 @@ public class CMActions implements OnHashCallback { public void killAllContract(JsonObject args, ResultCallback resultCallback) { if (args.has("verifiedPubKey")) { if (ContractManager.checkNodeManager(args.get(("verifiedPubKey")).getAsString())) { - Result r = new Result(); - r.action = "onKillAllContract"; StringBuilder sb = new StringBuilder(); sb.append("Kill:"); try { @@ -1566,22 +1503,15 @@ public class CMActions implements OnHashCallback { } catch (Exception e) { e.printStackTrace(); } - r.data = sb.toString(); ExecutionManager.instance.updateLocalContractToNodeCenter(); - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.simpleReply(resultCallback,"onKillAllContract",sb.toString()); manager.stopAllContracts(); } else { manager.stopAllContractsWithOwner(args.get(("verifiedPubKey")).getAsString()); - Result ret = new Result(); - ret.action = "onKillAllContract"; - ret.data = "Success"; - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback,"onKillAllContract","Success"); } } else { - Result ret = new Result(); - ret.action = "onKillAllContract"; - ret.data = "Failed: Illegal user"; - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.simpleReply(resultCallback,"onKillAllContract","Failed: Illegal user"); } } @@ -1593,7 +1523,7 @@ public class CMActions implements OnHashCallback { closePermission = closePermission.replace(", ", ""); String resetPermission = manager.resetPermission(contractFileName, closePermission, isOpen); LOGGER.debug(resetPermission); - ReplyUtil.simpleReply(resultCallback,"onSetPermission","success"); + ReplyUtil.simpleReply(resultCallback, "onSetPermission", "success"); } @Action(userPermission = 1L << 26, async = true, httpAccess = false) @@ -1601,7 +1531,7 @@ public class CMActions implements OnHashCallback { boolean flag = json.get("isDebug").getAsBoolean(); String contractID = json.get("contractID").getAsString(); String resetPermission = manager.resetDebugFlag(contractID, flag); - ReplyUtil.simpleReply(resultCallback,"onSetDebugFlag",resetPermission); + ReplyUtil.simpleReply(resultCallback, "onSetDebugFlag", resetPermission); } @Override @@ -1623,14 +1553,14 @@ public class CMActions implements OnHashCallback { JsonObject ret = new JsonObject(); ret.addProperty("status", "Error"); ret.addProperty("result", "missing arguments, contractID"); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); return; } ContractResult cr = manager.getLogSize(json.get("contractID").getAsString()); JsonObject ret = new JsonObject(); ret.addProperty("status", cr.status.toString()); ret.add("result", cr.result); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); } @Action(async = true, userPermission = 1L << 22) @@ -1640,7 +1570,7 @@ public class CMActions implements OnHashCallback { JsonObject ret = new JsonObject(); ret.addProperty("status", "Error"); ret.addProperty("result", "missing arguments, contractID / offset / count"); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); return; } String contractID = json.get("contractID").getAsString(); @@ -1654,7 +1584,7 @@ public class CMActions implements OnHashCallback { JsonUtil.fromJson( cr.result, new TypeToken>>() { }.getType())); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); } @Action(async = true, userPermission = 1L << 22) @@ -1664,7 +1594,7 @@ public class CMActions implements OnHashCallback { JsonObject ret = new JsonObject(); ret.addProperty("status", "Error"); ret.addProperty("result", "missing arguments, contractID / count"); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); return; } String contractID = json.get("contractID").getAsString(); @@ -1684,7 +1614,7 @@ public class CMActions implements OnHashCallback { } ret.put("contractID", contractID); - resultCallback.onResult(JsonUtil.toJson(ret)); + resultCallback.onResult(ret); } @Action(async = true, userPermission = 0L) @@ -1724,7 +1654,7 @@ public class CMActions implements OnHashCallback { JsonObject ret = new JsonObject(); ret.addProperty("status", "Error"); ret.addProperty("result", "Cannot form TCP connection to " + nodeName); - rc.onResult(JsonUtil.toJson(ret)); + rc.onResult(ret); } } } @@ -1862,7 +1792,7 @@ public class CMActions implements OnHashCallback { JsonObject ret = new JsonObject(); ret.addProperty("action", "onAskTimeRecorder"); ret.addProperty("data", data); - resultCallback.onResult(ret.toString()); + resultCallback.onResult(ret); } @Action(async = true) @@ -1908,7 +1838,7 @@ public class CMActions implements OnHashCallback { JsonObject ret = new JsonObject(); ret.addProperty("action", "onAskMasterElectTimeRecorder"); ret.addProperty("data", data); - resultCallback.onResult(ret.toString()); + resultCallback.onResult(ret); } @Action(async = true, userPermission = 1L << 12) @@ -1976,4 +1906,4 @@ public class CMActions implements OnHashCallback { } } } -} +} \ No newline at end of file diff --git a/src/main/java/org/bdware/server/action/LedgerActions.java b/src/main/java/org/bdware/server/action/LedgerActions.java index 93e9d51..366dbf0 100644 --- a/src/main/java/org/bdware/server/action/LedgerActions.java +++ b/src/main/java/org/bdware/server/action/LedgerActions.java @@ -115,19 +115,11 @@ public class LedgerActions { () -> { try { ByteString hash = future.get().getHash(); - Result r = new Result(); - r.action = "onSendTransaction"; - r.status = true; - r.data = HashUtil.byteArray2Str(hash.toByteArray()); - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", true, HashUtil.byteArray2Str(hash.toByteArray())); } catch (Exception e) { - Result r = new Result(); ByteArrayOutputStream bo = new ByteArrayOutputStream(); - r.action = "onSendTransaction"; - r.status = false; - e.printStackTrace(new PrintStream(bo)); - r.data = bo.toString(); - resultCallback.onResult(JsonUtil.toJson(r)); + String dataStr = bo.toString(); + ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", false, dataStr); e.printStackTrace(); } }, diff --git a/src/main/java/org/bdware/server/action/ManagerActions.java b/src/main/java/org/bdware/server/action/ManagerActions.java index 23c449f..d9a95b6 100644 --- a/src/main/java/org/bdware/server/action/ManagerActions.java +++ b/src/main/java/org/bdware/server/action/ManagerActions.java @@ -39,9 +39,9 @@ public class ManagerActions { @Action(userPermission = 1L << 11) public void getEncodedUUID(JsonObject args, ResultCallback resultCallback) { - Result r = new Result(); + String data = null; try { - r.data = + data = ByteUtils.toHexString( SM2Util.encrypt( GlobalConf.instance.keyPair.getPublicKey(), @@ -49,10 +49,7 @@ public class ManagerActions { } catch (Exception e) { e.printStackTrace(); } - r.status = true; - r.msg = null; - r.action = "onGetEncodedUUID"; - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onGetEncodedUUID", true, data); } @Action(userPermission = 1 << 10) @@ -67,40 +64,39 @@ public class ManagerActions { try { String key = args.get("key").getAsString(); String val = args.get("val").getAsString(); - Result r = new Result(); - r.msg = null; - r.action = "onUpdateConfig"; - r.status = true; + boolean + status = true; + Object data; switch (key) { case "licence": - r.data = GlobalConf.resetLicence(val); + data = GlobalConf.resetLicence(val); break; case "projectDir": - r.data = r.status = GlobalConf.resetProjectDir(val); + data = status = GlobalConf.resetProjectDir(val); break; case "yjsPath": - r.data = r.status = GlobalConf.resetYjsPath(val); + data = status = GlobalConf.resetYjsPath(val); break; case "dataChain": - r.data = r.status = GlobalConf.resetDataChain(val); + data = status = GlobalConf.resetDataChain(val); break; case "doipConfig": - r.data = r.status = GlobalConf.resetDOIPConfig(val); + data = status = GlobalConf.resetDOIPConfig(val); break; case "nodeCenter": - r.data = r.status = GlobalConf.resetNodeCenter(val); + data = status = GlobalConf.resetNodeCenter(val); break; case "nodeName": - r.data = r.status = GlobalConf.resetNodeName(val); + data = status = GlobalConf.resetNodeName(val); break; case "masterAddress": - r.data = r.status = GlobalConf.resetMasterAddress(val); + data = status = GlobalConf.resetMasterAddress(val); break; default: - r.status = false; - r.data = "unsupported key:" + key; + status = false; + data = "unsupported key:" + key; } - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onUpdateConfig", status, data); return; } catch (Exception e) { e.printStackTrace(); @@ -111,9 +107,7 @@ public class ManagerActions { @Action(userPermission = 1L << 11) // 弃用 新节点管理界面使用loadNodeConfig public void loadConfig(JsonObject args, ResultCallback resultCallback) { - Result r = new Result(); - r.action = "onLoadConfig"; - r.responseID=args.get("requestID").toString(); + Map data = new HashMap<>(); data.put("projectDir", GlobalConf.instance.projectDir); data.put("yjsPath", GlobalConf.instance.yjsPath); @@ -124,10 +118,7 @@ public class ManagerActions { data.put("expireTime", new Date(GlobalConf.instance.expireTime) + ""); data.put("nodeName", GlobalConf.instance.name); data.put("doipConfig", GlobalConf.instance.doipConfig); - r.data = data; - r.status = true; - r.msg = null; - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onLoadConfig", true, data); } @Action(userPermission = 1L << 11) @@ -136,11 +127,7 @@ public class ManagerActions { new ResultCallback() { @Override public void onResult(String str) { - Result ret = new Result(); - ret.status = true; - ret.action = "onListNodeInfos"; - ret.data = str; - resultCallback.onResult(JsonUtil.toJson(ret)); + ReplyUtil.replyWithStatus(resultCallback, "onListNodeInfos", true, str); } }); } @@ -154,10 +141,6 @@ public class ManagerActions { // Action in NodeNodePortal 节点配置 @Action(userPermission = 1L << 11) public void loadNodeConfig(JsonObject args, ResultCallback resultCallback) { - Result r = new Result(); - r.action = "onLoadNodeConfig"; - if (args.has("requestID")) - r.responseID=args.get("requestID").getAsString(); Map data = new HashMap<>(); data.put("yjsPath", GlobalConf.instance.yjsPath); data.put("nodeCenter", GlobalConf.getNodeCenterUrl()); @@ -171,24 +154,14 @@ public class ManagerActions { data.put("clusterConnected", String.valueOf(NetworkManager.instance.getNCClientHandler().isConnected())); data.put("nodePubKey", GlobalConf.instance.keyPair.getPublicKeyStr()); data.put("masterAddress", GlobalConf.instance.masterAddress); - r.data = data; - r.status = true; - r.msg = null; - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onLoadNodeConfig", true, data); } @Action(userPermission = 1 << 10) public void changeNodeCenter(JsonObject args, ResultCallback resultCallback) { String val = args.get("data").getAsString(); - Result r = new Result(); - r.msg = null; - r.action = "onChangeNodeCenter"; - r.status = true; - r.data = GlobalConf.resetNodeCenter(val); - - LOGGER.debug(JsonUtil.toJson(r)); - - resultCallback.onResult(JsonUtil.toJson(r)); + LOGGER.debug(JsonUtil.toJson(args)); + ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeCenter", true, GlobalConf.resetNodeCenter(val)); } @Action(userPermission = 1 << 10) @@ -196,80 +169,42 @@ public class ManagerActions { String val = args.get("data").getAsString(); String lines = val.replace(" ", "\n"); LOGGER.debug("changeBDledger " + lines); - Result r = new Result(); - r.msg = null; - r.action = "onChangeBDledger"; - r.status = true; - r.data = GlobalConf.resetDataChain(lines); - - LOGGER.debug(JsonUtil.toJson(r)); - - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onChangeBDledger", true, GlobalConf.resetDataChain(lines)); } @Action(userPermission = 1 << 10) public void changeNodeName(JsonObject args, ResultCallback resultCallback) { String val = args.get("data").getAsString(); - Result r = new Result(); - r.msg = null; - r.action = "onChangeNodeName"; - r.status = true; - r.data = GlobalConf.resetNodeName(val); - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeName", true, GlobalConf.resetNodeName(val)); } @Action(userPermission = 1 << 10) public void changeIpPort(JsonObject args, ResultCallback resultCallback) { String val = args.get("data").getAsString(); - Result r = new Result(); - r.msg = null; - r.action = "onChangeIpPort"; - r.status = true; - r.data = GlobalConf.resetIpPort(val); - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onChangeIpPort", true, GlobalConf.resetIpPort(val)); } @Action(userPermission = 1 << 10) public void changeDOIPConfig(JsonObject args, ResultCallback resultCallback) { String val = args.get("data").getAsString(); - Result r = new Result(); - r.msg = null; - r.action = "onChangeDOIPConfig"; - r.status = true; - r.data = GlobalConf.resetDOIPConfig(val); - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onChangeDOIPConfig", true, GlobalConf.resetDOIPConfig(val)); } @Action(userPermission = 1 << 10) public void changeYJSPath(JsonObject args, ResultCallback resultCallback) { String val = args.get("data").getAsString(); - Result r = new Result(); - r.msg = null; - r.action = "onChangeYJSPath"; - r.status = true; - r.data = GlobalConf.resetYjsPath(val); - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onChangeYJSPath", true, GlobalConf.resetYjsPath(val)); } @Action(userPermission = 1 << 10) public void uploadLicence(JsonObject args, ResultCallback resultCallback) { String val = args.get("data").getAsString(); - Result r = new Result(); - r.msg = null; - r.action = "onUploadLicence"; - r.status = true; - r.data = GlobalConf.resetLicence(val); - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onUploadLicence", true, GlobalConf.resetLicence(val)); } @Action(userPermission = 1 << 11) public void getPeerID(JsonObject args, ResultCallback resultCallback) { - Result r = new Result(); - r.msg = null; - r.action = "onGetPeerID"; - r.status = true; - r.data = GlobalConf.instance.peerID; - resultCallback.onResult(JsonUtil.toJson(r)); + ReplyUtil.replyWithStatus(resultCallback, "onGetPeerID", true, GlobalConf.instance.peerID); } @Action @@ -292,8 +227,7 @@ public class ManagerActions { String already = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubKey); if (already != null && already.contains(role.toString())) { - resultCallback.onResult( - "{\"action\":\"onApplyNodeRole\",\"data\":\"already has!\"}"); + ReplyUtil.simpleReply(resultCallback, "onApplyNodeRole", "already has!"); return; } @@ -310,15 +244,17 @@ public class ManagerActions { CMTables.ApplyTime.toString(), pubKey, Long.toString(new Date().getTime())); - resultCallback.onResult( - "{\"action\":\"onApplyNodeRole\",\"data\":\"success\"}"); + ReplyUtil.simpleReply(resultCallback, "onApplyNodeRole", "success"); + return; } } + JsonObject ret = new JsonObject(); + ret.addProperty("action", "onApplyNodeRole"); + ret.addProperty("data", "success"); + ret.addProperty("role", ro); resultCallback.onResult( - "{\"action\":\"onApplyNodeRole\",\"data\":\"success\",\"role\":\"" - + ro - + "\"}"); + ret); } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/org/bdware/server/trustedmodel/MasterProxy.java b/src/main/java/org/bdware/server/trustedmodel/MasterProxy.java index 855626b..45b10fe 100644 --- a/src/main/java/org/bdware/server/trustedmodel/MasterProxy.java +++ b/src/main/java/org/bdware/server/trustedmodel/MasterProxy.java @@ -1,5 +1,6 @@ package org.bdware.server.trustedmodel; +import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import io.netty.bootstrap.Bootstrap; import org.apache.logging.log4j.LogManager; @@ -80,17 +81,17 @@ public class MasterProxy implements MasterStub { request.getRequestID(), new ResultCallback() { @Override - public void onResult(String str) { - String ret = + public void onResult(String ret) { + JsonObject result =JsonUtil.parseString(ret); ContractManager.instance.extractEventsFromContractResult( - null, str, client, request, start); + null, result, client, request, start); LOGGER.debug( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date(System.currentTimeMillis())) + " [MasterProxy] executeByMaster 结果是 " + ret + "\n"); - rcb.onResult(ret); + rcb.onResult(result); } }, request); @@ -108,7 +109,7 @@ public class MasterProxy implements MasterStub { new ContractResult( ContractResult.Status.Error, new JsonPrimitive("canceled because of queue too long")); - cb.onResult(JsonUtil.toJson(cr)); + cb.onResult(JsonUtil.parseObject(cr)); CongestionControl.masterProxyLoad.decrementAndGet(); return; } @@ -117,7 +118,7 @@ public class MasterProxy implements MasterStub { new ResultCallback() { @Override public void onResult(String str) { - cb.onResult(str); + cb.onResult(JsonUtil.parseString(str)); CongestionControl.masterProxyLoad.decrementAndGet(); } }); diff --git a/src/main/java/org/bdware/server/ws/ContractManagerFrameHandler.java b/src/main/java/org/bdware/server/ws/ContractManagerFrameHandler.java index 78a46c8..3edd3b2 100644 --- a/src/main/java/org/bdware/server/ws/ContractManagerFrameHandler.java +++ b/src/main/java/org/bdware/server/ws/ContractManagerFrameHandler.java @@ -17,6 +17,7 @@ import org.bdware.server.action.*; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -111,6 +112,7 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler 0) { map.addProperty("verifiedPubKey", userManagerAction.getPubKey()); } - + final JsonObject jmap = map; ae.handle( action, map, new ResultCallback(ctx.channel()) { + @Override + public void onResult(Map jo) { + if (jmap.has("requestID")) { + + jo.put("responseID", jmap.get("requestID").getAsString()); + } + onResult(JsonUtil.toJson(jo)); + } + + @Override + public void onResult(JsonObject jo) { + if (jmap.has("requestID")) { + jo.add("responseID", jmap.get("requestID")); + } + onResult(jo.toString()); + } + + @Override public void onResult(String ret) { if (ret != null) {