mirror of
https://gitee.com/BDWare/contract-java-example.git
synced 2025-01-09 17:34:10 +00:00
release
This commit is contained in:
parent
905b06be39
commit
6b21c7ff7c
124
README.md
124
README.md
@ -1,116 +1,12 @@
|
||||
# contract-java-example
|
||||
# GD项目的标识解析系统
|
||||
|
||||
## 介绍
|
||||
## 用况
|
||||
1. 基于IRP的全网标识解析(无权限控制): 可配置scheme和前缀pre。在默认不使用scheme下,可解析pre/name格式的标识。对应地是在本地的数据库的app表中。
|
||||
2. 授权的标识解析:解析结果包含数据库/用户名密码等信息。(基于name,通过文件系统找到数据库配置)。
|
||||
3. 组网: 可与公网的标识解析系统组起来。
|
||||
|
||||
idea开发合约的示例。
|
||||
|
||||
## 测试环境配置
|
||||
|
||||
1. 在本地准备docker测试环境。
|
||||
```bash
|
||||
cd bdserver-docker-compose
|
||||
docker-compose up -d
|
||||
cat bdcontract/manager.keypair
|
||||
#并复制这组{"publickey".."privateKey"}
|
||||
```
|
||||
2. 打开浏览器`http://127.0.0.1:21030/NodePortal.html`。点击右上角`欢迎04xx`按钮,将步骤1中的keyPair复制,并点`导入密钥`。
|
||||
|
||||
## 开发环境配置
|
||||
|
||||
可安装idea插件:`ideaplugin/yjs-formater-1.0-SNAPSHOT-1653060411648.zip`
|
||||
用于格式化yjs文件和自动补全。
|
||||
|
||||
## 在本机调试运行
|
||||
|
||||
1.修改debugconf.json,将cpHost改为从docker可访问的域名或ip。
|
||||
|
||||
```
|
||||
在MAC/Linux环境下,可使用ifconfig | grep inet ,查看本地局域网ip,并配置到cpHost字段。
|
||||
在Windows环境下,可使用"cpHost":"host.docker.internal"。
|
||||
其中host.docker.internal是docker中内置的一个域名,可用于访问host。
|
||||
https://docs.docker.com/desktop/windows/networking/
|
||||
```
|
||||
|
||||
示例的debugconf.json配置:
|
||||
|
||||
```json
|
||||
{
|
||||
"agentAddress": "127.0.0.1:21030",
|
||||
"publicKey": "04180354fdb6507f8ab98ccfbe165ce11da74ba733f81af86ad6d32216b32cf4f797c559d50ceeefbf4c760c3483840471c67471b90acdffb388cd7d496d9a1610",
|
||||
"privateKey": "1d4196947f59532db6f8f4055e58474a48db8f30b476ae3edc66406464521b3b",
|
||||
"ypkPath": "./backend/build/contractexample-1.3.0.ypk",
|
||||
"killBeforeStart": "ContractExample",
|
||||
"createParam": {
|
||||
},
|
||||
"cpHost": "host.docker.internal"
|
||||
}
|
||||
```
|
||||
|
||||
2.启动测试用例:
|
||||
|
||||
```
|
||||
test/java/HelloTest.run
|
||||
```
|
||||
|
||||
注意run方法中的`for (;;);`用于防止测试用例退出。
|
||||
在windows中可能影响其他测试用例运行。可编写`public static void main(String[] args)`去运行合约。
|
||||
|
||||
3.带UI的ypk调试
|
||||
由于bdcontract会根据启动参数中的ypkPath去解析ypk文件中的资源文件,因此,当需要通过`http://xxx:xx/DOIP/ContractID`这种形式去访问静态资源时,
|
||||
需要配置ypk路径映射。
|
||||
一种做法是:
|
||||
|
||||
1) 在./bdserver-docker-compose目录下,在启动之后,会生成一个文件`./bdcontract/BDWareProjectDir`。将该目录映射至./backend目录下或是backend的上级目录下。
|
||||
|
||||
```
|
||||
cd 至backend
|
||||
ln -s /absolute/path/to/BDWareProjectDir ./
|
||||
```
|
||||
|
||||
2) 修改DebugMain的启动路径为BDWareProjectDir所在目录。
|
||||
|
||||
3) 修改debugconf.json中的ypkPath,使用相对路径的形式`./BDWareProjectDir/xxx`。
|
||||
|
||||
4) 注意需要将编译好的ypk放至BDWareProjectDir中。可编写一个新的gradle task完成脚本化复制。如:
|
||||
|
||||
```
|
||||
task copyToBDWareProjectDir(type: Copy) {
|
||||
from "./build/contractexample-${currVersion}.ypk"
|
||||
into "../bdserver-docker-compose/bdcontract/BDWareProjectDir/"
|
||||
}
|
||||
```
|
||||
|
||||
## 在docker内调试运行
|
||||
|
||||
打开镜像的`NodePortal.html`页面,以ypk的形式启动。
|
||||
在启动时,增加`remoteDebugPort`,注意远程调试的端口需要在镜像中映射出来。
|
||||
可使用docker镜像默认映射端口范围`21050-21100`,例如`21058`。
|
||||
而后即可通过jdwp可进行远程调试。 如果使用`idea`作为开发环境,则可搜索`idea java remote debug`,查看相关教程。
|
||||
NodePortal.html可参考:[BDContract管理页面](https://public.internetapi.cn/docs/bdcontract/doc/IDEUsage.html)
|
||||
|
||||
## 部署运行
|
||||
|
||||
部署至远程服务端执行":backend:deploy"任务:
|
||||
即执行./backend/build.gradle 中的 deploy。
|
||||
|
||||
## 前端sdk说明
|
||||
|
||||
1. 如何使用javascript sdk
|
||||
2. 如何使用typescript sdk
|
||||
3. 示例:使用vite/vue/...等框架
|
||||
3. 如何配置成前后端独立连接的
|
||||
4. 如何配置成前后端一体化
|
||||
|
||||
## 模拟后端数据
|
||||
|
||||
## 后端常用方法说明
|
||||
|
||||
## 调用相同CP的yjs代码
|
||||
|
||||
参考:
|
||||
Hello.callYJSInSameCP
|
||||
|
||||
## 调用其他CP的yjs代码
|
||||
|
||||
参考:
|
||||
Hello.callYJSInOtherCP
|
||||
## 对接接口
|
||||
HTTP接口
|
||||
`
|
||||
http://112.74.48.247:21030/SCIDE/SCManager?action=executeContract&contractID=GDRouter&operation=resolve&arg={"token":"correcttoken","doid":"bdtest.gd/dddd"}&pubkey=04861a7760f83418a04508877155e302c0af65acc8aa16cfb44de11fce6b564616a2eb92231de9788e0b4a7d7c27bd3b23a95024c70c702a6360f98f0a9d89e166&signature=3045022100b7382a653159517239a984f0ae8b2f5072ae6709fcd11ba72473d1a84aeb817202200fac8e24bde04e81227f238e8d142e48d8b5dfd273f165ec299f0784a95bb650
|
||||
`
|
1
backend/.gitignore
vendored
1
backend/.gitignore
vendored
@ -1,4 +1,5 @@
|
||||
/.DS_Store/
|
||||
debugconf.json
|
||||
ContractDB
|
||||
/build/
|
||||
/cplibs/
|
||||
|
@ -39,6 +39,9 @@ sourceSets {
|
||||
dependencies {
|
||||
api 'org.apache.logging.log4j:log4j-core:2.17.2'
|
||||
api 'org.apache.logging.log4j:log4j-api:2.17.2'
|
||||
implementation 'org.postgresql:postgresql:42.5.4'
|
||||
implementation 'org.bdware.doip:irp-sdk:1.1.3'
|
||||
|
||||
implementation 'org.bdware.sc:cp:1.6.8'
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
}
|
||||
@ -63,16 +66,16 @@ task copyAssets(type: Copy) {
|
||||
}
|
||||
|
||||
task copyJar(type: Copy, dependsOn: [":backend:jar", ":backend:copyLibs"]) {
|
||||
from "./build/libs/$project.name-${project.version}.jar"
|
||||
from "./build/libs/backend.jar"
|
||||
into "./build/output"
|
||||
rename { String fileName -> "sc-example.jar" }
|
||||
rename { String fileName -> "gdrouter.jar" }
|
||||
doFirst {
|
||||
println "copyJar start"
|
||||
}
|
||||
}
|
||||
def reltivePath = "./backend"
|
||||
//reltivePath="."
|
||||
def currVersion = "1.3.2"
|
||||
def currVersion = "0.0.1"
|
||||
task grepCP(dependsOn: ["copyJar"]) {
|
||||
doLast {
|
||||
org.bdware.datanet.YPKPacker.grepJarByCPVersion("${reltivePath}/build/output/libs", org.bdware.datanet.CPVersion.cp_1_6_8)
|
||||
@ -86,17 +89,17 @@ tasks.processTestResources.setDuplicatesStrategy(DuplicatesStrategy.INCLUDE)
|
||||
task buildZip(type: Zip, dependsOn: ["copyAssets", "copyJar", "copyYJS", "grepCP"]) {
|
||||
from './build/output/'
|
||||
duplicatesStrategy = DuplicatesStrategy.INCLUDE
|
||||
archiveFileName = 'contractexample.zip'
|
||||
archiveFileName = 'gdrouter.zip'
|
||||
destinationDirectory = file('build/')
|
||||
}
|
||||
|
||||
task buildYPK(dependsOn: ["buildZip"]) {
|
||||
doLast {
|
||||
org.bdware.datanet.YPKPacker.staticPack("${reltivePath}/build/contractexample.zip", "${reltivePath}/build/contractexample-${currVersion}.ypk")
|
||||
org.bdware.datanet.YPKPacker.staticPack("${reltivePath}/build/gdrouter.zip", "${reltivePath}/build/gdrouter-${currVersion}.ypk")
|
||||
}
|
||||
}
|
||||
task deploy(dependsOn: ["buildYPK"]) {
|
||||
doLast {
|
||||
org.bdware.ypkdeploy.HTTPTool.deployWithYpk("${reltivePath}/debugconf.json", "${reltivePath}/build/contractexample-${currVersion}.ypk")
|
||||
org.bdware.ypkdeploy.HTTPTool.deployWithYpk("${reltivePath}/debugconf.json", "${reltivePath}/build/gdrouter-${currVersion}.ypk")
|
||||
}
|
||||
}
|
@ -1,10 +0,0 @@
|
||||
{
|
||||
"agentAddress": "127.0.0.1:21030",
|
||||
"publicKey": "04180354fdb6507f8ab98ccfbe165ce11da74ba733f81af86ad6d32216b32cf4f797c559d50ceeefbf4c760c3483840471c67471b90acdffb388cd7d496d9a1610",
|
||||
"privateKey": "1d4196947f59532db6f8f4055e58474a48db8f30b476ae3edc66406464521b3b",
|
||||
"ypkPath": "./build/contractexample-1.3.0.ypk",
|
||||
"killBeforeStart": "ContractExample",
|
||||
"createParam": {
|
||||
},
|
||||
"cpHost": "host.docker.internal"
|
||||
}
|
19
backend/debugconf.json.template
Normal file
19
backend/debugconf.json.template
Normal file
@ -0,0 +1,19 @@
|
||||
{
|
||||
"agentAddress": "112.74.48.247:21030",
|
||||
"publicKey": "...",
|
||||
"privateKey": "...",
|
||||
"ypkPath": "./build/gdrouter-0.0.1.ypk",
|
||||
"killBeforeStart": "GDRouter",
|
||||
"createParam": {
|
||||
"upperRouter": "tcp://",
|
||||
"ip": "112.74.48.247",
|
||||
"prefix": "bdtest.gd",
|
||||
"scheme": "irp",
|
||||
"port": 21044,
|
||||
"dbUrl": "jdbc:postgresql://piandportofbass/bdwaas_web",
|
||||
"dbUserName": "name",
|
||||
"dbPwd": "pwd",
|
||||
"token": "abc"
|
||||
},
|
||||
"cpHost2": "host.docker.internal"
|
||||
}
|
@ -0,0 +1,210 @@
|
||||
package org.bdware.sc.contractexample;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.bdware.irp.irplib.core.IrpMessage;
|
||||
import org.bdware.irp.irplib.core.IrpMessageCode;
|
||||
import org.bdware.irp.irplib.core.IrpRequest;
|
||||
import org.bdware.irp.irplib.core.IrpResponse;
|
||||
import org.bdware.irp.irpserver.IrpHandler;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.sql.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class IrsHandler implements IrpHandler {
|
||||
static Logger LOGGER = LogManager.getLogger(IrsHandler.class);
|
||||
private final Resolver resolver;
|
||||
|
||||
public IrsHandler(Resolver resolver) {
|
||||
this.resolver = resolver;
|
||||
}
|
||||
|
||||
private Map<String, String> jsonToMap(JsonObject result) {
|
||||
Map<String, String> ret = new HashMap<>();
|
||||
for (String key : result.keySet()) ret.put(key, result.get(key).toString());
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
//TODO RETURN newDelegateRouterResponse instead
|
||||
@Override
|
||||
public IrpMessage batchCreateDOID(IrpMessage request) {
|
||||
return IrpResponse.newErrorResponse(IrpMessageCode.OC_BATCH_CREATE_DOID, IrpMessageCode.RC_ERROR, "unsupported operation");
|
||||
}
|
||||
|
||||
//for any input, fix it to scheme://prefix/suffix format.
|
||||
public String fixScheme(String doid) {
|
||||
if (!doid.contains(":")) {
|
||||
doid = resolver.config.scheme + ":" + "//" + doid;
|
||||
} else {
|
||||
if (doid.contains(":") && !doid.contains(":/"))
|
||||
doid = doid.replace(":", "://");
|
||||
if (doid.contains(":/") && !doid.contains("://")) {
|
||||
doid = doid.replace(":/", "://");
|
||||
}
|
||||
}
|
||||
return doid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage resolveDOID(IrpMessage request) {
|
||||
try {
|
||||
LOGGER.info(request);
|
||||
IrpRequest req = (IrpRequest) request;
|
||||
String doid = req.getDoid();
|
||||
// support old resolve request in irp-sdk 1.0.1
|
||||
doid = fixScheme(doid);
|
||||
if (!doid.matches(".*://.*")) {
|
||||
return IrpResponse.newErrorResponse(IrpMessageCode.OC_RESOLUTION_DOID, IrpMessageCode.RC_ERROR, "unknown scheme");
|
||||
} else {
|
||||
String[] domainAndID = doid.split("://");
|
||||
if (domainAndID[0].equals(resolver.config.scheme)) {
|
||||
String[] prefixAndSufix = domainAndID[1].split("/");
|
||||
if (prefixAndSufix[0].equals(resolver.config.prefix)) {
|
||||
JsonObject jsonObject = resolveInternal(prefixAndSufix[1]);
|
||||
//TODO connect and respon.
|
||||
Map<String, String> keypair = new HashMap<>();
|
||||
for (String key : jsonObject.keySet()) {
|
||||
if (!key.equals("sm2keypair"))
|
||||
keypair.put(key, jsonObject.get(key).toString());
|
||||
}
|
||||
return IrpResponse.newIrsResolveResponse(domainAndID[1], keypair);
|
||||
} else
|
||||
return IrpResponse.newDelegateRouterResponse(resolver.config.upperRouter);
|
||||
} else {
|
||||
return IrpResponse.newDelegateRouterResponse(resolver.config.upperRouter);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return IrpResponse.newErrorResponse(IrpMessageCode.OC_RESOLUTION_DOID, IrpMessageCode.RC_ERROR, fromException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] fromException(Exception e) {
|
||||
ByteArrayOutputStream bo = new ByteArrayOutputStream();
|
||||
e.printStackTrace(new PrintStream(bo));
|
||||
return bo.toByteArray();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public IrpMessage createDOID(IrpMessage request) {
|
||||
return IrpResponse.newErrorResponse(IrpMessageCode.OC_CREATE_DOID, IrpMessageCode.RC_ERROR, "unsupported operation");
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage updateDOID(IrpMessage request) {
|
||||
return IrpResponse.newErrorResponse(IrpMessageCode.OC_UPDATE_DOID, IrpMessageCode.RC_ERROR, "unsupported operation");
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage deleteDOID(IrpMessage request) {
|
||||
return IrpResponse.newErrorResponse(IrpMessageCode.OC_DELETE_DOID, IrpMessageCode.RC_ERROR, "unsupported operation");
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage verifyIrs(IrpMessage request) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage resolvePrefix(IrpMessage request) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage createPrefix(IrpMessage request) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage updatePrefix(IrpMessage request) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage deletePrefix(IrpMessage request) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage verifyChildRouter(IrpMessage request) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IrpMessage queryIdentifierByOffset(IrpMessage request) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public JsonObject resolveInternal(String appName) {
|
||||
try {
|
||||
//load info from db
|
||||
Connection conn = Storage.instance.getDBConnection();
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet result = stmt.executeQuery("select * from app where name = '" + appName + "';");
|
||||
JsonObject ele = parseFirstElementInResultSet(result);
|
||||
result.close();
|
||||
if (ele == null) {
|
||||
return null;
|
||||
}
|
||||
ele.remove("cover");
|
||||
System.out.println("[GDRouter] resolve step1:" + ele.toString());
|
||||
|
||||
stmt = conn.createStatement();
|
||||
result = stmt.executeQuery("select * from contract where \"appId\" = " + ele.get("id").getAsInt() + ";");
|
||||
JsonObject ele2 = parseFirstElementInResultSet(result);
|
||||
result.close();
|
||||
if (ele2 != null && ele2.has("name"))
|
||||
ele.add("contractName", ele2.get("name"));
|
||||
System.out.println("[GDRouter] resolve step2:" + ele.toString());
|
||||
return ele;
|
||||
} catch (Exception e) {
|
||||
ByteArrayOutputStream bo = new ByteArrayOutputStream();
|
||||
e.printStackTrace(new PrintStream(bo));
|
||||
JsonObject result = new JsonObject();
|
||||
result.addProperty("msg", new String(bo.toByteArray()));
|
||||
System.out.println("[GDRouter] resolve exception:" + result.toString());
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private JsonObject parseFirstElementInResultSet(ResultSet result) throws SQLException {
|
||||
ResultSetMetaData meta = result.getMetaData();
|
||||
boolean hasElement = result.next();
|
||||
if (!hasElement) {
|
||||
return null;
|
||||
}
|
||||
JsonObject ele = new JsonObject();
|
||||
for (int j = 1; j <= meta.getColumnCount(); j++) {
|
||||
int type = meta.getColumnType(j);
|
||||
switch (type) {
|
||||
case -6:
|
||||
case 5:
|
||||
case 4:
|
||||
ele.addProperty(meta.getColumnName(j), result.getInt(j));
|
||||
break;
|
||||
case -5:
|
||||
ele.addProperty(meta.getColumnName(j), result.getLong(j));
|
||||
break;
|
||||
case 6:
|
||||
case 7:
|
||||
case 8:
|
||||
ele.addProperty(meta.getColumnName(j), result.getDouble(j));
|
||||
break;
|
||||
default:
|
||||
ele.addProperty(meta.getColumnName(j), result.getString(j));
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
return ele;
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package org.bdware.sc.contractexample;
|
||||
|
||||
public class ResolveConfig {
|
||||
String upperRouter;
|
||||
String ip;
|
||||
|
||||
String prefix;
|
||||
String scheme;
|
||||
int port;
|
||||
String dbUrl;
|
||||
String dbUserName;
|
||||
String dbPwd;
|
||||
public String token;
|
||||
}
|
@ -0,0 +1,177 @@
|
||||
package org.bdware.sc.contractexample;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.bdware.irp.irpserver.IrpListenerInfo;
|
||||
import org.bdware.irp.irpserver.IrpServerImpl;
|
||||
import org.bdware.irp.irpserver.IrpServerInfo;
|
||||
import org.bdware.sc.boundry.utils.SQLUtil;
|
||||
import org.bdware.sc.engine.JSONTool;
|
||||
import org.bdware.sc.util.JsonUtil;
|
||||
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.PrintStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Resolver {
|
||||
static Logger LOGGER = LogManager.getLogger(Resolver.class);
|
||||
private IrsHandler testIrsHandler;
|
||||
|
||||
public Resolver(ResolveConfig config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public static Resolver instance;
|
||||
|
||||
public static Resolver main(ScriptObjectMirror obj) {
|
||||
|
||||
if (Storage.instance == null) {
|
||||
|
||||
}
|
||||
JsonObject jo = JSONTool.convertMirrorToJson(obj).getAsJsonObject();
|
||||
ResolveConfig config = JsonUtil.fromJson(jo.toString(), ResolveConfig.class);
|
||||
instance = new Resolver(config);
|
||||
instance.initAndStartServer();
|
||||
return instance;
|
||||
}
|
||||
|
||||
public ResolveConfig config;
|
||||
|
||||
public static JsonObject resolve(String name) {
|
||||
try {
|
||||
name = instance.testIrsHandler.fixScheme(name);
|
||||
String[] schemeAndID = name.split("://");
|
||||
System.out.println("[GDResolver] " + name + " --> " + schemeAndID.length);
|
||||
if (!schemeAndID[0].equals(instance.config.scheme)) {
|
||||
JsonObject ret = new JsonObject();
|
||||
ret.addProperty("msg", "unknown scheme, need delegate!");
|
||||
ret.addProperty("doid", name);
|
||||
ret.addProperty("code", 1);
|
||||
return ret;
|
||||
} else {
|
||||
if (schemeAndID[1].startsWith(instance.config.prefix + "/")) {
|
||||
String appName = schemeAndID[1].split("/")[1];
|
||||
JsonObject resolveResult = instance.testIrsHandler.resolveInternal(appName);
|
||||
if (resolveResult == null) {
|
||||
resolveResult = new JsonObject();
|
||||
resolveResult.addProperty("code", 2);
|
||||
resolveResult.addProperty("msg", "can't resolve:" + appName);
|
||||
return resolveResult;
|
||||
}
|
||||
if (resolveResult != null && resolveResult.has("contractName")) {
|
||||
String contractName = resolveResult.get("contractName").getAsString();
|
||||
String key = resolveResult.get("sm2keypair").getAsString();
|
||||
String publicKey = JsonParser.parseString(key).getAsJsonObject().get("publicKey").getAsString();
|
||||
File findDir = findDir(contractName, publicKey);
|
||||
File sqlConf = new File(findDir, "sql.conf");
|
||||
if (sqlConf.exists()) {
|
||||
JsonElement jo = JsonParser.parseReader(new FileReader(sqlConf));
|
||||
resolveResult.add("dbInfo", jo);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
resolveResult.addProperty("code", 0);
|
||||
return resolveResult;
|
||||
} else {
|
||||
JsonObject ret = new JsonObject();
|
||||
ret.addProperty("msg", "unknown prefix, need delegate!");
|
||||
ret.addProperty("doid", name);
|
||||
ret.addProperty("code", 1);
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
JsonObject ret = new JsonObject();
|
||||
ret.addProperty("msg", new String(IrsHandler.fromException(e)));
|
||||
ret.addProperty("doid", name);
|
||||
ret.addProperty("code", 1);
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
private static File findDir(String contractName, String publicKey) {
|
||||
File f = new File("/bdcontract/BDWareProjectDir/private");
|
||||
if (f.exists()) {
|
||||
File dir = new File(f, publicKey);
|
||||
if (dir.exists()) {
|
||||
dir = new File(dir, contractName);
|
||||
return dir;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static ResolveConfig getConfig() {
|
||||
return instance.config;
|
||||
}
|
||||
|
||||
|
||||
public static String peekDB(ScriptObjectMirror obj) {
|
||||
try {
|
||||
JsonObject jo = JSONTool.convertMirrorToJson(obj).getAsJsonObject();
|
||||
Connection conn = SQLUtil.getConnection(instance.config.dbUrl, instance.config.dbUserName, instance.config.dbPwd);
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet result = stmt.executeQuery("select * from app ;");
|
||||
ResultSetMetaData meta = result.getMetaData();
|
||||
JsonArray array = new JsonArray();
|
||||
for (; result.next(); ) {
|
||||
JsonObject ele = new JsonObject();
|
||||
array.add(ele);
|
||||
for (int j = 1; j <= meta.getColumnCount(); j++) {
|
||||
int type = meta.getColumnType(j);
|
||||
switch (type) {
|
||||
case -6:
|
||||
case 5:
|
||||
case 4:
|
||||
ele.addProperty(meta.getColumnName(j), result.getInt(j));
|
||||
break;
|
||||
case -5:
|
||||
ele.addProperty(meta.getColumnName(j), result.getLong(j));
|
||||
break;
|
||||
case 6:
|
||||
case 7:
|
||||
case 8:
|
||||
ele.addProperty(meta.getColumnName(j), result.getDouble(j));
|
||||
break;
|
||||
default:
|
||||
ele.addProperty(meta.getColumnName(j), result.getString(j));
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return array.toString();
|
||||
} catch (Exception e) {
|
||||
ByteArrayOutputStream bo = new ByteArrayOutputStream();
|
||||
e.printStackTrace(new PrintStream(bo));
|
||||
return new String(bo.toByteArray());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void initAndStartServer() {
|
||||
//init irpserver
|
||||
IrpListenerInfo listenerInfo = new IrpListenerInfo(config.ip, config.port, "TCP");
|
||||
List<IrpListenerInfo> listenerInfos = new ArrayList<>();
|
||||
listenerInfos.add(listenerInfo);
|
||||
IrpServerInfo info = new IrpServerInfo("bdware", "no description", listenerInfos);
|
||||
IrpServerImpl server = new IrpServerImpl(info);
|
||||
testIrsHandler = new IrsHandler(this);
|
||||
|
||||
server.setIrpServerHandler(testIrsHandler);
|
||||
server.start();
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package org.bdware.sc.contractexample;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import org.bdware.sc.boundry.utils.RocksDBUtil;
|
||||
import org.bdware.sc.boundry.utils.SQLUtil;
|
||||
import org.rocksdb.RocksIterator;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.sql.Connection;
|
||||
|
||||
public class Storage {
|
||||
static {
|
||||
SQLUtil.initDriver("org.postgresql.Driver");
|
||||
}
|
||||
|
||||
public static Storage instance = new Storage();
|
||||
public RocksDBUtil grsStorage = RocksDBUtil.loadDB("./grsTable", false);
|
||||
Connection conn;
|
||||
|
||||
public Connection getDBConnection() {
|
||||
ResolveConfig resolveConfig = Resolver.getConfig();
|
||||
try {
|
||||
if (instance.conn != null && instance.conn.isValid(2)) {
|
||||
return instance.conn;
|
||||
}
|
||||
instance.conn = SQLUtil.getConnection(resolveConfig.dbUrl, resolveConfig.dbUserName, resolveConfig.dbPwd);
|
||||
return instance.conn;
|
||||
} catch (Exception e) {
|
||||
instance.conn = SQLUtil.getConnection(resolveConfig.dbUrl, resolveConfig.dbUserName, resolveConfig.dbPwd);
|
||||
return instance.conn;
|
||||
}
|
||||
}
|
||||
|
||||
public JsonObject peekDB() {
|
||||
RocksIterator iter = grsStorage.newIterator();
|
||||
JsonObject ret = new JsonObject();
|
||||
try {
|
||||
for (iter.seekToFirst(); iter.isValid(); iter.next()) {
|
||||
String jsonStr = new String(iter.value());
|
||||
ret.addProperty(new String(iter.key()), jsonStr);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
ret.addProperty("result", "failed");
|
||||
ByteArrayOutputStream bo = new ByteArrayOutputStream();
|
||||
e.printStackTrace(new PrintStream(bo));
|
||||
ret.addProperty("errorMessage", bo.toString());
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
22
backend/src/test/java/IrpTest.java
Normal file
22
backend/src/test/java/IrpTest.java
Normal file
@ -0,0 +1,22 @@
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.bdware.irp.client.IrpClientImpl;
|
||||
import org.bdware.irp.exception.IrpClientException;
|
||||
import org.bdware.irp.stateinfo.StateInfoBase;
|
||||
import org.junit.Test;
|
||||
|
||||
public class IrpTest {
|
||||
static Logger LOGGER = LogManager.getLogger(IrpTest.class);
|
||||
|
||||
@Test
|
||||
public void resolve() {
|
||||
IrpClientImpl client = new IrpClientImpl();
|
||||
client.connect("tcp://112.74.48.247:21044");
|
||||
try {
|
||||
StateInfoBase result = client.resolve("bdtest.gd/dddd");
|
||||
LOGGER.info(result.handleValues.toString());
|
||||
} catch (IrpClientException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,11 +1,29 @@
|
||||
oracle ContractExample {
|
||||
function onCreate() {
|
||||
oracle GDRouter {
|
||||
function onCreate(arg) {
|
||||
Global.owner = requester;
|
||||
Global.resolver = org.bdware.sc.contractexample.Resolver.main(arg);
|
||||
}
|
||||
export function callHello(arg) {
|
||||
return org.bdware.sc.contractexample.Hello.call()+requester;
|
||||
return org.bdware.sc.contractexample.Hello.call() + requester;
|
||||
}
|
||||
export function getOwner() {
|
||||
return Global.owner;
|
||||
}
|
||||
@Description("{}")
|
||||
@ArgSchema({
|
||||
})
|
||||
export function peekDB(arg) {
|
||||
return org.bdware.sc.contractexample.Resolver.peekDB(arg);
|
||||
}
|
||||
@Description("resolve string, {\"token\":\"abc\",\"doid\":\"bdtest.gd/dddd\"}")
|
||||
@ArgSchema({
|
||||
"token" : "string", "doid" : "string"
|
||||
})
|
||||
export function resolve(arg) {
|
||||
if (arg.token != Global.resolver.config.token)
|
||||
YancloudUtil.exceptionReturn({
|
||||
"code" : 3, "msg" : "invalid token"
|
||||
});
|
||||
return org.bdware.sc.contractexample.Resolver.resolve(arg.doid);
|
||||
}
|
||||
}
|
@ -1,2 +1,2 @@
|
||||
rootProject.name = 'ContractJavaExample'
|
||||
rootProject.name = 'GuangDongResolver'
|
||||
include 'backend'
|
||||
|
Loading…
Reference in New Issue
Block a user