From 5034e36d86a4978b4268b319989ef9dba1ba6be7 Mon Sep 17 00:00:00 2001 From: CaiHQ Date: Wed, 22 Dec 2021 22:07:51 +0800 Subject: [PATCH] optimize: use jquery 2.1.4.min refactor: DOA Contract update: use doip sdk 1.0.2 optimize build.gradle --- build.gradle | 8 +- .../java/org/bdware/server/CMHttpServer.java | 18 +-- src/main/java/org/bdware/server/DOAConf.java | 6 + src/main/java/org/bdware/server/GRPCPool.java | 12 ++ .../java/org/bdware/server/GlobalConf.java | 96 +++++--------- .../org/bdware/server/action/FileActions.java | 24 +--- .../bdware/server/action/ManagerActions.java | 5 +- .../bdware/server/action/MasterWSAction.java | 20 +-- .../server/action/UserManagerAction.java | 7 +- .../server/doip/ContractRepoConfigurer.java | 115 ---------------- .../doip/ContractRepositoryHandler.java | 101 ++++++++------ .../server/doip/ContractRepositoryMain.java | 125 ++++-------------- .../server/doip/ContractRepositoryServer.java | 5 + .../org/bdware/server/http/CMHttpHandler.java | 5 +- src/test/java/org/bdware/server/DOIPTest.java | 55 ++++---- 15 files changed, 200 insertions(+), 402 deletions(-) create mode 100644 src/main/java/org/bdware/server/DOAConf.java delete mode 100644 src/main/java/org/bdware/server/doip/ContractRepoConfigurer.java create mode 100644 src/main/java/org/bdware/server/doip/ContractRepositoryServer.java diff --git a/build.gradle b/build.gradle index 6c7a935..82a93fb 100644 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,6 @@ plugins { mainClassName = 'org.bdware.server.CMHttpServer' - application { mainClass = mainClassName applicationDefaultJvmArgs = ['-Dfile.encoding=UTF-8', '-Djava.library.path="./dynamicLibrary"'] @@ -39,6 +38,7 @@ dependencies { implementation 'org.knowhowlab.osgi:sigar:1.6.5_01' implementation 'io.grpc:grpc-all:1.41.0' implementation 'org.apache.velocity:velocity-engine-core:2.3' + implementation 'com.nimbusds:nimbus-jose-jwt:9.10' testImplementation 'junit:junit:4.13.2' } @@ -183,9 +183,9 @@ task buildBDServerZipLite(type: Zip, dependsOn: [":agent-backend:copyWebContent" } task buildBDServerZipMin(type: Zip, dependsOn: [":agent-backend:copyWebContent", - ":agent-backend:copyBDWareProjectDir", ":agent-backend:copyScript", - ":agent-backend:copyJar", ":agent-backend:copyLibs", - ":agent-backend:copyKeys"]) { + ":agent-backend:copyBDWareProjectDir", ":agent-backend:copyScript", + ":agent-backend:copyJar", ":agent-backend:copyLibs", + ":agent-backend:copyKeys"]) { from('./build/output/') { exclude 'BDWareProjectDir/public/**' exclude 'WebContent/doc/' diff --git a/src/main/java/org/bdware/server/CMHttpServer.java b/src/main/java/org/bdware/server/CMHttpServer.java index 3fded33..be0a588 100644 --- a/src/main/java/org/bdware/server/CMHttpServer.java +++ b/src/main/java/org/bdware/server/CMHttpServer.java @@ -21,7 +21,6 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.Configurator; -import org.bdware.doip.core.utils.GlobalConfigurations; import org.bdware.sc.*; import org.bdware.sc.db.CMTables; import org.bdware.sc.db.KeyValueDBUtil; @@ -67,15 +66,15 @@ public class CMHttpServer { GlobalConf.instance.isLAN = cmdConf.isLAN; if (!cmdConf.doipCertPath.isEmpty()) { String[] conf = cmdConf.doipCertPath.split(":"); - GlobalConfigurations.certPath = conf[0]; - GlobalConfigurations.certPassword = conf[1]; +// DOAConf.certPath = conf[0]; +// DOAConf.certPassword = conf[1]; } if (!cmdConf.doipUserHandle.isEmpty()) { - GlobalConfigurations.User_Handle = cmdConf.doipUserHandle; + DOAConf.repoDoid = cmdConf.doipUserHandle; } if (!cmdConf.doipLhsAddress.isEmpty()) { - GlobalConfigurations.LHS_Address = cmdConf.doipLhsAddress; + DOAConf.lhsAddress = cmdConf.doipLhsAddress; } if (cmdConf.withBdledgerServer) { ContractManager.threadPool.execute( @@ -236,19 +235,16 @@ public class CMHttpServer { } } - start(cmdConf.ip, cmdConf.servicePort, cmdConf.doipPort, cmdConf); + start(cmdConf.ip, cmdConf.servicePort, cmdConf); } - public static void start(String ip, int port, int doipPort, CMDConf cmdConf) throws IOException { - if (DoConfig.callContractUsingDOI) { - ContractManager.threadPool.execute( - () -> ContractRepositoryMain.start("tcp://" + ip + ":" + doipPort)); - } + public static void start(String ip, int port, CMDConf cmdConf) throws IOException { LOGGER.info("start server at:" + port); GlobalConf.initMasterAddress(ip + ":" + (port + 1)); GlobalConf.initIpPort(ip + ":" + port); LOGGER.debug("dir:" + new File("./").getAbsolutePath()); new CMHttpServer(port).start(); + ContractRepositoryMain.start(); } /** diff --git a/src/main/java/org/bdware/server/DOAConf.java b/src/main/java/org/bdware/server/DOAConf.java new file mode 100644 index 0000000..8b67c75 --- /dev/null +++ b/src/main/java/org/bdware/server/DOAConf.java @@ -0,0 +1,6 @@ +package org.bdware.server; + +public class DOAConf { + public static String lhsAddress; + public static String repoDoid; +} diff --git a/src/main/java/org/bdware/server/GRPCPool.java b/src/main/java/org/bdware/server/GRPCPool.java index 47f43b1..e66b7f3 100644 --- a/src/main/java/org/bdware/server/GRPCPool.java +++ b/src/main/java/org/bdware/server/GRPCPool.java @@ -44,6 +44,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; + public class GRPCPool implements ChainOpener { public static final String LEDGER_NAME = "bdcontract"; public static final int WORKER_COUNT = 8; @@ -246,6 +247,16 @@ public class GRPCPool implements ChainOpener { } } + @Override + public void reRegister(String doid) { + //TODO just success + // throw new IllegalStateException("TODO"); + } + + public String register(String path) { + return "Contract_" + path.hashCode(); + } + @Override public void writeContractResultToLocalAndLedger( String result, @@ -595,6 +606,7 @@ public class GRPCPool implements ChainOpener { return index; } + static class Line { public transient String contractName; String from, to, data, requestID; diff --git a/src/main/java/org/bdware/server/GlobalConf.java b/src/main/java/org/bdware/server/GlobalConf.java index 88eed30..3d2d51c 100644 --- a/src/main/java/org/bdware/server/GlobalConf.java +++ b/src/main/java/org/bdware/server/GlobalConf.java @@ -1,12 +1,9 @@ package org.bdware.server; -import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonObject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.Configurator; -import org.bdware.doip.application.DoipServiceConfig; -import org.bdware.doip.core.utils.GlobalConfigurations; -import org.bdware.doip.endpoint.doipServer.DoipListenerInfo; import org.bdware.sc.ContractManager; import org.bdware.sc.db.CMTables; import org.bdware.sc.db.KeyValueDBUtil; @@ -14,14 +11,13 @@ import org.bdware.sc.db.TimeDBUtil; import org.bdware.sc.encrypt.HardwareInfo; import org.bdware.sc.util.ExceptionUtil; import org.bdware.sc.util.JsonUtil; +import org.bdware.server.doip.ContractRepositoryMain; import org.bdware.units.NetworkManager; import org.zz.gmhelper.SM2KeyPair; import org.zz.gmhelper.SM2Util; import java.io.File; -import java.net.URI; import java.net.URL; -import java.util.List; import java.util.logging.Level; public class GlobalConf { @@ -48,7 +44,6 @@ public class GlobalConf { public String masterAddress; public String ipPort; public boolean isLAN = true; - public String doipConfig; private String nodeCenterUrl; // 从ConfigDB读。 private static GlobalConf init() { @@ -103,7 +98,6 @@ public class GlobalConf { LOGGER.debug("recreating keyPair " + conf.keyPair.toJson()); byte[] cpuid = HardwareInfo.getCPUID().getBytes(); LOGGER.debug("before encrypt: " + conf.keyPair.toJson() + " len:" + cpuid.length); - String deviceName = ByteHexUtil.encode(SM2Util.encrypt(conf.keyPair.getPublicKey(), cpuid)); LOGGER.debug("device Name:" + deviceName); @@ -131,8 +125,11 @@ public class GlobalConf { KeyValueDBUtil.instance.setValue(dbName, "nodeName", deviceName.substring(0, 10)); KeyValueDBUtil.instance.setValue(dbName, "masterAddress", "null"); KeyValueDBUtil.instance.setValue(dbName, "ipPort", "null"); - KeyValueDBUtil.instance.setValue(dbName, "doipConfig", "{}"); - KeyValueDBUtil.instance.setValue(dbName, "nodeCenter", "ws://127.0.0.1:18002"); + JsonObject doipConfig = new JsonObject(); + doipConfig.addProperty("lhsAddress", "tcp://127.0.0.1:2641"); + doipConfig.addProperty("repoDoid", "bdware.trusted.test/Repo." + conf.keyPair.getPublicKeyStr().substring(0, 6)); + KeyValueDBUtil.instance.setValue(dbName, "doipConfig", doipConfig.toString()); + KeyValueDBUtil.instance.setValue(dbName, "nodeCenter", "ws://127.0.0.1:18002"); KeyValueDBUtil.instance.setValue( dbName, "datachainConf", @@ -157,16 +154,14 @@ public class GlobalConf { conf.datachainConf = KeyValueDBUtil.instance.getValue(dbName, "datachainConf"); conf.name = KeyValueDBUtil.instance.getValue(dbName, "nodeName"); conf.ipPort = KeyValueDBUtil.instance.getValue(dbName, "ipPort"); - conf.doipConfig = KeyValueDBUtil.instance.getValue(dbName, "doipConfig"); conf.isLAN = "true".equals(KeyValueDBUtil.instance.getValue(dbName, "isLAN")); conf.masterAddress = KeyValueDBUtil.instance.getValue(dbName, "masterAddress"); conf.nodeCenterUrl = KeyValueDBUtil.instance.getValue(dbName, "nodeCenter"); conf.peerID = KeyValueDBUtil.instance.getValue(dbName, "peerID"); - conf.keyPairStr = KeyValueDBUtil.instance.getValue(dbName, "keyPairStr"); // logger.debug("keyPairStr" + conf.keyPairStr); conf.keyPair = SM2KeyPair.fromJson(conf.keyPairStr); - + loadDOAConfig(KeyValueDBUtil.instance.getValue(dbName, "doipConfig")); } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.debug(ExceptionUtil.exceptionToString(e)); @@ -226,6 +221,24 @@ public class GlobalConf { return conf; } + private static void loadDOAConfig(String val) { + try { + JsonObject doipConfig = JsonUtil.parseStringAsJsonObject(val); + DOAConf.lhsAddress = doipConfig.get("lhsAddress").getAsString(); + DOAConf.repoDoid = doipConfig.get("repoDoid").getAsString(); + //TODO 这个怎么获取?要通过啥来获取自己的repoDoid呢? + //所以现在的lhsAddress暂时没起作用。 + } catch (Exception e) { + } + } + + public static String getDOAConfig() { + JsonObject doipConfig = new JsonObject(); + doipConfig.addProperty("lhsAddress", DOAConf.lhsAddress); + doipConfig.addProperty("repoDoid", DOAConf.repoDoid); + return doipConfig.toString(); + } + private static void deleteJelck(File file) { if (file.exists()) { LOGGER.trace("delete file " + file.getAbsolutePath() + ": " + file.delete()); @@ -320,32 +333,7 @@ public class GlobalConf { instance.masterAddress = val; KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "masterAddress", val); NetworkManager.instance.reInitNodeCenter(); - ContractManager.threadPool.execute(() -> { - try { - if (ContractManager.doipConfigurer != null) { - DoipServiceConfig doipServiceConfig = - ContractManager.doipConfigurer.getDoipServiceConfig(); - List listenerInfo = - JsonUtil.fromJson( - doipServiceConfig.listeners, - new TypeToken< - List>() { - }.getType()); - URI uri = new URI(listenerInfo.get(0).url); // old doip url - listenerInfo.get(0).url = - uri.getScheme() - + "://" - + val.split(":")[0] - + ":" - + (Integer.parseInt(val.split(":")[1]) + 1); - doipServiceConfig.listeners = JsonUtil.toJson(listenerInfo); - GlobalConf.resetDOIPConfig(JsonUtil.toJson(doipServiceConfig)); - } - } catch (Exception e) { - LOGGER.error(e.getMessage()); - LOGGER.debug(ExceptionUtil.exceptionToString(e)); - } - }); + ContractRepositoryMain.start(); return true; } catch (Exception e) { LOGGER.error(e.getMessage()); @@ -364,21 +352,6 @@ public class GlobalConf { LOGGER.error(e.getMessage()); LOGGER.debug(ExceptionUtil.exceptionToString(e)); return false; - } finally { - try { - if (ContractManager.doipConfigurer != null && instance.isLAN) { - DoipServiceConfig doipServiceConfig = - ContractManager.doipConfigurer.getDoipServiceConfig(); - URI uri = new URI(val); - doipServiceConfig.LHSProxyAddress = - GlobalConfigurations.LHS_Address = - "http://" + uri.getHost() + ":" + (uri.getPort() + 1) + "/"; - GlobalConf.resetDOIPConfig(JsonUtil.toJson(doipServiceConfig)); - } - } catch (Exception e) { - LOGGER.error(e.getMessage()); - LOGGER.debug(ExceptionUtil.exceptionToString(e)); - } } } @@ -450,17 +423,12 @@ public class GlobalConf { public static boolean resetDOIPConfig(String val) { try { - if (ContractManager.doipConfigurer != null) { - val = ContractManager.doipConfigurer.resetServiceConfig(val); - } + loadDOAConfig(val); + //TODO get prefix if needed! + KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "doipConfig", val); } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.debug(ExceptionUtil.exceptionToString(e)); - val = null; - } - instance.doipConfig = val; - if (null != val) { - KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "doipConfig", val); } return true; } @@ -469,10 +437,6 @@ public class GlobalConf { return instance.isLAN; } - public static String getDOIPConfig() { - return instance.doipConfig; - } - public static String getDBPath() { return new File("ContractDB").getAbsolutePath(); // return new File("./conf/").getAbsolutePath(); diff --git a/src/main/java/org/bdware/server/action/FileActions.java b/src/main/java/org/bdware/server/action/FileActions.java index 3349604..9d4da67 100644 --- a/src/main/java/org/bdware/server/action/FileActions.java +++ b/src/main/java/org/bdware/server/action/FileActions.java @@ -14,9 +14,6 @@ import io.netty.util.Timeout; import io.netty.util.TimerTask; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.bdware.doip.core.model.handleRecord.DoHandleRecord; -import org.bdware.doip.core.utils.GlobalConfigurations; -import org.bdware.doip.endpoint.irpClient.GlobalIrpClient; import org.bdware.sc.ContractManager; import org.bdware.sc.YJSPacker; import org.bdware.sc.bean.Contract; @@ -29,8 +26,8 @@ import org.bdware.sc.node.ContractManifest; import org.bdware.sc.util.FileUtil; import org.bdware.sc.util.JsonUtil; import org.bdware.server.ControllerManager; +import org.bdware.server.GRPCPool; import org.bdware.server.GlobalConf; -import org.bdware.server.doip.ContractRepositoryMain; import org.bdware.server.http.URIPath; import org.bdware.server.nodecenter.Response; import org.bdware.server.permission.Role; @@ -379,20 +376,15 @@ public class FileActions { String manifestJson = new String(content); JsonObject jo = JsonParser.parseString(manifestJson).getAsJsonObject(); - DoHandleRecord doHandleRecord = - new DoHandleRecord( - GlobalConfigurations.User_Handle, - ContractRepositoryMain.repoID); if (jo.get("doi") == null) { String doi = "86.5000.470/do." + geneRandomID(); jo.addProperty("doi", doi); } - doHandleRecord.handle = jo.get("doi").getAsString(); ContractManager.threadPool.execute( () -> { // manifestFile...... try { - GlobalIrpClient.getGlobalClient().reRegister(doHandleRecord); + GRPCPool.instance.reRegister(jo.get("doi").getAsString()); } catch (Exception e) { LOGGER.warn("unable to connect LHS: " + e.getMessage()); } @@ -724,16 +716,7 @@ public class FileActions { String doi = null; try { - DoHandleRecord dohr = - new DoHandleRecord( - GlobalConfigurations.User_Handle, GlobalConfigurations.DoipServiceID); - if (GlobalIrpClient.getGlobalClient() == null) { - LOGGER.info("globalIrpClient not initialized yet!"); - r.put("result", "globalIrpClient not initialized yet!"); - resultCallback.onResult(JsonUtil.toJson(r)); - return; - } - doi = GlobalIrpClient.getGlobalClient().register(dohr); + doi = GRPCPool.instance.register(dir.getAbsolutePath()); } catch (Exception e) { LOGGER.warn("unable to connect LHS: " + e.getMessage()); } @@ -743,7 +726,6 @@ public class FileActions { resultCallback.onResult(r); return; } - // write to manifest.json Map content = new HashMap(); try { diff --git a/src/main/java/org/bdware/server/action/ManagerActions.java b/src/main/java/org/bdware/server/action/ManagerActions.java index 8b0bf19..d177976 100644 --- a/src/main/java/org/bdware/server/action/ManagerActions.java +++ b/src/main/java/org/bdware/server/action/ManagerActions.java @@ -108,7 +108,6 @@ public class ManagerActions { @Action(userPermission = 1L << 11) // 弃用 新节点管理界面使用loadNodeConfig public void loadConfig(JsonObject args, ResultCallback resultCallback) { - Map data = new HashMap<>(); data.put("projectDir", GlobalConf.instance.projectDir); data.put("yjsPath", GlobalConf.instance.yjsPath); @@ -118,7 +117,7 @@ public class ManagerActions { data.put("licence", GlobalConf.instance.licence); data.put("expireTime", new Date(GlobalConf.instance.expireTime) + ""); data.put("nodeName", GlobalConf.instance.name); - data.put("doipConfig", GlobalConf.instance.doipConfig); + data.put("doipConfig", GlobalConf.getDOAConfig()); ReplyUtil.replyWithStatus(resultCallback, "onLoadConfig", true, data); } @@ -148,7 +147,7 @@ public class ManagerActions { data.put("licence", GlobalConf.instance.licence); data.put("nodeName", GlobalConf.instance.name); data.put("ipPort", GlobalConf.instance.ipPort); - data.put("doipConfig", GlobalConf.instance.doipConfig); + data.put("doipConfig", GlobalConf.getDOAConfig()); data.put("isLAN", String.valueOf(GlobalConf.isLAN())); data.put("peerID", GlobalConf.instance.peerID); data.put("bdledger", GlobalConf.instance.datachainConf.replace("\n", " ")); diff --git a/src/main/java/org/bdware/server/action/MasterWSAction.java b/src/main/java/org/bdware/server/action/MasterWSAction.java index 5f2c491..d995b87 100644 --- a/src/main/java/org/bdware/server/action/MasterWSAction.java +++ b/src/main/java/org/bdware/server/action/MasterWSAction.java @@ -3,10 +3,6 @@ package org.bdware.server.action; import com.google.gson.JsonObject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.bdware.doip.core.exception.IrpClientException; -import org.bdware.doip.core.model.handleRecord.DoHandleRecord; -import org.bdware.doip.core.utils.GlobalConfigurations; -import org.bdware.doip.endpoint.irpClient.GlobalIrpClient; import org.bdware.sc.ContractManager; import org.bdware.sc.bean.Contract; import org.bdware.sc.bean.ContractExecType; @@ -15,6 +11,7 @@ import org.bdware.sc.db.CMTables; import org.bdware.sc.db.KeyValueDBUtil; import org.bdware.sc.units.RecoverFlag; import org.bdware.sc.util.JsonUtil; +import org.bdware.server.GRPCPool; import org.bdware.server.GlobalConf; import org.bdware.server.action.p2p.MasterServerRecoverMechAction; import org.bdware.server.action.p2p.MasterServerTCPAction; @@ -210,26 +207,13 @@ public class MasterWSAction { // 多点合约更新repository信息 if (contract.getDOI() != null && !contract.getDOI().equals("null")) { LOGGER.info("multipoint contract doi register"); - try { - DoHandleRecord dohr = - new DoHandleRecord( - GlobalConfigurations.User_Handle, - GlobalConfigurations.DoipServiceID); - dohr.handle = contract.getDOI(); - LOGGER.info(contract.getDOI()); - if (GlobalIrpClient.getGlobalClient() != null) { - GlobalIrpClient.getGlobalClient().reRegister(dohr); - } - } catch (IrpClientException e) { - LOGGER.warn("unable to connect LHS: " + e.getMessage()); - } + GRPCPool.instance.reRegister(contract.getDOI()); } else { LOGGER.info( "multipoint contract don't update register " + (null == contract.getDOI() ? "null" : contract.getDOI())); } }); - final long curr = System.currentTimeMillis(); String requestID = curr + "_" + (int) (Math.random() * 10000); ResultCollector collector = diff --git a/src/main/java/org/bdware/server/action/UserManagerAction.java b/src/main/java/org/bdware/server/action/UserManagerAction.java index ee4c26e..7830887 100644 --- a/src/main/java/org/bdware/server/action/UserManagerAction.java +++ b/src/main/java/org/bdware/server/action/UserManagerAction.java @@ -34,6 +34,10 @@ public class UserManagerAction { private String sessionID; private String pubKey; + public static String getNodeManager() { + return KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), NodeManager); + } + public UserManagerAction(ContractManagerFrameHandler contractManagerFrameHandler) { handler = contractManagerFrameHandler; } @@ -78,8 +82,7 @@ public class UserManagerAction { return; } try { - String ret = - KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), NodeManager); + String ret = getNodeManager(); boolean isNodeManager; if (ret != null && ret.length() > 0) { isNodeManager = (ret.equals(pubKey)); diff --git a/src/main/java/org/bdware/server/doip/ContractRepoConfigurer.java b/src/main/java/org/bdware/server/doip/ContractRepoConfigurer.java deleted file mode 100644 index d29129e..0000000 --- a/src/main/java/org/bdware/server/doip/ContractRepoConfigurer.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.bdware.server.doip; - -import com.google.gson.reflect.TypeToken; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.bdware.doip.application.DoipServiceConfig; -import org.bdware.doip.core.crypto.GlobalCertifications; -import org.bdware.doip.core.utils.GlobalConfigurations; -import org.bdware.doip.endpoint.doipServer.DoipListenerInfo; -import org.bdware.doip.endpoint.doipServer.DoipServiceInfo; -import org.bdware.doip.endpoint.irpClient.GlobalIrpClient; -import org.bdware.sc.ContractManager; -import org.bdware.sc.DoipServiceInfoConfigurer; -import org.bdware.sc.util.JsonUtil; -import org.bdware.server.GlobalConf; - -import java.net.URI; -import java.util.List; - -public class ContractRepoConfigurer implements DoipServiceInfoConfigurer { - private static final Logger LOGGER = LogManager.getLogger(ContractRepoConfigurer.class); - DoipServiceConfig doipServiceConfig; - DoipServiceInfo doipServiceInfo; - - public ContractRepoConfigurer(DoipServiceInfo doipServiceInfo, DoipServiceConfig config) { - this.doipServiceInfo = doipServiceInfo; - this.doipServiceConfig = config; - } - - @Override - public String getServiceHandle() { - return doipServiceInfo.id; - } - - @Override - public String resetServiceConfig(String configJson) { - DoipServiceConfig localConfig; - try { - localConfig = JsonUtil.fromJson(configJson, DoipServiceConfig.class); - //refresh DOIPServiceInfo - doipServiceInfo.id = localConfig.repoID; - doipServiceInfo.owner = localConfig.ownerHandle; - doipServiceInfo.repoType = localConfig.type; - doipServiceInfo.listenerInfos = JsonUtil.fromJson(localConfig.listeners, new TypeToken>() { - }.getType()); - String url = doipServiceInfo.listenerInfos.get(0).url; - URI uri = URI.create(url); - doipServiceInfo.protocol = uri.getScheme(); - doipServiceInfo.ipAddress = uri.getHost(); - doipServiceInfo.port = uri.getPort(); - doipServiceInfo.protocolVersion = doipServiceInfo.listenerInfos.get(0).protocolVersion; - doipServiceInfo.serviceName = localConfig.serviceName; - doipServiceInfo.serviceDescription = localConfig.serviceDescription; - } catch (Exception e) { - LOGGER.warn("invalid DOIP config json, change nothing"); - return JsonUtil.toJson(doipServiceConfig); - } - if (localConfig.LHSProxyAddress != null) { - GlobalConfigurations.LHS_Address = localConfig.LHSProxyAddress; - } else { - localConfig.LHSProxyAddress = doipServiceConfig.LHSProxyAddress; - } - if (localConfig.ownerHandle != null) { - GlobalConfigurations.User_Handle = localConfig.ownerHandle; - } else { - localConfig.ownerHandle = doipServiceConfig.ownerHandle; - } - if (localConfig.certPath != null) { - GlobalConfigurations.certPath = localConfig.certPath; - } else { - localConfig.certPath = GlobalConfigurations.certPath; - } - if (localConfig.certPassword != null) { - GlobalConfigurations.certPassword = localConfig.certPassword; - } else { - localConfig.certPassword = GlobalConfigurations.certPassword; - } - - doipServiceConfig = localConfig; - //异步注册 - ContractManager.threadPool.execute(() -> { - GlobalIrpClient.useInternalIrpClient(GlobalCertifications.localKeypair, - GlobalConfigurations.User_Handle, - GlobalConfigurations.LHS_Address); - if (doipServiceInfo.id.equals("")) { - try { - doipServiceInfo.id = GlobalIrpClient.getGlobalClient().register(doipServiceInfo.toServiceHandleRecord()); - } catch (Exception e) { - LOGGER.warn("unable to connect LHS: " + e.getMessage()); -// e.printStackTrace(); - } - } else { - try { - GlobalIrpClient.getGlobalClient().reRegister(doipServiceInfo.toServiceHandleRecord()); - } catch (Exception e) { - LOGGER.warn("unable to connect LHS: " + e.getMessage()); -// e.printStackTrace(); - } - } - GlobalConfigurations.DoipServiceID = doipServiceConfig.repoID = doipServiceInfo.id; - GlobalConf.instance.doipConfig = JsonUtil.toJson(doipServiceConfig); - }); - return JsonUtil.toJson(doipServiceConfig); - } - - @Override - public DoipServiceConfig getDoipServiceConfig() { - return doipServiceConfig; - } - - @Override - public DoipServiceInfo getDoipServiceInfo() { - return doipServiceInfo; - } -} diff --git a/src/main/java/org/bdware/server/doip/ContractRepositoryHandler.java b/src/main/java/org/bdware/server/doip/ContractRepositoryHandler.java index 935ec83..62f7ddd 100644 --- a/src/main/java/org/bdware/server/doip/ContractRepositoryHandler.java +++ b/src/main/java/org/bdware/server/doip/ContractRepositoryHandler.java @@ -1,7 +1,9 @@ package org.bdware.server.doip; import com.google.gson.JsonArray; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; import io.netty.channel.ChannelHandler; import org.bdware.doip.core.doipMessage.DoipMessage; import org.bdware.doip.core.doipMessage.DoipResponseCode; @@ -13,19 +15,20 @@ import org.bdware.doip.endpoint.doipServer.DoipServiceInfo; import org.bdware.doip.endpoint.doipServer.Op; import org.bdware.doip.endpoint.doipServer.RepositoryHandlerBase; import org.bdware.sc.ContractClient; -import org.bdware.sc.ContractManager; import org.bdware.sc.bean.ContractRequest; import org.bdware.sc.bean.FunctionDesp; +import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.util.JsonUtil; +import org.bdware.server.action.CMActions; + +import java.util.ArrayList; +import java.util.List; @ChannelHandler.Sharable public class ContractRepositoryHandler extends RepositoryHandlerBase { - // private static final Logger LOGGER = LogManager.getLogger(ContractRepositoryHandler.class); - public static ContractManager cm; public ContractRepositoryHandler(DoipServiceInfo info) { super(info); - cm = ContractManager.instance; } @Override @@ -58,14 +61,63 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase { @Override public DoipMessage handleRetrieve(DoipMessage doipMessage) { - - ContractClient contract = cm.getContractClientByDoi(doipMessage.header.parameters.id); - if (contract == null) + ContractClient client = null; + try { + client = CMActions.manager.getContractClientByDoi(doipMessage.header.parameters.id); + } catch (Exception e) { + } + if (client == null) { + String doid = doipMessage.header.parameters.id; + int off = doid.lastIndexOf("/"); + if (off > 0) + doid = doid.substring(off + 1); + client = CMActions.manager.getContractClientByDoi(doid); + } + if (client == null) { return replyStringWithStatus( doipMessage, "Contract instance not exist!", DoipResponseCode.DoNotFound); - DigitalObject contractDO = contract2DigitalObject(contract); + } + byte[] data = doipMessage.body.getEncodedData(); - return replyDO(doipMessage, contractDO); + if (data == null || data.length == 0) { + DigitalObject contractDO = contract2DigitalObject(client); + return replyDO(doipMessage, contractDO); + } else { + JsonObject jo = JsonUtil.parseStringAsJsonObject(new String(data)); + List result = new ArrayList<>(); + jo.addProperty("contractID", client.contractMeta.getID()); + CMActions.executeContractInternal(jo, new ResultCallback() { + @Override + public void onResult(JsonObject str) { + result.add(str); + synchronized (result) { + result.notify(); + } + } + + @Override + public void onResult(String str) { + throw new IllegalStateException("Can't reach here!"); + } + }, null); + synchronized (result) { + try { + result.wait(15000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + DoipResponseCode retStatus = DoipResponseCode.Success; + if (result.size() == 0) { + result.add(new JsonPrimitive("Timeout!")); + retStatus = DoipResponseCode.MoreThanOneErrors; + } + DigitalObject digitalObject = new DigitalObject(doipMessage.header.parameters.id, DoType.DO); + digitalObject.addAttribute("status", retStatus.getName()); + digitalObject.addAttribute("result", result.get(0)); + + return replyDO(doipMessage, digitalObject); + } } private DigitalObject contract2DigitalObject(ContractClient contractClient) { @@ -83,12 +135,10 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase { @Op(op = BasicOperations.Extension, name = "call") public DoipMessage handleCall(DoipMessage doipMessage) { - - ContractClient cc = cm.getContractClientByDoi(doipMessage.header.parameters.id); + ContractClient cc = CMActions.manager.getContractClientByDoi(doipMessage.header.parameters.id); if (cc == null) return replyStringWithStatus( doipMessage, "Contract instance not exist!", DoipResponseCode.DoNotFound); - // todo transform doipMessage to args JsonObject args = doipMessage.header.parameters.attributes; ContractRequest cr = new ContractRequest(); @@ -120,7 +170,7 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase { } cr.setRequestID(reqID); - String resp = cm.execute(cr, null); + String resp = CMActions.manager.execute(cr, null); // StringContainer sc = new StringContainer(); // SyncContainer sync = new SyncContainer(sc); @@ -128,28 +178,5 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase { return replyString(doipMessage, resp); } - // static class SyncResultCallback extends ResultCallback { - // - // SyncContainer resultContainer; - // public SyncResultCallback(SyncContainer sc){ - // resultContainer = sc; - // } - // @Override - // public synchronized void onResult(String str) { - // resultContainer.sc.str = str; - // resultContainer.sc.notifyAll(); - // } - // - // } - // - // static class SyncContainer{ - // final StringContainer sc; - // public SyncContainer(StringContainer sc){ - // this.sc = sc; - // } - // } - // - // static class StringContainer{ - // String str = null; - // } + } diff --git a/src/main/java/org/bdware/server/doip/ContractRepositoryMain.java b/src/main/java/org/bdware/server/doip/ContractRepositoryMain.java index 0a1300e..a73083a 100644 --- a/src/main/java/org/bdware/server/doip/ContractRepositoryMain.java +++ b/src/main/java/org/bdware/server/doip/ContractRepositoryMain.java @@ -1,121 +1,50 @@ package org.bdware.server.doip; -import com.google.gson.reflect.TypeToken; +import com.nimbusds.jose.jwk.JWK; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.bdware.doip.application.DoipServiceConfig; import org.bdware.doip.core.crypto.GlobalCertifications; +import org.bdware.doip.core.doipMessage.DoipMessageFormat; import org.bdware.doip.core.utils.GlobalConfigurations; -import org.bdware.doip.endpoint.doipServer.*; -import org.bdware.doip.endpoint.irpClient.GlobalIrpClient; -import org.bdware.sc.ContractManager; -import org.bdware.sc.util.JsonUtil; +import org.bdware.doip.endpoint.doipServer.DoipListenerInfo; +import org.bdware.doip.endpoint.doipServer.DoipServerImpl; +import org.bdware.doip.endpoint.doipServer.DoipServiceInfo; +import org.bdware.server.DOAConf; import org.bdware.server.GlobalConf; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import java.security.Security; +import java.util.ArrayList; import java.util.List; public class ContractRepositoryMain { private static final Logger LOGGER = LogManager.getLogger(ContractRepositoryMain.class); - /** - * Default DOIP Service Information - */ - // static String configFilePath = "doip_config.json"; - public static String localListener; - public static String repoID = ""; - public static String serviceDescription = "test Contract Repository"; - public static String serviceName = "ContractEngine"; - public static String type; - public static DoipServiceInfo doipServiceInfo; + static DoipServerImpl currentServer; - public static void start(String url) { - DoipServiceConfig remoteConfig; - //to start DOIP service - localListener = "[{\"url\":\"" + url + "\",\"protocolVersion\":\"2.1\",\"messageFormat\":\"packet\"}]"; - //to register in LHS - String remoteListener = localListener; + public static void start() { try { - String configStr = GlobalConf.getDOIPConfig(); - if (configStr == null || configStr.equals("{}") || configStr.equals("")) - throw new Exception("empty configStr"); - remoteConfig = JsonUtil.fromJson(configStr, DoipServiceConfig.class); - if (null != remoteConfig.LHSProxyAddress) { - GlobalConfigurations.LHS_Address = remoteConfig.LHSProxyAddress; + String[] ipAndPort = GlobalConf.instance.masterAddress.split(":"); + String url = String.format("tcp://%s:%d", ipAndPort[0], Integer.valueOf(ipAndPort[1]) + 1); + String doid = DOAConf.repoDoid; + LOGGER.info("DOIPServer start:" + url); + if (url == null || doid == null) { + LOGGER.warn("missing args, failed to start! url:" + url + " doid:" + doid); + return; } - if (null != remoteConfig.ownerHandle) { - GlobalConfigurations.User_Handle = remoteConfig.ownerHandle; + if (currentServer != null) { + currentServer.stop(); } - if (null != remoteConfig.certPath) { - GlobalConfigurations.certPath = remoteConfig.certPath; - } - if (null != remoteConfig.certPassword) { - GlobalConfigurations.certPassword = remoteConfig.certPassword; - } - //doip Service config - serviceDescription = remoteConfig.serviceDescription; - serviceName = remoteConfig.serviceName; - remoteListener = remoteConfig.listeners; - GlobalConfigurations.DoipServiceID = repoID = remoteConfig.repoID; - type = remoteConfig.type; - } catch (Exception ignored) { - LOGGER.warn("load doip config json exception, use static config"); - remoteConfig = new DoipServiceConfig(); - //doip Service config - remoteConfig.serviceDescription = serviceDescription; - remoteConfig.serviceName = serviceName; - remoteConfig.listeners = remoteListener; - remoteConfig.ownerHandle = GlobalConfigurations.User_Handle; - remoteConfig.repoID = repoID; - remoteConfig.type = type; - - //LHS config - remoteConfig.LHSProxyAddress = GlobalConfigurations.LHS_Address; - - //key config - remoteConfig.certPassword = GlobalConfigurations.certPassword; - remoteConfig.certPath = GlobalConfigurations.certPath; - } - - - try { - init(); - //use local listener to initial doipservice info - doipServiceInfo = new DoipServiceInfo( - remoteConfig.repoID, - remoteConfig.ownerHandle, - remoteConfig.type, - JsonUtil.fromJson(localListener, new TypeToken>() { - }.getType())); - doipServiceInfo.serviceName = remoteConfig.serviceName; - doipServiceInfo.serviceDescription = remoteConfig.serviceDescription; - - DoipServer server = DoipServerImpl.createDoipServer(doipServiceInfo); - RepositoryHandler repositoryHandler = new ContractRepositoryHandler(doipServiceInfo); - server.setRepositoryHandler(repositoryHandler); - server.start(); - //change listener to public address in remote config after start (本地端口 - 远程端口 映射) - doipServiceInfo.listenerInfos = - JsonUtil.fromJson(remoteConfig.listeners, new TypeToken>() { - }.getType()); + List infos = new ArrayList<>(); + infos.add(new DoipListenerInfo(url, "2.1", DoipMessageFormat.PACKET)); + GlobalCertifications.jwKeyPair = JWK.parse("{\"kty\":\"EC\",\"d\":\"wMrGJjk877bKQ_AAvdb8DM1XpUFo6POSLYDXid6AfBw\",\"use\":\"sig\",\"crv\":\"P-256\",\"kid\":\"AIBD\\/dou.ADMIN\",\"x\":\"N0TydMwdnvkyHrXVh1zfc9_7DV6tRqfCGElhywzXJYo\",\"y\":\"rX5pGGML9efP2r8hoMSwxaR9gwVHmqaldsG-yfE_eUI\"}"); + GlobalConfigurations.userID = GlobalCertifications.jwKeyPair.getKeyID(); + DoipServiceInfo info = new DoipServiceInfo(doid, GlobalConfigurations.userID, "ContractRepo", infos); + currentServer = new DoipServerImpl(info); + currentServer.setRepositoryHandler(new ContractRepositoryHandler(info)); + currentServer.start(); } catch (Exception e) { - LOGGER.error("start doip repo failed! " + e.getMessage()); e.printStackTrace(); - } - ContractManager.doipConfigurer = new ContractRepoConfigurer(doipServiceInfo, remoteConfig); - GlobalConf.resetDOIPConfig(JsonUtil.toJson(remoteConfig)); - } - - public static void init() throws Exception { - if (Security.getProvider("BC") == null) { - Security.addProvider(new BouncyCastleProvider()); + LOGGER.warn("load doip config exception!"); } - GlobalCertifications.loadKeysFromJKS(GlobalConfigurations.certPath, GlobalConfigurations.certPassword); - - GlobalIrpClient.useInternalIrpClient(GlobalCertifications.localKeypair, - GlobalConfigurations.User_Handle, - GlobalConfigurations.LHS_Address); } } diff --git a/src/main/java/org/bdware/server/doip/ContractRepositoryServer.java b/src/main/java/org/bdware/server/doip/ContractRepositoryServer.java new file mode 100644 index 0000000..100e8b1 --- /dev/null +++ b/src/main/java/org/bdware/server/doip/ContractRepositoryServer.java @@ -0,0 +1,5 @@ +package org.bdware.server.doip; + +public class ContractRepositoryServer { + +} diff --git a/src/main/java/org/bdware/server/http/CMHttpHandler.java b/src/main/java/org/bdware/server/http/CMHttpHandler.java index 286b5d4..1618878 100644 --- a/src/main/java/org/bdware/server/http/CMHttpHandler.java +++ b/src/main/java/org/bdware/server/http/CMHttpHandler.java @@ -352,8 +352,7 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - LOGGER.warn("catch exception in " + this + ": " + cause.getClass().getSimpleName()); - cause.printStackTrace(); -// ctx.close(); + LOGGER.warn("catch exception in " + this + ": " + cause.getClass().getSimpleName() + " " + ExceptionUtil.exceptionToString(cause)); + // ctx.close(); } } diff --git a/src/test/java/org/bdware/server/DOIPTest.java b/src/test/java/org/bdware/server/DOIPTest.java index db6062f..79ca8ee 100644 --- a/src/test/java/org/bdware/server/DOIPTest.java +++ b/src/test/java/org/bdware/server/DOIPTest.java @@ -1,41 +1,54 @@ package org.bdware.server; -import org.bdware.doip.application.client.ContractDOAClient; import org.bdware.doip.core.doipMessage.DoipMessage; -import org.bdware.doip.core.model.handleRecord.DoHandleRecord; -import org.bdware.doip.core.utils.GlobalConfigurations; -import org.bdware.doip.endpoint.irpClient.GlobalIrpClient; +import org.bdware.doip.core.doipMessage.DoipMessageFactory; +import org.bdware.doip.core.model.operations.BasicOperations; +import org.bdware.doip.endpoint.doipClient.DoipClientImpl; +import org.bdware.doip.endpoint.doipClient.DoipMessageCallback; import org.junit.Before; import org.junit.Test; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + public class DOIPTest { public static String repoID = "86.5000.470/doip.localContractRepo"; - ContractDOAClient client; + @Before public void init() { - client = ContractDOAClient.getContractDOAClientForTest(); } @Test public void registryTempOD() { - try { - DoHandleRecord doHandleRecord = - new DoHandleRecord(GlobalConfigurations.User_Handle, repoID); - String doi = GlobalIrpClient.getGlobalClient().register(doHandleRecord); - GlobalIrpClient.getGlobalClient().register(doHandleRecord); - System.out.println("[DOI]:" + doi); - // GlobalIrpClient.getGlobalClient().reRegister(doHandleRecord); - } catch (Exception e) { - e.printStackTrace(); - } + } @Test public void retrieve() { try { + DoipClientImpl doipClient = new DoipClientImpl(); + doipClient.connect("tcp://127.0.0.1:18002"); //86.5000.470/do.Yie0yPsjt4_bdw - DoipMessage result = client.retrieve("86.5000.470/do.LoRovvDgg0_bdw", null, false); + List ret = new ArrayList<>(); + DoipMessage msg = (new DoipMessageFactory.DoipMessageBuilder()).createRequest("86.5000.470/Counter", BasicOperations.Retrieve.getName()) + .setBody("{\"operation\":\"count\",\"arg\":\"\"}".getBytes(StandardCharsets.UTF_8)).create(); + doipClient.sendMessage(msg, new DoipMessageCallback() { + @Override + public void onResult(DoipMessage doipMessage) { + ret.add(doipMessage); + synchronized (ret) { + ret.notify(); + } + } + }); + synchronized (ret) { + ret.wait(5000); + } + DoipMessage result = null; + if (ret.size() > 0) + result = ret.get(0); System.out.println(result.body.getDataAsJsonString()); // GlobalIrpClient.getGlobalClient().reRegister(doHandleRecord); } catch (Exception e) { @@ -45,12 +58,6 @@ public class DOIPTest { @Test public void call() { - try { - DoipMessage result = client.call("86.5000.470/do.LoRovvDgg0_bdw", "count", "".getBytes()); - System.out.println(result.body.getDataAsJsonString()); - // GlobalIrpClient.getGlobalClient().reRegister(doHandleRecord); - } catch (Exception e) { - e.printStackTrace(); - } + } }