From 1a3404de0c311f85bde231e8f974ce431a26bc80 Mon Sep 17 00:00:00 2001 From: Franklin_Zhang Date: Fri, 6 Apr 2018 21:45:28 +0800 Subject: [PATCH 1/8] Add python SDK Signed-off-by: Franklin_Zhang --- swig/python/test.py | 203 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 203 insertions(+) create mode 100644 swig/python/test.py diff --git a/swig/python/test.py b/swig/python/test.py new file mode 100644 index 0000000..0f8fc0d --- /dev/null +++ b/swig/python/test.py @@ -0,0 +1,203 @@ +import urllib +import httplib +import json +import requests +import time + +class HttpHelper: + @staticmethod + def Request_get_sync(ip, port, path): + conn = httplib.HTTPConnection(ip, port) + conn.request("GET", path) + res = conn.getresponse() + jsData = json.loads(res.read()) + return jsData + + @staticmethod + def Request_get_stream_sync(ip, port, path): + conn = httplib.HTTPConnection(ip, port) + conn.request("GET", path) + res = conn.getresponse() + jsData = res.read() + return jsData + + + @staticmethod + def Request_post_sync(ip, port, path, params, files): + pass + + @staticmethod + def Request_put_sync(ip, port, path): + pass + +class Service: + def __init__(self, ip, port): + self.ip = ip + self.port = port + + def getBaseURL(self): + return "http://" + self.ip + ":" + str(self.port) + "/" + + def connect(self): + strData = HttpHelper.Request_get_stream_sync(self.ip, self.port, "/ping") + if strData == "OK": + return True + else: + return False + +class Data(Service): + def __init__(self, id, tag, type, size, value, datetime, ip, port): + Service.__init__(self, ip, port) + self.id = id + self.tag = tag + self.type = type + self.size = size + self.value = value + self.datetime = datetime + + def isExist(self): + return False + + def save(self, filepath): + urllib.urlretrieve(self.getBaseURL() + "geodata/" + self.id, filepath) + return 1 + +class DataConfigrationItem: + def __init__(self, stateid, eventname, dataid, destoryed = False, requested = False, optional = False): + self.stateid = stateid + self.eventname = eventname + self.dataid = dataid + self.destoryed = destoryed + self.requested = requested + self.optional = optional + + @staticmethod + def MakeUpDataItem(jsData): + dat = DataConfigrationItem(jsData["StateId"], jsData["Event"], jsData["DataId"], bool(jsData["Destroyed"])) + return dat + +class ModelService(Service): + def __init__(self, ip, port, id, name, type): + Service.__init__(self, ip, port) + self.id = id + self.name = name + self.type = type + + def invoke(self, list_data): + path = "?ac=run&inputdata=[" + for index, item in enumerate(list_data): + path += "{\"StateId\":\"" + item.stateid + "\",\"Event\":\"" + item.eventname + "\",\"DataId\":\"" + item.dataid + "\",\"Destoryed\":\"" + str(item.destoryed) + "\"}" + path += "]" + jsData = HttpHelper.Request_get_sync(self.ip, self.port, path) + if jsData["result"] == "suc": + recordid = jsData["data"] + return recordid + +class ModelServiceRunningRecord(Service): + def __init__(self, ip, port, id, msid, status, inputs = [], outputs = []): + Service.__init__(self, ip, port) + self.id = id + self.msid = msid + self.status = status + self.inputs = inputs + self.outputs = outputs + + def waitForFinished(self): + self.refresh() + while self.status == 0: + time.sleep(3) + self.refresh() + return 1 + + def refresh(self): + jsData = HttpHelper.Request_get_sync(self.ip, self.port, "/modelserrun/json/" + self.id) + if jsData["result"] == "suc": + self.status = int(jsData["data"]["msr_status"]) + self.inputs = [] + for index, item in enumerate(jsData["data"]["msr_input"]): + self.inputs.append(DataConfigrationItem.MakeUpDataItem(item)) + + self.outputs = [] + for index, item in enumerate(jsData["data"]["msr_output"]): + self.outputs.append(DataConfigrationItem.MakeUpDataItem(item)) + +class ServiceAccess(Service): + def __init__(self, ip, port): + Service.__init__(self, ip, port) + + def getModelServicesList(self): + jsData = HttpHelper.Request_get_sync(self.ip, self.port, "/modelser/json/all") + mslist = [] + if jsData["result"] == "suc": + jsMss = jsData["data"] + for index, item in enumerate(jsMss): + ms = ModelService(self.ip, self.port, item["_id"], item["ms_model"]["m_name"], item["ms_model"]["m_type"]) + mslist.append(ms) + return mslist + + def getModelServiceByID(self, msid): + jsData = HttpHelper.Request_get_sync(self.ip, self.port, "/modelser/json/" + msid) + ms = None + if jsData["result"] == "suc": + jsMs = jsData["data"] + ms = ModelService(self.ip, self.port, jsMs["_id"], jsMs["ms_model"]["m_name"], jsMs["ms_model"]["m_type"]) + return ms + + def getModelServiceRunningRecordByID(self, msrid): + jsData = HttpHelper.Request_get_sync(self.ip, self.port, "/modelserrun/json/" + msrid) + msr = None + if jsData["result"] == "suc": + jsMsr = jsData["data"] + msr = ModelServiceRunningRecord(self.ip, self.port, jsMsr["_id"], jsMsr["msr_ms"]["_id"], int(jsMsr["msr_status"])) + return msr + + + def uploadDataByFile(self, tag, filepath): + data = {"gd_tag" : tag} + files = { + "myfile" : open(filepath, "rb") + } + r = requests.post("http://" + self.ip + ":" + str(self.port) + "/geodata?type=file", data, files=files) + jsData = json.loads(r.text) + if jsData["result"] == "suc": + return jsData["data"] + return "" + + def getDataByID(self, dataid): + jsData = HttpHelper.Request_get_sync(self.ip, self.port, "/geodata/json/" + dataid) + dat = None + if jsData["result"] == "suc" and jsData["data"] != "": + dat = Data(jsData["data"]["gd_id"], jsData["data"]["gd_tag"], jsData["data"]["gd_type"], int(jsData["data"]["gd_size"]), jsData["data"]["gd_value"], jsData["data"]["gd_datetime"], self.ip, self.port) + return dat + +class Server(Service): + def __init__(self, ip, port): + Service.__init__(self, ip, port) + + def getServiceAccess(self): + return ServiceAccess(self.ip, self.port) + + +server = Server("172.21.212.119", 8060) +print str(server.connect()) +access = server.getServiceAccess() +list_ms = access.getModelServicesList() +for index, item in enumerate(list_ms): + print "ID : " + item.id + " - Name : " + item.name + " - Type : " + item.type +dataid = access.uploadDataByFile("swat_input", "/Users/zhangfengyuan/Data/SWAT664_INPUT.zip") +print "SWAT - Data ID : " + dataid +swat = access.getModelServiceByID("5aac7d81926ec0059c553f0c") +recordid = swat.invoke([DataConfigrationItem("04579ee0-5983-4d75-bdc9-a1a460229aa0", "LoadHydroResponseUnit", dataid)]) +record = access.getModelServiceRunningRecordByID(recordid) +record.waitForFinished() +print "SWAT has been finished" +for index,item in enumerate(record.outputs): + dat = access.getDataByID(item.dataid) + dat.save("/Users/zhangfengyuan/Data/SWAT664_OUTPUT_" + item.eventname + ".zip") + +# conn = httplib.HTTPConnection("127.0.0.1:8060") +# conn.request("GET", "/modelser/json/all") +# res = conn.getresponse() +# strData = res.read() +# jsData = json.loads(strData) +# print jsData['result'] -- Gitee From a01f070ecb4dd34c2515b7c7ac4c7ac78220e64e Mon Sep 17 00:00:00 2001 From: wang ming <1508574735@qq.com> Date: Tue, 10 Apr 2018 23:11:40 +0800 Subject: [PATCH 2/8] add java file --- swig/java/factory/NJServiceFactory.java | 18 +++++ .../java/nativeInterface/INJModelService.java | 11 +++ swig/java/nativeInterface/INJServer.java | 7 ++ .../nativeInterface/INJServiceAccess.java | 9 +++ swig/java/nativecode/NxServiceApiDemo.java | 44 +++++++++++ swig/java/nativecode/Test.java | 75 +++++++++++++++++++ swig/java/nativemodel/NJModelServerModel.java | 37 +++++++++ swig/java/nativemodel/NJServerModel.java | 21 ++++++ .../nativemodel/NJServiceAccessModel.java | 37 +++++++++ 9 files changed, 259 insertions(+) create mode 100644 swig/java/factory/NJServiceFactory.java create mode 100644 swig/java/nativeInterface/INJModelService.java create mode 100644 swig/java/nativeInterface/INJServer.java create mode 100644 swig/java/nativeInterface/INJServiceAccess.java create mode 100644 swig/java/nativecode/NxServiceApiDemo.java create mode 100644 swig/java/nativecode/Test.java create mode 100644 swig/java/nativemodel/NJModelServerModel.java create mode 100644 swig/java/nativemodel/NJServerModel.java create mode 100644 swig/java/nativemodel/NJServiceAccessModel.java diff --git a/swig/java/factory/NJServiceFactory.java b/swig/java/factory/NJServiceFactory.java new file mode 100644 index 0000000..078d5b2 --- /dev/null +++ b/swig/java/factory/NJServiceFactory.java @@ -0,0 +1,18 @@ +package com.wwj.factory; + +import com.wwj.nativeInterface.INJServer; +import com.wwj.nativecode.NxServiceApiDemo; +import com.wwj.nativemodel.NJServerModel; + +public class NJServiceFactory { + + public static INJServer CreateServer(String ip, int port){ + + NxServiceApiDemo instance = new NxServiceApiDemo(); + //System.out.println(instance.NJS_CreateServerHandle(ip, port)); + int handle = instance.NJS_CreateServerHandle(ip, port); + //return new NJServerModel((INJServer)handle); + return new NJServerModel(handle); + } + +} diff --git a/swig/java/nativeInterface/INJModelService.java b/swig/java/nativeInterface/INJModelService.java new file mode 100644 index 0000000..37b34ef --- /dev/null +++ b/swig/java/nativeInterface/INJModelService.java @@ -0,0 +1,11 @@ +package com.wwj.nativeInterface; + +public interface INJModelService { + + public String getServiceOID(); + + public String getServiceName(); + + public String getServiceType(); + +} diff --git a/swig/java/nativeInterface/INJServer.java b/swig/java/nativeInterface/INJServer.java new file mode 100644 index 0000000..ed78181 --- /dev/null +++ b/swig/java/nativeInterface/INJServer.java @@ -0,0 +1,7 @@ +package com.wwj.nativeInterface; + +public interface INJServer { + + public INJServiceAccess CreateModelServiceAccess(); + +} diff --git a/swig/java/nativeInterface/INJServiceAccess.java b/swig/java/nativeInterface/INJServiceAccess.java new file mode 100644 index 0000000..e054dff --- /dev/null +++ b/swig/java/nativeInterface/INJServiceAccess.java @@ -0,0 +1,9 @@ +package com.wwj.nativeInterface; + +import java.util.List; + +public interface INJServiceAccess { + + public List GetModelServicesList(); + +} diff --git a/swig/java/nativecode/NxServiceApiDemo.java b/swig/java/nativecode/NxServiceApiDemo.java new file mode 100644 index 0000000..831ba60 --- /dev/null +++ b/swig/java/nativecode/NxServiceApiDemo.java @@ -0,0 +1,44 @@ +package com.wwj.nativecode; + +public class NxServiceApiDemo { + + static { + //System.load("G:\\NJTest\\VS2010_64\\x64\\Debug\\NJModelServiceJava.dll"); + System.loadLibrary("NJModelServiceJava"); + } + + public native int NJS_CreateServerHandle(String ip, int port); + + public native int NJS_CreateServiceAccessHandle(int server); + + public native int NJS_CreateModelServerList(int access); + + public native int NJS_CleanModelServiceListHandle(int list); + + public native int NJS_GetModelServiceListCount(int list); + + public native int NJS_GetModelServiceByIndex(int list, int index); + + public native String NJS_GetModelServiceOID(int ms); + + public native String NJS_GetModelServiceName(int ms); + + public native String NJS_GetModelServiceType(int ms); + + public native String NJS_testchar(String content); + +// public static void main(String[] args){ +// String content = "hello"; +// String result; +// +// NxServiceApiDemo test = new NxServiceApiDemo(); +// +// result = test.NJS_testchar(content); +// +// System.out.println("The test content:" + result); +// +// +// +// } + +} diff --git a/swig/java/nativecode/Test.java b/swig/java/nativecode/Test.java new file mode 100644 index 0000000..4264d74 --- /dev/null +++ b/swig/java/nativecode/Test.java @@ -0,0 +1,75 @@ +package com.wwj.nativecode; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.List; + +import com.wwj.factory.NJServiceFactory; +import com.wwj.nativeInterface.INJModelService; +import com.wwj.nativeInterface.INJServer; +import com.wwj.nativeInterface.INJServiceAccess; +import com.wwj.nativecode.FileUtil; + +public class Test { + + public static void main(String[] args)throws Exception{ + + //Path path1 = Paths.get("E:\\NativeTest\\xiaowang\\a.txt"); + //Path path2 = Paths.get("E:\\NativeTest\\wm\\just\\b.txt"); + + //Files.copy(path1, path2, StandardCopyOption.REPLACE_EXISTING); + +// if(!Files.exists(path2)){ +// Path rootpath = path2.getParent(); +// if(!Files.exists(rootpath)){ +// //创建上级所有文件夹目录 +// Files.createDirectories(rootpath); +// } +// //创建文件 +// Files.createFile(path2); +// +// } + +// Files.copy(path1, path2, StandardCopyOption.REPLACE_EXISTING); + +// Path rootpath = path2.getParent(); +// System.out.println(rootpath.toString()); + + //测试文件夹复制功能 +// Path path1 = Paths.get("E:\\NativeTest\\wangming"); +// Path path2 = Paths.get("E:\\NativeTest\\xiaowang"); +// +// FileUtil.copyDir(path1, path2, StandardCopyOption.REPLACE_EXISTING); + + //FileUtil.copyFile(path1, path2, StandardCopyOption.REPLACE_EXISTING); + String ip = "127.0.0.1"; + int port = 8060; + + INJServer pServer = NJServiceFactory.CreateServer(ip, port); + + System.out.println("success"); + + INJServiceAccess pServiceAccess = pServer.CreateModelServiceAccess(); + + List list_ms; + + list_ms = pServiceAccess.GetModelServicesList(); + + + System.out.println("hhaa"); + + + + + + } + + + //实现拷贝文件夹的方法 + + +} diff --git a/swig/java/nativemodel/NJModelServerModel.java b/swig/java/nativemodel/NJModelServerModel.java new file mode 100644 index 0000000..858dcb1 --- /dev/null +++ b/swig/java/nativemodel/NJModelServerModel.java @@ -0,0 +1,37 @@ +package com.wwj.nativemodel; + +import com.wwj.nativeInterface.INJModelService; + +public class NJModelServerModel implements INJModelService { + + private String _oid; + private String _name; + private String _type; + + + public NJModelServerModel(String oid, String name, String type){ + this._oid = oid; + this._name = name; + this._type = type; + } + + @Override + public String getServiceOID() { + // TODO Auto-generated method stub + return this._oid; + } + + @Override + public String getServiceName() { + // TODO Auto-generated method stub + return this._name; + } + + @Override + public String getServiceType() { + // TODO Auto-generated method stub + return this._type; + } + + +} diff --git a/swig/java/nativemodel/NJServerModel.java b/swig/java/nativemodel/NJServerModel.java new file mode 100644 index 0000000..1c03ebe --- /dev/null +++ b/swig/java/nativemodel/NJServerModel.java @@ -0,0 +1,21 @@ +package com.wwj.nativemodel; + +import com.wwj.nativeInterface.INJServer; +import com.wwj.nativeInterface.INJServiceAccess; +import com.wwj.nativecode.NxServiceApiDemo; + +public class NJServerModel implements INJServer { + + private int _handle; + public NJServerModel(int handle){ + this._handle = handle; + } + + @Override + public INJServiceAccess CreateModelServiceAccess() { + NxServiceApiDemo instance = new NxServiceApiDemo(); + return new NJServiceAccessModel(instance.NJS_CreateServiceAccessHandle(this._handle)); + + } + +} diff --git a/swig/java/nativemodel/NJServiceAccessModel.java b/swig/java/nativemodel/NJServiceAccessModel.java new file mode 100644 index 0000000..8180b37 --- /dev/null +++ b/swig/java/nativemodel/NJServiceAccessModel.java @@ -0,0 +1,37 @@ +package com.wwj.nativemodel; + +import java.util.ArrayList; +import java.util.List; + +import com.wwj.nativeInterface.INJModelService; +import com.wwj.nativeInterface.INJServiceAccess; +import com.wwj.nativecode.NxServiceApiDemo; + +public class NJServiceAccessModel implements INJServiceAccess { + + private int _handle; + public NJServiceAccessModel(int object){ + this._handle = object; + } + + @Override + public List GetModelServicesList() { + // TODO Auto-generated method stub + List list_ms = new ArrayList(); + NxServiceApiDemo instance = new NxServiceApiDemo(); + int listHandle = instance.NJS_CreateModelServerList(this._handle); + int count = instance.NJS_GetModelServiceListCount(listHandle); + + for(int i = 0; i < count; i++ ){ + int msHandle = instance.NJS_GetModelServiceByIndex(listHandle, i); + String oid = instance.NJS_GetModelServiceOID(msHandle); + String name = instance.NJS_GetModelServiceName(msHandle); + String type = instance.NJS_GetModelServiceType(msHandle); + INJModelService pMs = new NJModelServerModel(oid,name,type); + list_ms.add(pMs); + } + + return list_ms; + } + +} -- Gitee From b5ee63c5e2f5a3493af048901f657411131bb3e5 Mon Sep 17 00:00:00 2001 From: Franklin_Zhang Date: Wed, 11 Apr 2018 11:24:41 +0800 Subject: [PATCH 3/8] put python package files in order Signed-off-by: Franklin_Zhang --- swig/python/base.py | 16 ++++ swig/python/base.pyc | Bin 0 -> 1099 bytes swig/python/data.py | 35 ++++++++ swig/python/data.pyc | Bin 0 -> 2031 bytes swig/python/modelser.py | 52 +++++++++++ swig/python/modelser.pyc | Bin 0 -> 2819 bytes swig/python/server.py | 68 ++++++++++++++ swig/python/server.pyc | Bin 0 -> 4073 bytes swig/python/setup.py | 7 ++ swig/python/setup.pyc | Bin 0 -> 658 bytes swig/python/test.py | 189 ++------------------------------------- swig/python/utils.py | 30 +++++++ swig/python/utils.pyc | Bin 0 -> 1491 bytes 13 files changed, 214 insertions(+), 183 deletions(-) create mode 100644 swig/python/base.py create mode 100644 swig/python/base.pyc create mode 100644 swig/python/data.py create mode 100644 swig/python/data.pyc create mode 100644 swig/python/modelser.py create mode 100644 swig/python/modelser.pyc create mode 100644 swig/python/server.py create mode 100644 swig/python/server.pyc create mode 100644 swig/python/setup.py create mode 100644 swig/python/setup.pyc create mode 100644 swig/python/utils.py create mode 100644 swig/python/utils.pyc diff --git a/swig/python/base.py b/swig/python/base.py new file mode 100644 index 0000000..a015797 --- /dev/null +++ b/swig/python/base.py @@ -0,0 +1,16 @@ +from utils import HttpHelper + +class Service: + def __init__(self, ip, port): + self.ip = ip + self.port = port + + def getBaseURL(self): + return "http://" + self.ip + ":" + str(self.port) + "/" + + def connect(self): + strData = HttpHelper.Request_get_stream_sync(self.ip, self.port, "/ping") + if strData == "OK": + return True + else: + return False diff --git a/swig/python/base.pyc b/swig/python/base.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f70afc63be3fd24c55b70f12f175a1d0ebb8a9c GIT binary patch literal 1099 zcmb_b!EV$*4D}@0!WIym*aH_N4n#s?k+`i8LTv>Vg&-wxV71aHB*Qk4O+v;Cs#H$P zKk!rh2Oq!(z_YWZcS;n$@k~6npY4RduI+yR`D0$t_6e~*f%vf&sE|6h7r3xh`$4HB;FAW zZpEchB_xEClZetRmb?l9kpQv}@izgdhE9nrlt2~rlxZeOES4-#bsS;o+Md;y?!2qt zr}8xwuQ6l*{{WhsEuK}p-pZK-RZkekl3Sx=9oq#4^IcxPV zuy)m!>l)is4AQZ{b-;Nps{PZzrDr4M<^S6;<7gZvgJT&9EytRx+G{b@`hSE~mX8Kr Lk0k}2iyOfo)N0rz literal 0 HcmV?d00001 diff --git a/swig/python/data.py b/swig/python/data.py new file mode 100644 index 0000000..3a1d0dd --- /dev/null +++ b/swig/python/data.py @@ -0,0 +1,35 @@ +import urllib + +from utils import HttpHelper +from base import Service + +class Data(Service): + def __init__(self, id, tag, type, size, value, datetime, ip, port): + Service.__init__(self, ip, port) + self.id = id + self.tag = tag + self.type = type + self.size = size + self.value = value + self.datetime = datetime + + def isExist(self): + return False + + def save(self, filepath): + urllib.urlretrieve(self.getBaseURL() + "geodata/" + self.id, filepath) + return 1 + +class DataConfigrationItem: + def __init__(self, stateid, eventname, dataid, destoryed = False, requested = False, optional = False): + self.stateid = stateid + self.eventname = eventname + self.dataid = dataid + self.destoryed = destoryed + self.requested = requested + self.optional = optional + + @staticmethod + def MakeUpDataItem(jsData): + dat = DataConfigrationItem(jsData["StateId"], jsData["Event"], jsData["DataId"], bool(jsData["Destroyed"])) + return dat \ No newline at end of file diff --git a/swig/python/data.pyc b/swig/python/data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python/server.py new file mode 100644 index 0000000..0efdd06 --- /dev/null +++ b/swig/python/server.py @@ -0,0 +1,68 @@ +import requests +import json + +from utils import HttpHelper +from base import Service +from modelser import ModelService +from modelser import ModelServiceRunningRecord +from data import Data +from data import DataConfigrationItem + +class ServiceAccess(Service): + def __init__(self, ip, port): + Service.__init__(self, ip, port) + + def getModelServicesList(self): + jsData = HttpHelper.Request_get_sync(self.ip, self.port, "/modelser/json/all") + mslist = [] + if jsData["result"] == "suc": + jsMss = jsData["data"] + for index, item in enumerate(jsMss): + ms = ModelService(self.ip, self.port, item["_id"], item["ms_model"]["m_name"], item["ms_model"]["m_type"]) + mslist.append(ms) + return mslist + + def getModelServiceByID(self, msid): + jsData = HttpHelper.Request_get_sync(self.ip, self.port, "/modelser/json/" + msid) + ms = None + if jsData["result"] == "suc": + jsMs = jsData["data"] + ms = ModelService(self.ip, self.port, jsMs["_id"], jsMs["ms_model"]["m_name"], jsMs["ms_model"]["m_type"]) + return ms + + def getModelServiceRunningRecordByID(self, msrid): + jsData = HttpHelper.Request_get_sync(self.ip, self.port, "/modelserrun/json/" + msrid) + msr = None + if jsData["result"] == "suc": + jsMsr = jsData["data"] + msr = ModelServiceRunningRecord(self.ip, self.port, jsMsr["_id"], jsMsr["msr_ms"]["_id"], int(jsMsr["msr_status"])) + return msr + + + def uploadDataByFile(self, tag, filepath): + data = {"gd_tag" : tag} + files = { + "myfile" : open(filepath, "rb") + } + r = requests.post("http://" + self.ip + ":" + str(self.port) + "/geodata?type=file", data, files=files) + jsData = json.loads(r.text) + if jsData["result"] == "suc": + return jsData["data"] + return "" + + def getDataByID(self, dataid): + jsData = HttpHelper.Request_get_sync(self.ip, self.port, "/geodata/json/" + dataid) + dat = None + if jsData["result"] == "suc" and jsData["data"] != "": + dat = Data(jsData["data"]["gd_id"], jsData["data"]["gd_tag"], jsData["data"]["gd_type"], int(jsData["data"]["gd_size"]), jsData["data"]["gd_value"], jsData["data"]["gd_datetime"], self.ip, self.port) + return dat + + def createDataConfigurationItem(self, stateid, eventname, dataid): + return DataConfigrationItem(stateid, eventname, dataid) + +class Server(Service): + def __init__(self, ip, port): + Service.__init__(self, ip, port) + + def getServiceAccess(self): + return ServiceAccess(self.ip, self.port) \ No newline at end of file diff --git a/swig/python/server.pyc b/swig/python/server.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa9c1692e34496a5b507f4ad0d46524b54370927 GIT binary patch literal 4073 zcmb_fU2hvj6us-O*iHhaEkveBEj)k)s1a35rK+VR4gH`r51R*s6|}hCiM#H4?e2_2 zQzZ{5@F#fStr9%)KlnHO0dUS8J9bTwAR+CJ@4cR#xpU9Ccdm;sm+Qa3{G-*8@m~?2 zxA53sF~s;ENGj4glmlr6YA;AykbY5GMF}{sC}~OhWoebYUXrvT{RL?)c)hH8Ra#ZA zS0t@Tzb>u1*B4Y@l-45js+h8DW22h0Tw`oy|;XkDg*o6RLSoBWBtjb;GR z)iK<2Zg|h6Lz8>k0&JTm-$^>g8~D=0L2S}jtc^KqILfjl>xQN?$YcLv2~*bFuI;t6 zW9{}J+fKT9+a-hSzB7Hdj4#GZf8OaBYY&4=AJ_2MyBG|@t0BcnTLqqnLQ&#^3MGb? zma@bp6)F;!RalU?qC!=|%_h&+A$)x3;%z*31%ngm1+piyhp`|B9WCnZDGhlAWTp^6Un5+rkN>u%z1BbHkmU(SYfbN#`V{XXe# z4R_t+LAGTPf0JJv?uPW109dXpL5B{|MjzDiUmzSh-Yd}k9)c3k{ry0?BKt5Ra0O`~ zLQe{k|EzjR8v8|gwngvvigFOh`nL~ct04O&*)NML>r#^i_Yl^yH26`$LJL!|Dvg7( z>{l4F9>xln3ZCARuQNol0M^yu;)XqqakWn#;dHA#JIGesY3eF4=f;jw=NL*m>S*+0 z@J0<$5<4EYZzFwKU+70!yKly#+Z`H3HN-S=r!a)(>Bv|Yb&ZScZq^CuLP)kdN+uii z4H#%bMpc(-4~Hg;{W9E6jXg{H`fY5QScjk>y!N5BDkWKLo~gSDiOj|NR^is+n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CD@B(ct$kYgG)Fc# zJ@zQJeXd{~kPB$upcQ13Jpi+Y*+5l{dE_|s;LW6a2eV^wj_R`Xle-6fIGKFt6?txA zmlnA!SLVyoSm*9y`OLV=*s{p2K^nla*u-RIMU+@^RVGThT!Q0tX(`UKs9dc??p%}@ zNdyYwIo>|E{m4aKXe7eEfM#CK2C3^6iJ6VwzQ>e}P4zX6&A9(=X1}Fpv+}~77x`@I z(#$@Gag4WgjW`6_&|c&*7iqbVQ!v&Os-rLvtggbIU5j&94ut+*#gxec`P{s9%70uUpAsU)3C(aL)u& J8#fU@?>Bm{El&Ud literal 0 HcmV?d00001 -- Gitee From e6872d0d498270f3f84eaa5c2d63d06d3fa14c2e Mon Sep 17 00:00:00 2001 From: wang ming <1508574735@qq.com> Date: Sat, 14 Apr 2018 17:54:10 +0800 Subject: [PATCH 4/8] add matlab function --- .../+HttpHelper/Request_file_post.m | 21 ++ .../+HttpHelper/Request_get.m | 9 + .../modelserviceContainer/+utils/license.txt | 27 +++ .../+utils/urlreadpost.m | 113 ++++++++++ .../+utils/urlreadwrite.m | 58 +++++ swig/matlab/modelserviceContainer/Data.m | 50 +++++ .../DataConfigrationItem.m | 44 ++++ .../modelserviceContainer/ModelService.m | 38 ++++ .../ModelServiceFactory.m | 13 ++ .../ModelServiceRecordFactory.m | 13 ++ .../ModelServiceRunningRecord.m | 84 +++++++ swig/matlab/modelserviceContainer/Server.m | 20 ++ swig/matlab/modelserviceContainer/Service.m | 33 +++ .../modelserviceContainer/ServiceAccess.m | 89 ++++++++ .../json4mat/html/json4mat_pub.html | 166 ++++++++++++++ .../json4mat/html/json4mat_pub.pdf | Bin 0 -> 9285 bytes .../modelserviceContainer/json4mat/json2mat.m | 130 +++++++++++ .../json4mat/json4mat_pub.m | 57 +++++ .../json4mat/license.txt | 24 ++ .../modelserviceContainer/json4mat/mat2json.m | 59 +++++ .../json4mat/parse_json.m | 205 ++++++++++++++++++ .../modelserviceContainer/json4mat/pub.m | 3 + swig/matlab/modelserviceContainer/test.m | 24 ++ 23 files changed, 1280 insertions(+) create mode 100644 swig/matlab/modelserviceContainer/+HttpHelper/Request_file_post.m create mode 100644 swig/matlab/modelserviceContainer/+HttpHelper/Request_get.m create mode 100644 swig/matlab/modelserviceContainer/+utils/license.txt create mode 100644 swig/matlab/modelserviceContainer/+utils/urlreadpost.m create mode 100644 swig/matlab/modelserviceContainer/+utils/urlreadwrite.m create mode 100644 swig/matlab/modelserviceContainer/Data.m create mode 100644 swig/matlab/modelserviceContainer/DataConfigrationItem.m create mode 100644 swig/matlab/modelserviceContainer/ModelService.m create mode 100644 swig/matlab/modelserviceContainer/ModelServiceFactory.m create mode 100644 swig/matlab/modelserviceContainer/ModelServiceRecordFactory.m create mode 100644 swig/matlab/modelserviceContainer/ModelServiceRunningRecord.m create mode 100644 swig/matlab/modelserviceContainer/Server.m create mode 100644 swig/matlab/modelserviceContainer/Service.m create mode 100644 swig/matlab/modelserviceContainer/ServiceAccess.m create mode 100644 swig/matlab/modelserviceContainer/json4mat/html/json4mat_pub.html create mode 100644 swig/matlab/modelserviceContainer/json4mat/html/json4mat_pub.pdf create mode 100644 swig/matlab/modelserviceContainer/json4mat/json2mat.m create mode 100644 swig/matlab/modelserviceContainer/json4mat/json4mat_pub.m create mode 100644 swig/matlab/modelserviceContainer/json4mat/license.txt create mode 100644 swig/matlab/modelserviceContainer/json4mat/mat2json.m create mode 100644 swig/matlab/modelserviceContainer/json4mat/parse_json.m create mode 100644 swig/matlab/modelserviceContainer/json4mat/pub.m create mode 100644 swig/matlab/modelserviceContainer/test.m diff --git a/swig/matlab/modelserviceContainer/+HttpHelper/Request_file_post.m b/swig/matlab/modelserviceContainer/+HttpHelper/Request_file_post.m new file mode 100644 index 0000000..c171cac --- /dev/null +++ b/swig/matlab/modelserviceContainer/+HttpHelper/Request_file_post.m @@ -0,0 +1,21 @@ +function [ jsData ] = Request_file_post( ip,port,path,tag,filepath ) +%REQUEST_FILE_POST ˴ʾйش˺ժҪ +% ˴ʾϸ˵ + url = ['http://',ip,':',num2str(port),'/',path]; + diroutput = dir(filepath); + filename = diroutput.name; + fid = fopen(filepath,'r'); + if fid == -1 + disp('fopen failed') + else + data = fread(fid,Inf,'*uint8'); + fclose(fid); + end + response = utils.urlreadpost(url,{'myfile',data,'gd_tag',tag},filename); + %jsData = json2mat(response); + jsData = parse_json(response); + +end + + + diff --git a/swig/matlab/modelserviceContainer/+HttpHelper/Request_get.m b/swig/matlab/modelserviceContainer/+HttpHelper/Request_get.m new file mode 100644 index 0000000..05e7b7f --- /dev/null +++ b/swig/matlab/modelserviceContainer/+HttpHelper/Request_get.m @@ -0,0 +1,9 @@ +function [ jsData ] = Request_get( ip,port, path) +%REQUEST_GET ˴ʾйش˺ժҪ +% ˴ʾϸ˵ + url = ['http://',ip,':',num2str(port),'/',path]; + options = weboptions('ContentType','json'); + jsData = webread(url,options); +end + + diff --git a/swig/matlab/modelserviceContainer/+utils/license.txt b/swig/matlab/modelserviceContainer/+utils/license.txt new file mode 100644 index 0000000..b34ec63 --- /dev/null +++ b/swig/matlab/modelserviceContainer/+utils/license.txt @@ -0,0 +1,27 @@ +Copyright (c) 2010, Dan Ellis +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution + * Neither the name of the Columbia University nor the names + of its contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/swig/matlab/modelserviceContainer/+utils/urlreadpost.m b/swig/matlab/modelserviceContainer/+utils/urlreadpost.m new file mode 100644 index 0000000..ea80284 --- /dev/null +++ b/swig/matlab/modelserviceContainer/+utils/urlreadpost.m @@ -0,0 +1,113 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +function [output,status] = urlreadpost(urlChar,params,options) +%URLREADPOST Returns the contents of a URL POST method as a string. +% S = URLREADPOST('URL',PARAMS) passes information to the server as +% a POST request. PARAMS is a cell array of param/value pairs. +% +% Unlike stock urlread, this version uses the multipart/form-data +% encoding, and can thus post file content. File data is +% encoded as a value element of numerical type (e.g. uint8) +% in PARAMS. For example: +% +% f = fopen('music.mp3'); +% d = fread(f,Inf,'*uint8'); % Read in byte stream of MP3 file +% fclose(f); +% str = urlreadpost('http://developer.echonest.com/api/upload', ... +% {'file',dd,'version','3','api_key','API-KEY','wait','Y'}); +% +% ... will upload the mp3 file to the Echo Nest Analyze service. +% +% Based on TMW's URLREAD. Note that unlike URLREAD, there is no +% METHOD argument + +% 2010-04-07 Dan Ellis dpwe@ee.columbia.edu + +% This function requires Java. +if ~usejava('jvm') + error('MATLAB:urlreadpost:NoJvm','URLREADPOST requires Java.'); +end + +import com.mathworks.mlwidgets.io.InterruptibleStreamCopier; + +% Be sure the proxy settings are set. +com.mathworks.mlwidgets.html.HTMLPrefs.setProxySettings + +% Check number of inputs and outputs. +error(nargchk(3,3,nargin)) +error(nargoutchk(0,2,nargout)) +if ~ischar(urlChar) + error('MATLAB:urlreadpost:InvalidInput','The first input, the URL, must be a character array.'); +end + +% Do we want to throw errors or catch them? +if nargout == 2 + catchErrors = true; +else + catchErrors = false; +end + +% Set default outputs. +output = ''; +status = 0; + +% Create a urlConnection. +[urlConnection,errorid,errormsg] = utils.urlreadwrite(mfilename,urlChar); +if isempty(urlConnection) + if catchErrors, return + else error(errorid,errormsg); + end +end + +% POST method. Write param/values to server. +% Modified for multipart/form-data 2010-04-06 dpwe@ee.columbia.edu +% try + urlConnection.setDoOutput(true); + boundary = '***********************'; + urlConnection.setRequestProperty( ... + 'Content-Type',['multipart/form-data; boundary=',boundary]); + printStream = java.io.PrintStream(urlConnection.getOutputStream); + % also create a binary stream + dataOutputStream = java.io.DataOutputStream(urlConnection.getOutputStream); + eol = [char(13),char(10)]; + for i=1:2:length(params) + printStream.print(['--',boundary,eol]); + printStream.print(['Content-Disposition: form-data; name="',params{i},'"']); + if ~ischar(params{i+1}) + % binary data is uploaded as an octet stream + % Echo Nest API demands a filename in this case + printStream.print(['; filename="',options,'"',eol]); + printStream.print(['Content-Type: application/octet-stream',eol]); + printStream.print([eol]); + dataOutputStream.write(params{i+1},0,length(params{i+1})); + printStream.print([eol]); + else + printStream.print([eol]); + printStream.print([eol]); + printStream.print([params{i+1},eol]); + end + end + printStream.print(['--',boundary,'--',eol]); + printStream.close; +% catch +% if catchErrors, return +% else error('MATLAB:urlread:ConnectionFailed','Could not POST to URL.'); +% end +% end + +% Read the data from the connection. +try + inputStream = urlConnection.getInputStream; + byteArrayOutputStream = java.io.ByteArrayOutputStream; + % This StreamCopier is unsupported and may change at any time. + isc = InterruptibleStreamCopier.getInterruptibleStreamCopier; + isc.copyStream(inputStream,byteArrayOutputStream); + inputStream.close; + byteArrayOutputStream.close; + output = native2unicode(typecast(byteArrayOutputStream.toByteArray','uint8'),'UTF-8'); +catch + if catchErrors, return + else error('MATLAB:urlreadpost:ConnectionFailed','Error downloading URL. Your network connection may be down or your proxy settings improperly configured.'); + end +end + +status = 1; diff --git a/swig/matlab/modelserviceContainer/+utils/urlreadwrite.m b/swig/matlab/modelserviceContainer/+utils/urlreadwrite.m new file mode 100644 index 0000000..f6927e2 --- /dev/null +++ b/swig/matlab/modelserviceContainer/+utils/urlreadwrite.m @@ -0,0 +1,58 @@ +function [urlConnection,errorid,errormsg] = urlreadwrite(fcn,urlChar) +%URLREADWRITE A helper function for URLREAD and URLWRITE. + +% Matthew J. Simoneau, June 2005 +% Copyright 1984-2007 The MathWorks, Inc. +% $Revision: 1.1.6.3.6.1 $ $Date: 2009/01/30 22:37:42 $ + +% Default output arguments. +urlConnection = []; +errorid = ''; +errormsg = ''; + +% Determine the protocol (before the ":"). +protocol = urlChar(1:min(find(urlChar==':'))-1); + +% Try to use the native handler, not the ice.* classes. +switch protocol + case 'http' + try + handler = sun.net.www.protocol.http.Handler; + catch exception %#ok + handler = []; + end + case 'https' + try + handler = sun.net.www.protocol.https.Handler; + catch exception %#ok + handler = []; + end + otherwise + handler = []; +end + +% Create the URL object. +try + if isempty(handler) + url = java.net.URL(urlChar); + else + url = java.net.URL([],urlChar,handler); + end +catch exception %#ok + errorid = ['MATLAB:' fcn ':InvalidUrl']; + errormsg = 'Either this URL could not be parsed or the protocol is not supported.'; + return +end + +% Get the proxy information using MathWorks facilities for unified proxy +% prefence settings. +mwtcp = com.mathworks.net.transport.MWTransportClientPropertiesFactory.create(); +proxy = mwtcp.getProxy(); + + +% Open a connection to the URL. +if isempty(proxy) + urlConnection = url.openConnection; +else + urlConnection = url.openConnection(proxy); +end diff --git a/swig/matlab/modelserviceContainer/Data.m b/swig/matlab/modelserviceContainer/Data.m new file mode 100644 index 0000000..cd74002 --- /dev/null +++ b/swig/matlab/modelserviceContainer/Data.m @@ -0,0 +1,50 @@ +classdef Data = 4 + self.destoryed = destoryed; + requested = false; + self.requested = requested; + optional = false; + self.optional = optional; + end + end + + end + + methods (Static) + function dat = MakeUpDataItem(jsData) + dat = DataConfigrationItem(jsData.StateId, jsData.Event, jsData.DataId, jsData.Destroyed); + end + end + +end + diff --git a/swig/matlab/modelserviceContainer/ModelService.m b/swig/matlab/modelserviceContainer/ModelService.m new file mode 100644 index 0000000..6f4c02e --- /dev/null +++ b/swig/matlab/modelserviceContainer/ModelService.m @@ -0,0 +1,38 @@ +classdef ModelService + + + JSON4MAT

JSON4MAT

Jonas Almeida, April 2010

This manual was generated automatically by running pub.m .

JSON strings into (json2mat) and from (mat2json) Matlab structures. The name, "...4MAT", is a wink to an old, outdated but similalry minded XML toolbox XML4MAT where loose typing was argued for as being closer to Matlab's own loose assignment of types within a mat structure (http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.84.9787)

This is the first version of JSON4MAT was developed specifically for COUCH4MAT (http://couch4mat.googlecode.com), a tbox developed to help with interoperability with CouchDB. A reflection of the idea of loose typing and dimensionality natural to Matlab environments is ported to the reading and writting of numerical matrices into JSON.

Contents

JSON2MAT

JavaScript Object Notation (JSON) has a much looser and smaller set of data types that Matlab. Also, unlike XML it does not explicitly make room for attributes to be defined to additionally characterize a data element such as size and class. As a consequence the JSON strings can be interpreted just as dynamically:

json='{lele:2,lili:4,lolo:[1,2,{lulu:5,bubu:[[1,2],[3,4],[5,6]]}]}';
+mat=json2mat(json)
+
+mat = 
+
+    lele: 2
+    lili: 4
+    lolo: {[1]  [2]  [1x1 struct]}
+
+

Dimensionality in numerical arrays

The array of pairs of numbers suggests a 3x2 matrix and indeed JSON2MAT made that conversion:

mat.lolo{3}.bubu
+
+ans =
+
+     1     2
+     3     4
+     5     6
+
+

Non-numerial arrays

When there are non-numerical elements in a JSON array the array of arrays will be directly converted into a Matlab cell of cells. Notice the last numerical element of bubu is now "a".

json2mat('{lele:2,lili:4,lolo:[1,2,{lulu:5,bubu:[[1,2],[3,4],[5,"a"]]}]}');
+ans.lolo{3}
+
+ans = 
+
+    lulu: 5
+    bubu: {[1 2]  [3 4]  {1x2 cell}}
+
+

Unmatched dimensionality

The interpretation of arrays of arrays of numbers as corresponding to embedded dimensionality is performed by a try / catch command. Therefore, if teh dimensions don't match the cells of cells will be returned instead. In a future version maybe dimensionality in cell arrays will be coded in JSON2MAT as well, but presently that is only attempted for numerical arrays.

ans=json2mat('{lele:2,lili:4,lolo:[1,2,{lulu:5,bubu:[[1,2],[3,4],[5,6,7]]}]}');
+ans.lolo{3}
+
+ans = 
+
+    lulu: 5
+    bubu: {[1 2]  [3 4]  [5 6 7]}
+
+

MAT2JSON

Since the original motivation for this toolbox was to read entries from a CouchDB deployment, the conversion of mat into json was designed with a single criterion in mind: that the reverse operation JSON2MAT would return the original mat structure. Accordingly, if we return to the mat structure generated from the json string produced under JSON2MAT above, one can confirm that the same string is returned from mat:

mat2json(mat)
+
+ans =
+
+{"lele":2,"lili":4,"lolo":[1,2,{"lulu":5,"bubu":[[1,2],[3,4],[5,6]]}]}
+
+
\ No newline at end of file diff --git a/swig/matlab/modelserviceContainer/json4mat/html/json4mat_pub.pdf b/swig/matlab/modelserviceContainer/json4mat/html/json4mat_pub.pdf new file mode 100644 index 0000000000000000000000000000000000000000..caa83b195307179edd2273b75f068028efb0c044 GIT binary patch literal 9285 zcmcgy2|QHo_kYuB%1e@^l&g44nElRT>$QfmQ(2}OGlLN`ni)%kiYP6XinO3b3))cL z2$e`FONCV0NGVIQ6{+97cgSe^_0#A7e*QimGxs_7x#xV(InO!gdCnbmTN5*F9GZYq z&&bR=iy{J8fa~s!($fPljvM`00LFsj!9`(gd0eJHgT(_DbNqdLGynqw6pO=zXM!S6 ztYC3G1zrG-Ou_;fGq#TadH`eQLl>}2SPU+c1)$&u`2rq`?u!aK-0t$8`-CL(t)tlJ zQIgK)lI~(dBaz#$ z+qI{;D=1KHD444ISyH!rqFv;X*TF3k_0E40>KpE+HN`A_3n))$zGW>_3Vbl~Ox9i1 zou~4wxEo!Sw5)P>&L++M*JRR8*VafznJ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Q+SJ+jf#D?S74`R@N}PP|FJ*~Xj!yO`>rC%e11AG$>Y!0-NtT(< z!y(ExN|sKQtA?JZZQBzU6*r$$ycr-nT;mnvaVu`ZN!F zyN&dcZ72YLS8PooO7{km-j{auSxbc?D@XF<)&Ordq3r z`Obck=5gjb2aM(|_td^@Z*!&6c2%kDkCvB>D~{a`aNO;*hkHIoQM&6w0{D@` zB`|!bMeYe#@y}7?5Ttkn2M&RUgK>}$G7g50!y+o-i9Z8i%VPxqh-vI0{s^f#4If`c3bWcqE2| z3xX&D|6g7+|8t`BpZ0!K^DxCBx~1r8f@oRY-*7QZwkNmP>1kQM^E z51TPQaidvnL@#(t#fQ3#Tz_cgL55q-X7T}7q`U#h4$L0FBhdxWL|$r+W|I*<#&ie< z*Awp6LJWtSwE)J(U*N;$K!ooV6TWW+zw5*}@mV9c;nD>K0v~`qY{KG0U0V1`NOJ{% z#Y`*Wnai$#*mZYeGUR;GOi=^8r)=L>4+Fp#6dKX?Hp2ahbt`H z*!%AcL>)JV!>A?3LinXa$8Z?Uod1i1sH4ZQ7|l)pi-pJn5aobG#`mp;8Jow4c9e*B zpr}|uheiZpr5i18$S!kSwj+_Do+g%xEGJQ+K|GcR3Jx9=_WK_|0zqiqcmTsRGJyo~4Md7ZO$6A7m_13^VyBz9i#GB3J}G zI@^cEgMRS?#Wy>c1;-4=p38-T6waV1~',x(indOC(i,2)+1:end)]; +end +indOC=extract_embed(x,'[',']'); +m=size(indOC,1); +for j=m:-1:1 + i=n+j; + tag{i}=json2mat(x(indOC(i,1):indOC(i,2))); + try;tag{i}=cell2mat(tag{i});end + x=[x(1:indOC(i,1)-1),'tag{',num2str(i),'}',x(indOC(i,2)+1:end)]; +end +x=strrep(x,'~<','{'); +x=strrep(x,'>~','}'); +if exist('tag') %catching numeric content + if isnumeric([tag{:}]) + try + y=eval(['[',strrep(x,'},','};'),']']); + end + end +end + +if exist('y')~=1 + y=eval(['{',strrep(x,'"',''''),'}']); +end + +%look for embeded objects and arrays + +function y=extract_embed(x,tagOpen,tagClose) + +%EXTRACT_EMBED identifies embeded tagged segments +%Example y=extract_embed(str,'[',']') + +indOpen=strfind(x,tagOpen)'; +indOpen=[indOpen,ones(length(indOpen),1)]; +indClose=strfind(x,tagClose)'; +indClose=[indClose,-ones(length(indClose),1)]; +indOpenClose=[indOpen;indClose]; +[~,Ind]=sort(indOpenClose(:,1)); +indOpenClose=indOpenClose(Ind,:); +n=size(indOpenClose,1); +for i=2:n % add one for open, take one for close + indOpenClose(i,2)=indOpenClose(i-1,2)+indOpenClose(i,2); +end +i=0; +op=0; %open +while i2 % for now treat higher dimensions as linear vectors + J=['[',num2str(M(:)'),']']; % and of destroying dimensionality + J=regexprep(J,'\s+',','); + end + end + else + J=['"',M,'"']; % otherwise it is treated as a string + end +end + +if nargin>1 %save JSON result in file + fid=fopen(F,'w'); + fprintf(fid,'%s',J); + fclose(fid); +end \ No newline at end of file diff --git a/swig/matlab/modelserviceContainer/json4mat/parse_json.m b/swig/matlab/modelserviceContainer/json4mat/parse_json.m new file mode 100644 index 0000000..60c1d5d --- /dev/null +++ b/swig/matlab/modelserviceContainer/json4mat/parse_json.m @@ -0,0 +1,205 @@ +function data = parse_json(string) +% DATA = PARSE_JSON(string) +% This function parses a JSON string and returns a cell array with the +% parsed data. JSON objects are converted to structures and JSON arrays are +% converted to cell arrays. + +% F. Glineur, 2009 +% (inspired by the JSON parser by Joel Feenstra on MATLAB File Exchange +% (http://www.mathworks.com/matlabcentral/fileexchange/20565) but with +% faster handling of strings) + +pos = 1; +len = length(string); +% String delimiters and escape characters are identified beforehand to improve speed +esc = regexp(string, '["\\]'); index_esc = 1; len_esc = length(esc); + +if pos <= len + switch(next_char) + case '{' + data = parse_object; + case '[' + data = parse_array; + otherwise + error_pos('Outer level structure must be an object or an array'); + end +end + + function object = parse_object + parse_char('{'); + object = []; + if next_char ~= '}' + while 1 + str = parse_string; + if isempty(str) + error_pos('Name of value at position %d cannot be empty'); + end + parse_char(':'); + val = parse_value; + object.(valid_field(str)) = val; + if next_char == '}' + break; + end + parse_char(','); + end + end + parse_char('}'); + end + + function object = parse_array + parse_char('['); + object = cell(0, 1); + if next_char ~= ']' + while 1 + val = parse_value; + object{end+1} = val; + if next_char == ']' + break; + end + parse_char(','); + end + end + parse_char(']'); + end + + function parse_char(c) + skip_whitespace; + if pos > len || string(pos) ~= c + error_pos(sprintf('Expected %c at position %%d', c)); + else + pos = pos + 1; + skip_whitespace; + end + end + + function c = next_char + skip_whitespace; + if pos > len + c = []; + else + c = string(pos); + end + end + + function skip_whitespace + while pos <= len && isspace(string(pos)) + pos = pos + 1; + end + end + + function str = parse_string + if string(pos) ~= '"' + error_pos('String starting with " expected at position %d'); + else + pos = pos + 1; + end + str = ''; + while pos <= len + while index_esc <= len_esc && esc(index_esc) < pos + index_esc = index_esc + 1; + end + if index_esc > len_esc + str = [str string(pos:end)]; + pos = len + 1; + break; + else + str = [str string(pos:esc(index_esc)-1)]; + pos = esc(index_esc); + end + switch string(pos) + case '"' + pos = pos + 1; + return; + case '\' + if pos+1 > len + error_pos('End of file reached right after escape character'); + end + pos = pos + 1; + switch string(pos) + case {'"' '\' '/'} + str(end+1) = string(pos); + pos = pos + 1; + case {'b' 'f' 'n' 'r' 't'} + str(end+1) = sprintf(['\' string(pos)]); + pos = pos + 1; + case 'u' + if pos+4 > len + error_pos('End of file reached in escaped unicode character'); + end + str(end+1:end+6) = string(pos-1:pos+4); + pos = pos + 5; + end + otherwise % should never happen + str(end+1) = string(pos); + pos = pos + 1; + end + end + error_pos('End of file while expecting end of string'); + end + + function num = parse_number + [num, one, err, delta] = sscanf(string(pos:min(len,pos+20)), '%f', 1); % TODO : compare with json(pos:end) + if ~isempty(err) + error_pos('Error reading number at position %d'); + end + pos = pos + delta-1; + end + + function val = parse_value + switch(string(pos)) + case '"' + val = parse_string; + return; + case '[' + val = parse_array; + return; + case '{' + val = parse_object; + return; + case {'-','0','1','2','3','4','5','6','7','8','9'} + val = parse_number; + return; + case 't' + if pos+3 <= len && strcmpi(string(pos:pos+3), 'true') + val = true; + pos = pos + 4; + return; + end + case 'f' + if pos+4 <= len && strcmpi(string(pos:pos+4), 'false') + val = false; + pos = pos + 5; + return; + end + case 'n' + if pos+3 <= len && strcmpi(string(pos:pos+3), 'null') + val = []; + pos = pos + 4; + return; + end + end + error_pos('Value expected at position %d'); + end + + function error_pos(msg) + poss = max(min([pos-15 pos-1 pos pos+20],len),1); + if poss(3) == poss(2) + poss(3:4) = poss(2)+[0 -1]; % display nothing after + end + msg = [sprintf(msg, pos) ' : ... ' string(poss(1):poss(2)) '' string(poss(3):poss(4)) ' ... ']; + ME = MException('JSONparser:invalidFormat', msg); + throw(ME); + end + + function str = valid_field(str) + % From MATLAB doc: field names must begin with a letter, which may be + % followed by any combination of letters, digits, and underscores. + % Invalid characters will be converted to underscores, and the prefix + % "alpha_" will be added if first character is not a letter. + if ~isletter(str(1)) + str = ['alpha_' str]; + end + str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; + end + +end \ No newline at end of file diff --git a/swig/matlab/modelserviceContainer/json4mat/pub.m b/swig/matlab/modelserviceContainer/json4mat/pub.m new file mode 100644 index 0000000..0c6f320 --- /dev/null +++ b/swig/matlab/modelserviceContainer/json4mat/pub.m @@ -0,0 +1,3 @@ +%Publishes manual +close all;web(publish('json4mat_pub.m')) +web(publish('json4mat_pub.m','pdf')) \ No newline at end of file diff --git a/swig/matlab/modelserviceContainer/test.m b/swig/matlab/modelserviceContainer/test.m new file mode 100644 index 0000000..55f3a7a --- /dev/null +++ b/swig/matlab/modelserviceContainer/test.m @@ -0,0 +1,24 @@ +server = Server('127.0.0.1',8060); +access = server.getServiceAccess(); +list_ms = access.getModelServiceList(); +for index = 1: numel(list_ms) + disp(['ID : ',list_ms(index).id,' - Name : ',list_ms(index).name,' - Type : ',list_ms(index).type]) +end +dataid = access.uploadDataByFile('E:\NativeTest\TestData\TouchAir\input.xml','input.xml'); +if ~(strcmp(dataid,'')) + disp(['TouchAir - Data ID : ',dataid]); + % invoke model + touchair = access.getModelServiceByID('5aab9a194290c617a88f347b'); + pDataconfig = access.createDataConfigurationItem('aa00cced-60e7-48a5-90d2-f91ac08b624d','InputData',dataid); + recordid = touchair.invoke([pDataconfig]); + disp(['Invoke successfully! Model service Record ID is : [',recordid,']']); + record = access.getModelServiceRunningRecordByID(recordid); + record.waitForFinished(); + disp('TouchAir model has been finished') + for index = 1:numel(record.output) + item = record.output; + dat = access.getDataByID(item.dataid); + end +else + disp('upload data file failed'); +end -- Gitee From 3d92efbab98807db283c902ec0cc8db4e127625f Mon Sep 17 00:00:00 2001 From: wang ming <1508574735@qq.com> Date: Mon, 16 Apr 2018 11:47:29 +0800 Subject: [PATCH 5/8] update test content --- swig/matlab/modelserviceContainer/test.m | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/swig/matlab/modelserviceContainer/test.m b/swig/matlab/modelserviceContainer/test.m index 55f3a7a..948fb55 100644 --- a/swig/matlab/modelserviceContainer/test.m +++ b/swig/matlab/modelserviceContainer/test.m @@ -18,6 +18,12 @@ if ~(strcmp(dataid,'')) for index = 1:numel(record.output) item = record.output; dat = access.getDataByID(item.dataid); + % get file ext + % maybe use [filepath,name,ext] = fileparts(filename) + datavalue = dat.value; + [filename,name,ext] = fileparts(datavalue); + % save as file + dat.save(['E:\NativeTest\TestData\TouchAir\',item.eventname,ext]); end else disp('upload data file failed'); -- Gitee From c31d63854ae485a42ba7d27dfc6ae032d70a485f Mon Sep 17 00:00:00 2001 From: wang ming <1508574735@qq.com> Date: Mon, 16 Apr 2018 20:55:25 +0800 Subject: [PATCH 6/8] update the newest version --- .../+utils/urlreadpost.m | 6 +- swig/matlab/modelserviceContainer/Data.m | 30 ++-- .../modelserviceContainer/ModelService.m | 133 +++++++++++++++++- .../ModelServiceFactory.m | 54 ++++++- .../modelserviceContainer/ServiceAccess.m | 9 +- .../enumation/NjModelServiceLimitation.m | 19 +++ .../enumation/NjModelServicePermission.m | 18 +++ .../enumation/NjModelServiceStatus.m | 21 +++ .../enumation/NjPlatform.m | 19 +++ swig/matlab/modelserviceContainer/test.m | 2 +- 10 files changed, 294 insertions(+), 17 deletions(-) create mode 100644 swig/matlab/modelserviceContainer/enumation/NjModelServiceLimitation.m create mode 100644 swig/matlab/modelserviceContainer/enumation/NjModelServicePermission.m create mode 100644 swig/matlab/modelserviceContainer/enumation/NjModelServiceStatus.m create mode 100644 swig/matlab/modelserviceContainer/enumation/NjPlatform.m diff --git a/swig/matlab/modelserviceContainer/+utils/urlreadpost.m b/swig/matlab/modelserviceContainer/+utils/urlreadpost.m index ea80284..01b2e56 100644 --- a/swig/matlab/modelserviceContainer/+utils/urlreadpost.m +++ b/swig/matlab/modelserviceContainer/+utils/urlreadpost.m @@ -33,8 +33,10 @@ import com.mathworks.mlwidgets.io.InterruptibleStreamCopier; com.mathworks.mlwidgets.html.HTMLPrefs.setProxySettings % Check number of inputs and outputs. -error(nargchk(3,3,nargin)) -error(nargoutchk(0,2,nargout)) +%error(nargchk(3,3,nargin)) +%error(nargoutchk(0,2,nargout)) +narginchk(3,3) +nargoutchk(0,2) if ~ischar(urlChar) error('MATLAB:urlreadpost:InvalidInput','The first input, the URL, must be a character array.'); end diff --git a/swig/matlab/modelserviceContainer/Data.m b/swig/matlab/modelserviceContainer/Data.m index cd74002..8710fe7 100644 --- a/swig/matlab/modelserviceContainer/Data.m +++ b/swig/matlab/modelserviceContainer/Data.m @@ -1,14 +1,7 @@ classdef Data Date: Tue, 17 Apr 2018 19:29:38 +0800 Subject: [PATCH 7/8] update function --- .../ModelServiceRunningRecord.asv | 166 ++++++++++++++++++ .../ModelServiceRunningRecord.m | 95 +++++++++- .../modelserviceContainer/RunningLog.asv | 60 +++++++ .../matlab/modelserviceContainer/RunningLog.m | 60 +++++++ .../modelserviceContainer/ServiceAccess.m | 2 +- swig/matlab/modelserviceContainer/test.m | 14 +- 6 files changed, 393 insertions(+), 4 deletions(-) create mode 100644 swig/matlab/modelserviceContainer/ModelServiceRunningRecord.asv create mode 100644 swig/matlab/modelserviceContainer/RunningLog.asv create mode 100644 swig/matlab/modelserviceContainer/RunningLog.m diff --git a/swig/matlab/modelserviceContainer/ModelServiceRunningRecord.asv b/swig/matlab/modelserviceContainer/ModelServiceRunningRecord.asv new file mode 100644 index 0000000..768ba6c --- /dev/null +++ b/swig/matlab/modelserviceContainer/ModelServiceRunningRecord.asv @@ -0,0 +1,166 @@ +classdef ModelServiceRunningRecord Date: Thu, 19 Apr 2018 15:19:58 +0800 Subject: [PATCH 8/8] update function about instance, to be achieve in the future --- .../+HttpHelper/Request_put.m | 9 + .../+utils/http_createHeader.m | 11 + .../+utils/http_paramsToString.m | 63 +++ .../modelserviceContainer/+utils/urlread2.m | 371 ++++++++++++++++++ .../ModelServiceInstance.m | 136 +++++++ .../ModelServiceInstanceFactory.m | 19 + .../ModelServiceRunningRecord.asv | 166 -------- .../ModelServiceRunningRecord.m | 1 + .../ModelServiceRunningRecordFactory.m | 36 ++ .../modelserviceContainer/RunningLog.asv | 60 --- swig/matlab/modelserviceContainer/Server.m | 12 + swig/matlab/modelserviceContainer/Service.m | 10 + .../modelserviceContainer/ServiceAccess.m | 7 +- .../enumation/NjDataType.m | 19 + .../enumation/NjModelInstanceStatus.m | 19 + .../enumation/NjModelServiceLimitation.m | 6 +- .../enumation/NjModelServicePermission.m | 6 +- .../enumation/NjPlatform.m | 6 +- .../enumation/NjRecordStatus.m | 19 + swig/matlab/modelserviceContainer/test.m | 4 +- 20 files changed, 742 insertions(+), 238 deletions(-) create mode 100644 swig/matlab/modelserviceContainer/+HttpHelper/Request_put.m create mode 100644 swig/matlab/modelserviceContainer/+utils/http_createHeader.m create mode 100644 swig/matlab/modelserviceContainer/+utils/http_paramsToString.m create mode 100644 swig/matlab/modelserviceContainer/+utils/urlread2.m create mode 100644 swig/matlab/modelserviceContainer/ModelServiceInstance.m create mode 100644 swig/matlab/modelserviceContainer/ModelServiceInstanceFactory.m delete mode 100644 swig/matlab/modelserviceContainer/ModelServiceRunningRecord.asv create mode 100644 swig/matlab/modelserviceContainer/ModelServiceRunningRecordFactory.m delete mode 100644 swig/matlab/modelserviceContainer/RunningLog.asv create mode 100644 swig/matlab/modelserviceContainer/enumation/NjDataType.m create mode 100644 swig/matlab/modelserviceContainer/enumation/NjModelInstanceStatus.m create mode 100644 swig/matlab/modelserviceContainer/enumation/NjRecordStatus.m diff --git a/swig/matlab/modelserviceContainer/+HttpHelper/Request_put.m b/swig/matlab/modelserviceContainer/+HttpHelper/Request_put.m new file mode 100644 index 0000000..80a670e --- /dev/null +++ b/swig/matlab/modelserviceContainer/+HttpHelper/Request_put.m @@ -0,0 +1,9 @@ +function [ jsData ] = Request_put( ip,port,path ) +%REQUEST_PUT ˴ʾйش˺ժҪ +% ˴ʾϸ˵ + url = ['http://',ip,':',num2str(port),'/',path]; + [jsData,extras] = urlread2(url,'PUT'); + jsData = parse_json(jsData); + +end + diff --git a/swig/matlab/modelserviceContainer/+utils/http_createHeader.m b/swig/matlab/modelserviceContainer/+utils/http_createHeader.m new file mode 100644 index 0000000..0e80241 --- /dev/null +++ b/swig/matlab/modelserviceContainer/+utils/http_createHeader.m @@ -0,0 +1,11 @@ +function header = http_createHeader(name,value) +%http_createHeader Simple function for creating input header to urlread2 +% +% header = http_createHeader(name,value) +% +% CODE: header = struct('name',name,'value',value); +% +% See Also: +% urlread2 + +header = struct('name',name,'value',value); \ No newline at end of file diff --git a/swig/matlab/modelserviceContainer/+utils/http_paramsToString.m b/swig/matlab/modelserviceContainer/+utils/http_paramsToString.m new file mode 100644 index 0000000..f9251be --- /dev/null +++ b/swig/matlab/modelserviceContainer/+utils/http_paramsToString.m @@ -0,0 +1,63 @@ +function [str,header] = http_paramsToString(params,encodeOption) +%http_paramsToString Creates string for a POST or GET requests +% +% [queryString,header] = http_paramsToString(params, *encodeOption) +% +% INPUTS +% ======================================================================= +% params: cell array of property/value pairs +% NOTE: If the input is in a 2 column matrix, then first column +% entries are properties and the second column entries are +% values, however this is NOT necessary (generally linear) +% encodeOption: (default 1) +% 1 - the typical URL encoding scheme (Java call) +% +% OUTPUTS +% ======================================================================= +% queryString: querystring to add onto URL (LACKS "?", see example) +% header : the header that should be attached for post requests when +% using urlread2 +% +% EXAMPLE: +% ============================================================== +% params = {'cmd' 'search' 'db' 'pubmed' 'term' 'wtf batman'}; +% queryString = http_paramsToString(params); +% queryString => cmd=search&db=pubmed&term=wtf+batman +% +% IMPORTANT: This function does not filter parameters, sort them, +% or remove empty inputs (if necessary), this must be done before hand + +if ~exist('encodeOption','var') + encodeOption = 1; +end + +if size(params,2) == 2 && size(params,1) > 1 + params = params'; + params = params(:); +end + +str = ''; +for i=1:2:length(params) + if (i == 1), separator = ''; else separator = '&'; end + switch encodeOption + case 1 + param = urlencode(params{i}); + value = urlencode(params{i+1}); +% case 2 +% param = oauth.percentEncodeString(params{i}); +% value = oauth.percentEncodeString(params{i+1}); +% header = http_getContentTypeHeader(1); + otherwise + error('Case not used') + end + str = [str separator param '=' value]; %#ok +end + +switch encodeOption + case 1 + header = http_createHeader('Content-Type','application/x-www-form-urlencoded'); + %header = http_createHeader('Content-Type','multipart/form-data'); +end + + +end \ No newline at end of file diff --git a/swig/matlab/modelserviceContainer/+utils/urlread2.m b/swig/matlab/modelserviceContainer/+utils/urlread2.m new file mode 100644 index 0000000..b552861 --- /dev/null +++ b/swig/matlab/modelserviceContainer/+utils/urlread2.m @@ -0,0 +1,371 @@ +function [output,extras] = urlread2(urlChar,method,body,headersIn,varargin) +%urlread2 Makes HTTP requests and processes response +% +% [output,extras] = urlread2(urlChar, *method, *body, *headersIn, varargin) +% +% * indicates optional inputs that must be entered in place +% +% UNDOCUMENTED MATLAB VERSION +% +% EXAMPLE CALLING FORMS +% ... = urlread2(urlChar) +% ... = urlread2(urlChar,'GET','',[],prop1,value1,prop2,value2,etc) +% ... = urlread2(urlChar,'POST',body,headers) +% +% FEATURES +% ======================================================================= +% 1) Allows specification of any HTTP method +% 2) Allows specification of any header. Very little is hard-coded +% in for header handling. +% 3) Returns response status and headers +% 4) Should handle unicode properly ... +% +% OUTPUTS +% ======================================================================= +% output : body of the response, either text or binary depending upon +% CAST_OUTPUT property +% extras : (structure) +% .allHeaders - stucture, fields have cellstr values, HTTP headers may +% may be repeated but will have a single field entry, with each +% repeat's value another being another entry in the cellstr, for +% example: +% .Set_Cookie = {'first_value' 'second_value'} +% .firstHeaders - (structure), variable fields, contains the first +% string entry for each field in allHeaders, this +% structure can be used to avoid dereferencing a cell +% for fields you expect not to be repeated ... +% EXAMPLE: +% .Response : 'HTTP/1.1 200 OK'} +% .Server : 'nginx' +% .Date : 'Tue, 29 Nov 2011 02:23:16 GMT' +% .Content_Type : 'text/html; charset=UTF-8' +% .Content_Length : '109155' +% .Connection : 'keep-alive' +% .Vary : 'Accept-Encoding, User-Agent' +% .Cache_Control : 'max-age=60, private' +% .Set_Cookie : 'first_value' +% .status - (structure) +% .value : numeric value of status, ex. 200 +% .msg : message that goes along with status, ex. 'OK' +% .url - eventual url that led to output, this can change from +% the input with redirects, see FOLLOW_REDIRECTS +% .isGood - (logical) I believe this is an indicator of the presence of 400 +% or 500 status codes (see status.value) but more +% testing is needed. In other words, true if status.value < 400. +% In code, set true if the response was obtainable without +% resorting to checking the error stream. +% +% INPUTS +% ======================================================================= +% urlChar : The full url, must include scheme (http, https) +% method : examples: 'GET' 'POST' etc +% body : (vector)(char, uint8 or int8) body to write, generally used +% with POST or PUT, use of uint8 or int8 ensures that the +% body input is not manipulated before sending, char is sent +% via unicode2native function with ENCODING input (see below) +% headersIn : (structure array), use empty [] or '' if no headers are needed +% but varargin property/value pairs are, multiple headers +% may be passed in as a structure array +% .name - (string), name of the header, a name property is used +% instead of a field because the name must match a valid +% header +% .value - (string), value to use +% +% OPTIONAL INPUTS (varargin, property/value pairs) +% ======================================================================= +% CAST_OUTPUT : (default true) output is uint8, useful if the body +% of the response is not text +% ENCODING : (default ''), ENCODING input to function unicode2native +% FOLLOW_REDIRECTS : (default true), if false 3xx status codes will +% be returned and need to be handled by the user, +% note this does not handle javascript or meta tag +% redirects, just server based ones +% READ_TIMEOUT : (default 0), 0 means no timeout, value is in +% milliseconds +% +% EXAMPLES +% ======================================================================= +% GET: +% -------------------------------------------- +% url = 'http://www.mathworks.com/matlabcentral/fileexchange/'; +% query = 'urlread2'; +% params = {'term' query}; +% queryString = http_paramsToString(params,1); +% url = [url '?' queryString]; +% [output,extras] = urlread2(url); +% +% POST: +% -------------------------------------------- +% url = 'http://posttestserver.com/post.php'; +% params = {'testChars' char([2500 30000]) 'new code' '?'}; +% [paramString,header] = http_paramsToString(params,1); +% [output,extras] = urlread2(url,'POST',paramString,header); +% +% From behind a firewall, use the Preferences to set your proxy server. +% +% See Also: +% http_paramsToString +% unicode2native +% native2unicode +% +% Subfunctions: +% fixHeaderCasing - small subfunction to fix case errors encountered in real +% world, requires updating when casing doesn't match expected form, like +% if someone sent the header content-Encoding instead of +% Content-Encoding +% +% Based on original urlread code by Matthew J. Simoneau +% +% VERSION = 1.1 + +in.CAST_OUTPUT = true; +in.FOLLOW_REDIRECTS = true; +in.READ_TIMEOUT = 0; +in.ENCODING = ''; + +%Input handling +%--------------------------------------- +if ~isempty(varargin) + for i = 1:2:numel(varargin) + prop = upper(varargin{i}); + value = varargin{i+1}; + if isfield(in,prop) + in.(prop) = value; + else + error('Unrecognized input to function: %s',prop) + end + end +end + +if ~exist('method','var') || isempty(method), method = 'GET'; end +if ~exist('body','var'), body = ''; end +if ~exist('headersIn','var'), headersIn = []; end + +assert(usejava('jvm'),'Function requires Java') + +import com.mathworks.mlwidgets.io.InterruptibleStreamCopier; +com.mathworks.mlwidgets.html.HTMLPrefs.setProxySettings %Proxy settings need to be set + +%Create a urlConnection. +%----------------------------------- +urlConnection = getURLConnection(urlChar); +%For HTTP uses sun.net.www.protocol.http.HttpURLConnection +%Might use ice.net.HttpURLConnection but this has more overhead + +%SETTING PROPERTIES +%------------------------------------------------------- +urlConnection.setRequestMethod(upper(method)); +urlConnection.setFollowRedirects(in.FOLLOW_REDIRECTS); +urlConnection.setReadTimeout(in.READ_TIMEOUT); + +for iHeader = 1:length(headersIn) + curHeader = headersIn(iHeader); + urlConnection.setRequestProperty(curHeader.name,curHeader.value); +end + +if ~isempty(body) + %Ensure vector? + if size(body,1) > 1 + if size(body,2) > 1 + error('Input parameter to function: body, must be a vector') + else + body = body'; + end + end + + if ischar(body) + %NOTE: '' defaults to Matlab's default encoding scheme + body = unicode2native(body,in.ENCODING); + elseif ~(strcmp(class(body),'uint8') || strcmp(class(body),'int8')) + error('Function input: body, should be of class char, uint8, or int8, detected: %s',class(body)) + end + + urlConnection.setRequestProperty('Content-Length',int2str(length(body))); + urlConnection.setDoOutput(true); + outputStream = urlConnection.getOutputStream; + outputStream.write(body); + outputStream.close; +else + urlConnection.setRequestProperty('Content-Length','0'); +end + +%========================================================================== +% Read the data from the connection. +%========================================================================== +%This should be done first because it tells us if things are ok or not +%NOTE: If there is an error, functions below using urlConnection, notably +%getResponseCode, will fail as well +try + inputStream = urlConnection.getInputStream; + isGood = true; +catch ME + isGood = false; +%NOTE: HTTP error codes will throw an error here, we'll allow those for now +%We might also get another error in which case the inputStream will be +%undefined, those we will throw here + inputStream = urlConnection.getErrorStream; + + if isempty(inputStream) + msg = ME.message; + I = strfind(msg,char([13 10 9])); %see example by setting timeout to 1 + %Should remove the barf of the stack, at ... at ... at ... etc + %Likely that this could be improved ... (generate link with full msg) + if ~isempty(I) + msg = msg(1:I(1)-1); + end + fprintf(2,'Response stream is undefined\n below is a Java Error dump (truncated):\n'); + error(msg) + end +end + +%POPULATING HEADERS +%-------------------------------------------------------------------------- +allHeaders = struct; +allHeaders.Response = {char(urlConnection.getHeaderField(0))}; +done = false; +headerIndex = 0; + +while ~done + headerIndex = headerIndex + 1; + headerValue = char(urlConnection.getHeaderField(headerIndex)); + if ~isempty(headerValue) + headerName = char(urlConnection.getHeaderFieldKey(headerIndex)); + headerName = fixHeaderCasing(headerName); %NOT YET FINISHED + + %Important, for name safety all hyphens are replace with underscores + headerName(headerName == '-') = '_'; + if isfield(allHeaders,headerName) + allHeaders.(headerName) = [allHeaders.(headerName) headerValue]; + else + allHeaders.(headerName) = {headerValue}; + end + else + done = true; + end +end + +firstHeaders = struct; +fn = fieldnames(allHeaders); +for iHeader = 1:length(fn) + curField = fn{iHeader}; + firstHeaders.(curField) = allHeaders.(curField){1}; +end + +status = struct(... + 'value', urlConnection.getResponseCode(),... + 'msg', char(urlConnection.getResponseMessage)); + +%PROCESSING OF OUTPUT +%---------------------------------------------------------- +byteArrayOutputStream = java.io.ByteArrayOutputStream; +% This StreamCopier is unsupported and may change at any time. OH GREAT :/ +isc = InterruptibleStreamCopier.getInterruptibleStreamCopier; +isc.copyStream(inputStream,byteArrayOutputStream); +inputStream.close; +byteArrayOutputStream.close; + +if in.CAST_OUTPUT + charset = ''; + + %Extraction of character set from Content-Type header if possible + if isfield(firstHeaders,'Content_Type') + text = firstHeaders.Content_Type; + %Always open to regexp improvements + charset = regexp(text,'(?<=charset=)[^\s]*','match','once'); + end + + if ~isempty(charset) + output = native2unicode(typecast(byteArrayOutputStream.toByteArray','uint8'),charset); + else + output = char(typecast(byteArrayOutputStream.toByteArray','uint8')); + end +else + %uint8 is more useful for later charecter conversions + %uint8 or int8 is somewhat arbitary at this point + output = typecast(byteArrayOutputStream.toByteArray','uint8'); +end + +extras = struct; +extras.allHeaders = allHeaders; +extras.firstHeaders = firstHeaders; +extras.status = status; +%Gets eventual url even with redirection +extras.url = char(urlConnection.getURL); +extras.isGood = isGood; + + + +end + +function headerNameOut = fixHeaderCasing(headerName) +%fixHeaderCasing Forces standard casing of headers +% +% headerNameOut = fixHeaderCasing(headerName) +% +% This is important for field access in a structure which +% is case sensitive +% +% Not yet finished. +% I've been adding to this function as problems come along + + switch lower(headerName) + case 'location' + headerNameOut = 'Location'; + case 'content_type' + headerNameOut = 'Content_Type'; + otherwise + headerNameOut = headerName; + end +end + +%========================================================================== +%========================================================================== +%========================================================================== + +function urlConnection = getURLConnection(urlChar) +%getURLConnection +% +% urlConnection = getURLConnection(urlChar) + +% Determine the protocol (before the ":"). +protocol = urlChar(1:find(urlChar==':',1)-1); + + +% Try to use the native handler, not the ice.* classes. +try + switch protocol + case 'http' + %http://www.docjar.com/docs/api/sun/net/www/protocol/http/HttpURLConnection.html + handler = sun.net.www.protocol.http.Handler; + case 'https' + handler = sun.net.www.protocol.https.Handler; + end +catch ME + handler = []; +end + +% Create the URL object. +try + if isempty(handler) + url = java.net.URL(urlChar); + else + url = java.net.URL([],urlChar,handler); + end +catch ME + error('Failure to parse URL or protocol not supported for:\nURL: %s',urlChar); +end + +% Get the proxy information using MathWorks facilities for unified proxy +% preference settings. +mwtcp = com.mathworks.net.transport.MWTransportClientPropertiesFactory.create(); +proxy = mwtcp.getProxy(); + +% Open a connection to the URL. +if isempty(proxy) + urlConnection = url.openConnection; +else + urlConnection = url.openConnection(proxy); +end + + +end diff --git a/swig/matlab/modelserviceContainer/ModelServiceInstance.m b/swig/matlab/modelserviceContainer/ModelServiceInstance.m new file mode 100644 index 0000000..14284f0 --- /dev/null +++ b/swig/matlab/modelserviceContainer/ModelServiceInstance.m @@ -0,0 +1,136 @@ +classdef ModelServiceInstance 65535 || port < 0) + result = -1; + return; + end + self.setPort(port); + result = 1; + end + + + end end diff --git a/swig/matlab/modelserviceContainer/Service.m b/swig/matlab/modelserviceContainer/Service.m index b576d2f..f50311a 100644 --- a/swig/matlab/modelserviceContainer/Service.m +++ b/swig/matlab/modelserviceContainer/Service.m @@ -26,6 +26,16 @@ classdef Service