From e015cf4881dd66ab808aed6e59ec99bc32f1f116 Mon Sep 17 00:00:00 2001 From: lifansheng Date: Tue, 21 Dec 2021 16:36:57 +0800 Subject: [PATCH 1/5] Signed-off-by: lifansheng On branch master Your branch is up to date with 'origin/master'. --- README.md | 254 +++-- README_zh.md | 255 +++-- convertxml/build_ts_js.py => build_ts_js.py | 24 +- convertxml/BUILD.gn | 222 ++-- convertxml/js_convertxml.cpp | 10 +- convertxml/js_convertxml.h | 132 +-- convertxml/native_module_convertxml.cpp | 33 +- convertxml/src/js_convertxml.ts | 4 +- convertxml/tsconfig.json | 4 +- mgit.info | 1 + mozilla_docs.txt | 44 - ohos.build | 6 +- test_uri/unittest/BUILD.gn | 2 +- test_uri/unittest/test_ark.cpp | 2 +- .../unittest/BUILD.gn | 81 +- test_xml/unittest/test.h | 33 + test_xml/unittest/test_ark.cpp | 62 ++ test_xml/unittest/test_xml.cpp | 961 ++++++++++++++++++ uri/BUILD.gn | 8 +- uri/js_uri.cpp | 4 +- uri/native_module_uri.cpp | 34 +- uri/src/js_uri.ts | 4 +- uri/tsconfig.json | 6 +- url/BUILD.gn | 10 +- url/build_ts_js.py | 55 - url/js_url.cpp | 150 ++- url/native_module_url.cpp | 31 +- url/src/js_url.ts | 2 +- url/tsconfig.json | 6 +- xml/BUILD.gn | 6 +- xml/build_ts_js.py | 54 - xml/js_xml.cpp | 412 ++++---- xml/js_xml.h | 103 +- xml/native_module_xml.cpp | 25 +- xml/src/js_xml.ts | 139 ++- xml/tsconfig.json | 4 +- 36 files changed, 2227 insertions(+), 956 deletions(-) rename convertxml/build_ts_js.py => build_ts_js.py (71%) mode change 100755 => 100644 create mode 100644 mgit.info delete mode 100644 mozilla_docs.txt rename uri/build_ts_js.py => test_xml/unittest/BUILD.gn (31%) mode change 100755 => 100644 create mode 100644 test_xml/unittest/test.h create mode 100644 test_xml/unittest/test_ark.cpp create mode 100644 test_xml/unittest/test_xml.cpp delete mode 100755 url/build_ts_js.py delete mode 100644 xml/build_ts_js.py diff --git a/README.md b/README.md index 06197679..4df80fe2 100755 --- a/README.md +++ b/README.md @@ -16,63 +16,80 @@ URI Represents a Uniform Resource Identifier (URI) reference. XML representation refers to extensible markup language. +The XmlSerializer interface is used to generate an xml file. The constructor of XmlSerializer creates a new XmlSerializer object, and calls the method of the XmlSerializer object to generate an xml file. The XmlPullParser interface is used to parse the existing xml file. The constructor of XmlPullParser creates a new XmlPullParser object, and calls the method of the XmlPullParser object to parse the xml file. + ## Contents ``` base/compileruntime/js_api_module/ -├── Class:URL # URL class -│ ├── new URL(input[, base]) # Create URL object -│ ├── hash # hash attribute -│ ├── host # host attribute -│ ├── hostname # hostname attribute -│ ├── href # href attribute -│ ├── origin # origin attribute -│ ├── password # password attribute -│ ├── pathname # pathname attribute -│ ├── port # port attribute -│ ├── protocol # protocol attribute -│ ├── search # search attribute -│ ├── searchParams # searchParams attribute -│ ├── username # username attribute -│ ├── toString() # toString method -│ └── toJSON() # toJSON method -├── Class: URLSearchParams # URLSearchParams class -│ ├── new URLSearchParams() # Create URLSearchParams object -│ ├── new URLSearchParams(string) # Create URLSearchParams object -│ ├── new URLSearchParams(obj) # Create URLSearchParams object -│ ├── new URLSearchParams(iterable) # Create URLSearchParams object -│ ├── append(name, value) # append method -│ ├── delete(name) # delete method -│ ├── entries() # entries method -│ ├── forEach(fn[, thisArg]) # forEach method -│ ├── get(name) # get method -│ ├── getAll(name) # getAll method -│ ├── has(name) # has method -│ ├── keys() # keys method -│ ├── set(name, value) # set method -│ ├── sort() # sort method -│ ├── toString() # toString method -│ ├── values() # values method -│ └── urlSearchParams[Symbol.iterator]() # Create URLSearchParams object -├── Class:URI # URI class -│ ├── URI(String str) # URI class -│ ├── scheme # Create URI object -│ ├── authority # scheme attribute -│ ├── ssp # authority attribute -│ ├── userinfo # ssp attribute -│ ├── host # userinfo attribute -│ ├── port # host attribute -│ ├── query # port attribute -│ ├── fragment # query attribute -│ ├── path # fragment attribute -│ ├── equals(Object ob) # path method -│ ├── normalize() # equals method -│ ├── isAbsolute() # normalize method -│ ├── normalize() # isAbsolute method -│ └── toString() # normalize method -└── Class:ConvertXml # ConvertXml class - ├── ConvertXml() # Create convertxml class object - └── convert(String xml, Object options) # Convert method +├── Class:URL # URL class +│ ├── new URL(input[, base]) # Create URL object +│ ├── hash # hash attribute +│ ├── host # host attribute +│ ├── hostname # hostname attribute +│ ├── href # href attribute +│ ├── origin # origin attribute +│ ├── password # password attribute +│ ├── pathname # pathname attribute +│ ├── port # port attribute +│ ├── protocol # protocol attribute +│ ├── search # search attribute +│ ├── searchParams # searchParams attribute +│ ├── username # username attribute +│ ├── toString() # toString method +│ └── toJSON() # toJSON method +├── Class: URLSearchParams # URLSearchParams class +│ ├── new URLSearchParams() # Create URLSearchParams object +│ ├── new URLSearchParams(string) # Create URLSearchParams object +│ ├── new URLSearchParams(obj) # Create URLSearchParams object +│ ├── new URLSearchParams(iterable) # Create URLSearchParams object +│ ├── append(name, value) # append method +│ ├── delete(name) # delete method +│ ├── entries() # entries method +│ ├── forEach(fn[, thisArg]) # forEach method +│ ├── get(name) # get method +│ ├── getAll(name) # getAll method +│ ├── has(name) # has method +│ ├── keys() # keys method +│ ├── set(name, value) # set method +│ ├── sort() # sort method +│ ├── toString() # toString method +│ ├── values() # values method +│ └── urlSearchParams[Symbol.iterator]() # Create URLSearchParams object +├── Class:URI # URI class +│ ├── URI(str: string) # Create URI object +│ ├── scheme # scheme attribute +│ ├── authority # authority attribute +│ ├── ssp # ssp attribute +│ ├── userinfo # userinfo attribute +│ ├── host # host attribute +│ ├── port # port attribute +│ ├── query # query attribute +│ ├── fragment # fragment attribute +│ ├── path # path method +│ ├── equals(ob: Object) # equals method +│ ├── normalize() # normalize method +│ ├── checkIsAbsolute() # checkIsAbsolute method +│ ├── normalize() # normalize method +│ ├── toString() # toString method +├── Class:ConvertXml # ConvertXml class +│ ├── ConvertXml() # Create convertxml class object +│ └── convert(xml: string, options: Object) # convert method +├── Class:XmlSerializer # XmlSerializer class +│ ├── new XmlSerializer(buffer: ArrayBuffer | DataView, encoding?: string) # Create XmlSerializer class object +│ ├── setAttributes(name: string, value: string) # Set Attributes method +│ ├── addEmptyElement(name: string) # Add an empty element method +│ ├── setDeclaration() # Set the Declaration method +│ ├── startElement(name: string) # Set the start element method +│ ├── endElement() # Set the end element method +│ ├── setNamespace(prefix: string, namespace: string) # Namespace method +│ ├── setCommnet(text: string) # Set up Commnet method +│ ├── setCData(text: string) # Set the CData method +│ ├── setText(text: string) # Set the Text method +│ ├── setDocType(text: string) # Set DocType method +└── Class: XmlPullParser # XmlPullParser class + ├── new (buffer: ArrayBuffer | DataView, encoding?: string) # Create XmlPullParser object + └── parse(option: ParseOptions) # parse method ``` ## Illustrate @@ -80,7 +97,7 @@ base/compileruntime/js_api_module/ ### Interface Description -| Interface name | Illustrate | +| Interface name | Illustrate | | -------- | -------- | | new URL(url: string,base?:string \| URL) | Create and return a URL object that references the URL specified by the absolute URL string, the relative URL string, and the basic URL string. | | tostring():string | The stringification method returns a USVString containing the complete URL. It is equivalent to the read-only URL.href. | @@ -102,7 +119,7 @@ base/compileruntime/js_api_module/ | entries(): iterableIterator<[string, string]> | Returns an iterator that allows iterating through all key/value pairs contained in the searchParams object. | | forEach(): void | Through the callback function to traverse the key-value pairs on the URLSearchParams instance object. | | urlSearchParams\[Symbol.iterator]() | Returns an ES6 iterator for each name-value pair in the query string. Each item of the iterator is a JavaScript array. | -| URI​(String str) | Construct the URI by parsing the given input parameter (String str). This constructor parses the given string strictly in accordance with the grammatical provisions in RFC 2396 Appendix A. | +| URI​(str: string) | Construct the URI by parsing the given input parameter (String str). This constructor parses the given string strictly in accordance with the grammatical provisions in RFC 2396 Appendix A. | | getScheme​() | Return the scheme component of this URI, or null if the scheme is not defined. | | getAuthority​() | Returns the decoded authority component of this URI, or null if authority is not defined. The string returned by this method is the same as the string returned by the getRawAuthority method, except that all escaped octet sequences are decoded. | | getSchemeSpecificPart​() | Returns the decoding scheme-specific part of this URI. The string returned by this method is the same as the string returned by the getRawSchemeSpecificPart method, except that all escaped octet sequences are decoded. | @@ -112,17 +129,30 @@ base/compileruntime/js_api_module/ | getQuery​() | Returns the decoded query component of this URI, or null if the query is not defined. The string returned by this method is the same as the string returned by the getRawQuery method, except that all escaped octet sequences are decoded. | | getFragment​() | Returns the decoded fragment component of this URI, or null if the fragment is not defined. The string returned by this method is the same as the string returned by the getRawFragment method, except that all escaped octet sequences are decoded. | | getPath​() | Returns the decoded path component of this URI, or null if path is not defined. The string returned by this method is the same as the string returned by the getRawPath method, except that all escaped octet sequences are decoded. | -| equals(Object ob) | Test whether this URI is equal to another object. If the given object is not a URI, this method immediately returns false. | +| equals(ob: Object) | Test whether this URI is equal to another object. If the given object is not a URI, this method immediately returns false. | | normalize​() | Normalize the path of this URI. If this URI is opaque, or its path is already in normal form, then this URI is returned. Otherwise, a new URI identical to this URI will be constructed. | -| isAbsolute​() | Determine whether this URI is absolute. If and only if it has a scheme component, the URI is absolute and the return value is true, otherwise the return value is false. | +| checkIsAbsolute() | Determine whether this URI is absolute. If and only if it has a scheme component, the URI is absolute and the return value is true, otherwise the return value is false. | | toString() | Return the content of this URI as a string. | | ConvertXml() | The constructor used to construct the convertxml class object. This constructor does not need to pass in parameters. | -| convert(String xml, Object options) | Returns a JavaScript object that converts an XML string as required by the option. | - +| convert(xml: string, options: Object) | Returns a JavaScript object that converts an XML string as required by the option. | +| XmlSerializer(buffer: ArrayBuffer \| DataView, encoding?: string) | Create and return an XmlSerializer object. The XmlSerializer object passes two parameters. The first parameter is ArrayBuffer or DataView, and the second parameter is the file format (UTF-8 by default). | +| setAttributes(name: string, value: string): void | Write the Attributes attribute to the xml file. | +| addEmptyElement(name: string): void | Write an empty element. | +| setDeclaration(): void | Set the Declaration to use the encoding to write the xml declaration. For example: | +| startElement(name: string): void | Write the elemnet start tag with the given name.| +| endElement(): void | Write the end tag of the element. | +| setNamespace(prefix: string, namespace: string): void | Write the namespace of the current element tag. | +| setCommnet(text: string): void | Write the comment attribute. | +| setCData(text: string): void | Write the CData attribute. | +| setText(text: string): void | Write the Text property. | +| setDocType(text: string): void | Write the DocType attribute. | +| XmlPullParser(buffer: ArrayBuffer \| DataView, encoding?: string) | Create and return an XmlPullParser object. The XmlPullParser object passes two parameters. The first parameter is ArrayBuffer or DataView, and the second parameter is the file format (default is UTF-8). | +| parse(option: ParseOptions): void | This interface is used to parse xml. The ParseOptions parameter is an interface containing five optional parameters {supportDoctype?: boolea ignoreNameSpace?: boolean tagValueCallbackFunction?: (name: string, value: string) => boolean attributeValueCallbackFunction?: (name: string, value: string) => boolean) tokenValueCallbackFunction?: (eventType: EventType, value: ParseInfo) => boolean }. The input parameter 1 of the tokenValueCallbackFunction callback function is the event type, and the input parameter 2 is the info interface containing get attributes such as getColumnNumber and getDepth. The user can obtain the depth and other information in the current parsing process through methods such as info.getDepth(). | ### Instructions for use The usage of each interface is as follows: + 1、new URL(url: string,base?:string|URL) ``` let b = new URL('https://developer.mozilla.org'); // => 'https://developer.mozilla.org/' @@ -134,7 +164,7 @@ let a = new URL( 'sca/./path/path/../scasa/text', 'http://www.example.com'); ``` const url = new URL('http://10.0xFF.O400.235:8080/directory/file?query#fragment'); url.toString() // => 'http://10.0xff.o400.235:8080/directory/file?query#fragment' - + const url = new URL("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"); url.toString() // => 'http://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/index.html' @@ -168,6 +198,7 @@ console.log(params.getAll('query')); 7、new URLSearchParams(iterable) ``` let params; + // Using an array params = new URLSearchParams([ ['user', 'abc'], @@ -246,6 +277,7 @@ for (const [name, value] of params) { // xyz ba ``` + 21、URI​(String str) ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); @@ -309,10 +341,10 @@ let res = gaogao.normalize(); console.log(res.path); // => "/path/path1" console.log(res.toString()); // => "http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/path1?query#fagment" ``` -33、isAbsolute​() +33、checkIsAbsolute() ``` let gaogao = new Uri.URI('f/tp://username:password@www.baidu.com:88/path?query#fagment'); -let res = gaogao.isAbsolute(); +let res = gaogao.checkIsAbsolute(); console.log(res); //=> false; ``` 34、toString() @@ -321,19 +353,107 @@ let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././ let res = gaogao.toString(); console.log(res.toString()); // => 'http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'; ``` + + 35、ConvertXml() ``` var convertml = new convertXml.ConvertXml(); ``` -36、convert(String xml, Object options) +36、convert(xml: string, options: Object) ``` var result = convertml.convert(xml, {compact: false, spaces: 4}); ``` +37、new XmlSerializer(buffer: ArrayBuffer | DataView, encoding?: string) +``` + +var arrayBuffer = new ArrayBuffer(1024); +var bufView = new DataView(arrayBuffer); +var thatSer = new xml.XmlSerializer(bufView); +``` +38、setDeclaration():void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setDeclaration() // => ; +``` +39、setCommnet(text: string):void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setCommnet("Hello, World!"); // => ; +``` +40、setCData(text: string) :void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setDocType('root SYSTEM "http://www.test.org/test.dtd"'); // => +``` +41、setDocType(text: string):void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setDocType("foo"); // => +``` +42、setNamespace(prefix: string, namespace: string): void +43、startElement(name: string): void +44、setAttributes(name: string, value: string): void +45、endElement(): void +46、setText(text: string): void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("table"); +thatSer.setAttributes("importance", "high"); +thatSer.setText("Happy"); +endElement(); // => Happy +``` +47、addEmptyElement(name: string): void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.addEmptyElement("b"); // => +``` +48、new (buffer: ArrayBuffer | DataView, encoding?: string) +``` +var strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +var arrayBuffer = new ArrayBuffer(strXml.length*2); +var bufView = new Uint8Array(arrayBuffer); +var strLen = strXml.length; +for (var i = 0; i < strLen; ++i) { + bufView[i] = strXml.charCodeAt(i);//设置arraybuffer 方式 +} +var that = new xml.XmlPullParser(arrayBuffer); + +``` +49、parse(option: ParseOptions): void +``` +var strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +var arrayBuffer = new ArrayBuffer(strXml.length*2); +var bufView = new Uint8Array(arrayBuffer); +var strLen = strXml.length; +for (var i = 0; i < strLen; ++i) { + bufView[i] = strXml.charCodeAt(i); +} +var that = new xml.XmlPullParser(arrayBuffer); +var arrTag = {}; +arrTag[0] = '132'; +var i = 1; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); + i++; + return true; +} +var options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; +that.parse(options); +``` ## Related warehouse [js_api_module Subsystem](https://gitee.com/OHOS_STD/js_api_module) [base/compileruntime/js_api_module/](base/compileruntime/js_api_module-readme.md) - -## License - -URL is available under [Mozilla license](https://www.mozilla.org/en-US/MPL/), and the documentation is detailed in [documentation](https://gitee.com/openharmony/js_api_module/blob/master/mozilla_docs.txt). See [LICENSE](https://gitee.com/openharmony/js_api_module/blob/master/LICENSE) for the full license text. \ No newline at end of file diff --git a/README_zh.md b/README_zh.md index 6366df05..991f5c2e 100755 --- a/README_zh.md +++ b/README_zh.md @@ -16,63 +16,80 @@ URI表示统一资源标识符引用。 xml表示指可扩展标记语言。 +XmlSerializer接口用于生成一个xml文件。 XmlSerializer的构造函数创建新的XmlSerializer对象,调用XmlSerializer对象的方法生成一个xml文件。XmlPullParser 接口用于解析已有的xml文件,XmlPullParser的构造函数创建新的XmlPullParser对象,调用XmlPullParser对象的方法解析xml。 + ## 目录 ``` base/compileruntime/js_api_module/ -├── Class:URL # URL类 -│ ├── new URL(input[, base]) # 创建URL对象 -│ ├── hash # hash属性 -│ ├── host # host属性 -│ ├── hostname # hostname属性 -│ ├── href # href属性 -│ ├── origin # origin属性 -│ ├── password # password属性 -│ ├── pathname # pathname属性 -│ ├── port # port属性 -│ ├── protocol # protocol属性 -│ ├── search # search属性 -│ ├── searchParams # searchParams属性 -│ ├── username # username属性 -│ ├── toString() # toString方法 -│ └── toJSON() # toJSON方法 -├── Class: URLSearchParams # URLSearchParams类 -│ ├── new URLSearchParams() # 创建URLSearchParams对象 -│ ├── new URLSearchParams(string) # 创建URLSearchParams对象 -│ ├── new URLSearchParams(obj) # 创建URLSearchParams对象 -│ ├── new URLSearchParams(iterable) # 创建URLSearchParams对象 -│ ├── append(name, value) # append方法 -│ ├── delete(name) # delete方法 -│ ├── entries() # entries方法 -│ ├── forEach(fn[, thisArg]) # forEach方法 -│ ├── get(name) # get方法 -│ ├── getAll(name) # getAll方法 -│ ├── has(name) # has方法 -│ ├── keys() # keys方法 -│ ├── set(name, value) # set方法 -│ ├── sort() # sort方法 -│ ├── toString() # toString方法 -│ ├── values() # values方法 -│ └── urlSearchParams[Symbol.iterator]() # 创建URLSearchParams对象 -├── Class:URI # URI类 -│ ├── URI(String str) # 创建URI对象 -│ ├── scheme # scheme属性 -│ ├── authority # authority属性 -│ ├── ssp # ssp属性 -│ ├── userinfo # userinfo属性 -│ ├── host # host属性 -│ ├── port # port属性 -│ ├── query # query属性 -│ ├── fragment # fragment属性 -│ ├── path # path属性 -│ ├── equals(Object ob) # equals方法 -│ ├── normalize() # normalize方法 -│ ├── isAbsolute() # isAbsolute方法 -│ ├── normalize() # normalize方法 -│ └── toString() # toString方法 -└── Class:ConvertXml # ConvertXml类 - ├── ConvertXml() # 创建ConvertXml类对象 - └── convert(String xml, Object options) # convert方法 +├── Class:URL # URL类 +│ ├── new URL(input[, base]) # 创建URL对象 +│ ├── hash # hash属性 +│ ├── host # host属性 +│ ├── hostname # hostname属性 +│ ├── href # href属性 +│ ├── origin # origin属性 +│ ├── password # password属性 +│ ├── pathname # pathname属性 +│ ├── port # port属性 +│ ├── protocol # protocol属性 +│ ├── search # search属性 +│ ├── searchParams # searchParams属性 +│ ├── username # username属性 +│ ├── toString() # toString方法 +│ └── toJSON() # toJSON方法 +├── Class: URLSearchParams # URLSearchParams类 +│ ├── new URLSearchParams() # 创建URLSearchParams对象 +│ ├── new URLSearchParams(string) # 创建URLSearchParams对象 +│ ├── new URLSearchParams(obj) # 创建URLSearchParams对象 +│ ├── new URLSearchParams(iterable) # 创建URLSearchParams对象 +│ ├── append(name, value) # append方法 +│ ├── delete(name) # delete方法 +│ ├── entries() # entries方法 +│ ├── forEach(fn[, thisArg]) # forEach方法 +│ ├── get(name) # get方法 +│ ├── getAll(name) # getAll方法 +│ ├── has(name) # has方法 +│ ├── keys() # keys方法 +│ ├── set(name, value) # set方法 +│ ├── sort() # sort方法 +│ ├── toString() # toString方法 +│ ├── values() # values方法 +│ └── urlSearchParams[Symbol.iterator]() # 创建URLSearchParams对象 +├── Class:URI # URI类 +│ ├── URI(str: string) # 创建URI对象 +│ ├── scheme # scheme属性 +│ ├── authority # authority属性 +│ ├── ssp # ssp属性 +│ ├── userinfo # userinfo属性 +│ ├── host # host属性 +│ ├── port # port属性 +│ ├── query # query属性 +│ ├── fragment # fragment属性 +│ ├── path # path属性 +│ ├── equals(ob: Object) # equals方法 +│ ├── normalize() # normalize方法 +│ ├── checkIsAbsolute() # checkIsAbsolute方法 +│ ├── normalize() # normalize方法 +│ └── toString() # toString方法 +├── Class:ConvertXml # ConvertXml类 +│ ├── ConvertXml() # 创建ConvertXml类对象 +│ └── convert(xml: string, options: Object) # convert方法 +├── Class:XmlSerializer # XmlSerializer类 +│ ├── new XmlSerializer(buffer: ArrayBuffer | DataView, encoding?: string) # 创建XmlSerializer类对象 +│ ├── setAttributes(name: string, value: string) # 设置Attributes方法 +│ ├── addEmptyElement(name: string) # 添加一个空元素方法 +│ ├── setDeclaration() # 设置Declaration方法 +│ ├── startElement(name: string) # 设置开始元素方法 +│ ├── endElement() # 设置结束元素方法 +│ ├── setNamespace(prefix: string, namespace: string) # 设置命名空间方法 +│ ├── setCommnet(text: string) # 设置Commnet方法 +│ ├── setCData(text: string) # 设置CData方法 +│ ├── setText(text: string) # 设置Text方法 +│ └── setDocType(text: string) # 设置DocType方法 +└── Class: XmlPullParser # XmlPullParser类 + ├── new (buffer: ArrayBuffer | DataView, encoding?: string) # 创建XmlPullParser对象 + └── parse(option: ParseOptions) # parse方法 ``` ## 说明 @@ -81,7 +98,7 @@ base/compileruntime/js_api_module/ | 接口名 | 说明 | -| -------- | -------- | +| -------- | -------- | | URL(url: string,base?:string \| URL) | 创建并返回一个URL对象,该URL对象引用使用绝对URL字符串,相对URL字符串和基本URL字符串指定的URL。 | | tostring():string | 该字符串化方法返回一个包含完整 URL 的 USVString。它的作用等同于只读的 URL.href。 | | toJSON():string | 该方法返回一个USVString,其中包含一个序列化的URL版本。 | @@ -102,7 +119,7 @@ base/compileruntime/js_api_module/ | entries(): iterableIterator<[string, string]> | 返回一个iterator,允许遍历searchParams对象中包含的所有键/值对。 | | forEach(): void | 通过回调函数来遍历URLSearchParams实例对象上的键值对。 | | urlSearchParams\[Symbol.iterator]() | 返回查询字符串中每个名称-值对的ES6迭代器。迭代器的每个项都是一个JavaScript数组。 | -| URI​(String str) | 通过解析给定入参(String str)来构造URI。此构造函数严格按照RFC 2396附录A中的语法规定解析给定字符串。 | +| URI​(str: string) | 通过解析给定入参(String str)来构造URI。此构造函数严格按照RFC 2396附录A中的语法规定解析给定字符串。 | | scheme​ | 返回此 URI 的scheme部分,如果scheme未定义,则返回 null | | authority​ | 返回此 URI 的解码authority部分,如果authority未定义,则返回 null。 | | ssp​ | 返回此 URI 的解码scheme-specific部分。 | @@ -110,18 +127,31 @@ base/compileruntime/js_api_module/ | host​ | 返回此 URI 的host部分,如果host未定义,则返回 null。 | | port​ | 返回此 URI 的port部分,如果port未定义,则返回 -1。URI 的port组件(如果已定义)是一个非负整数。 | | query​ | 返回此 URI 的query部分,如果query未定义,则返回 null。 | -| fragment​ | 返回此 URI 的解码fragment组件,如果fragment未定义,则返回 null。 +| fragment​ | 返回此 URI 的解码fragment组件,如果fragment未定义,则返回 null。| | path​ | 返回此 URI 的解码path组件,如果path未定义,则返回 null。 | -| equals(Object ob) | 测试此 URI 是否与另一个对象相等。如果给定的对象不是 URI,则此方法立即返回 false。 | +| equals(ob: Object) | 测试此 URI 是否与另一个对象相等。如果给定的对象不是 URI,则此方法立即返回 false。 | | normalize​() | 规范化这个 URI 的路径。如果这个 URI 的path不规范,将规范后构造一个新 URI对象返回。 | -| isAbsolute​() | 判断这个 URI 是否是绝对的。当且仅当它具有scheme部分时,URI 是绝对的,返回值为true,否则返回值为false。 | +| checkIsAbsolute​() | 判断这个 URI 是否是绝对的。当且仅当它具有scheme部分时,URI 是绝对的,返回值为true,否则返回值为false。 | | ConvertXml() | 用于构造ConvertXml类对象的构造函数。此构造函数无需传入参数。 | -| convert(String xml, Object options) | 返回按选项要求转化xml字符串的JavaScrip对象。 | - +| convert(xml: string, options: Object) | 返回按选项要求转化xml字符串的JavaScrip对象。 | +| XmlSerializer(buffer: ArrayBuffer \| DataView, encoding?: string) | 创建并返回一个XmlSerializer对象,该XmlSerializer对象传参两个第一参数是ArrayBuffer或DataView一段内存,第二个参数为文件格式(默认为UTF-8)。 | +| setAttributes(name: string, value: string): void | 给xml文件中写入属性Attributes属性。 | +| addEmptyElement(name: string): void | 写入一个空元素。 | +| setDeclaration(): void | 设置Declaration使用编码写入xml声明。例如:<?xml version=“1.0”encoding=“utf-8”> | +| startElement(name: string): void | 写入具有给定名称的elemnet开始标记。| +| endElement(): void | 写入元素的结束标记。 | +| setNamespace(prefix: string, namespace: string): void | 写入当前元素标记的命名空间。 | +| setCommnet(text: string): void | 写入comment属性。 | +| setCData(text: string): void | 写入CData属性。 | +| setText(text: string): void | 写入Text属性。 | +| setDocType(text: string): void | 写入DocType属性。 | +| XmlPullParser(buffer: ArrayBuffer \| DataView, encoding?: string) | 创建并返回一个XmlPullParser对象,该XmlPullParser对象传参两个第一参数是ArrayBuffer或DataView一段内存,第二个参数为文件格式(默认为UTF-8)。 | +| parse(option: ParseOptions): void | 该接口用于解析xml,ParseOptions参数为一个接口包含五个可选参{supportDoctype?: boolea ignoreNameSpace?: boolean tagValueCallbackFunction?: (name: string, value: string) => boolean attributeValueCallbackFunction?: (name: string, value: string) => boolean) tokenValueCallbackFunction?: (eventType: EventType, value: ParseInfo) => boolean }。其中tokenValueCallbackFunction回调函数的入参1是事件类型,入参2是包含getColumnNumber、getDepth等get属性的info接口,用户可通过info.getDepth()等方法来获取当前解析过程中的depth等信息。 | ### 使用说明 各接口使用方法如下: + 1、new URL(url: string,base?:string|URL) ``` let b = new URL('https://developer.mozilla.org'); // => 'https://developer.mozilla.org/' @@ -246,7 +276,8 @@ for (const [name, value] of params) { // xyz ba ``` -21、URI​(String str) + +21、URI​(str: string) ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); ``` @@ -295,7 +326,7 @@ gaogao.fragment // => "fagment"; let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.path // => "/path/path"; ``` -31、equals(Object ob) +31、equals(ob: Object) ``` let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path1?query#fagment'); let gaogao1 = gaogao; @@ -309,10 +340,10 @@ let res = gaogao.normalize(); console.log(res.path); // => "/path/path1" console.log(res.toString()); // => "http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/path1?query#fagment" ``` -33、isAbsolute​() +33、checkIsAbsolute​() ``` let gaogao = new Uri.URI('f/tp://username:password@www.baidu.com:88/path?query#fagment'); -let res = gaogao.isAbsolute(); +let res = gaogao.checkIsAbsolute(); console.log(res); //=> false; ``` 34、toString() @@ -322,20 +353,106 @@ let res = gaogao.toString(); console.log(res.toString()); // => 'http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'; ``` + 35、ConvertXml() ``` var convertml = new convertXml.ConvertXml(); ``` -36、convert(String xml, Object options) +36、convert(xml: string, options: Object) ``` var result = convertml.convert(xml, {compact: false, spaces: 4}); ``` +37、new XmlSerializer(buffer: ArrayBuffer | DataView, encoding?: string) +``` + +var arrayBuffer = new ArrayBuffer(1024); +var bufView = new DataView(arrayBuffer); +var thatSer = new xml.XmlSerializer(bufView); +``` +38、setDeclaration():void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setDeclaration() // => ; +``` +39、setCommnet(text: string):void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setCommnet("Hello, World!"); // => ; +``` +40、setCData(text: string) :void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setDocType('root SYSTEM "http://www.test.org/test.dtd"'); // => +``` +41、setDocType(text: string):void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setDocType("foo"); // => +``` +42、setNamespace(prefix: string, namespace: string): void +43、startElement(name: string): void +44、setAttributes(name: string, value: string): void +45、endElement(): void +46、setText(text: string): void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("table"); +thatSer.setAttributes("importance", "high"); +thatSer.setText("Happy"); +endElement(); // => Happy +``` +47、addEmptyElement(name: string): void +``` +var thatSer = new xml.XmlSerializer(bufView); +thatSer.addEmptyElement("b"); // => +``` +48、new (buffer: ArrayBuffer | DataView, encoding?: string) +``` +var strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +var arrayBuffer = new ArrayBuffer(strXml.length*2); +var bufView = new Uint8Array(arrayBuffer); +var strLen = strXml.length; +for (var i = 0; i < strLen; ++i) { + bufView[i] = strXml.charCodeAt(i);//设置arraybuffer 方式 +} +var that = new xml.XmlPullParser(arrayBuffer); + +``` +49、parse(option: ParseOptions): void +``` +var strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +var arrayBuffer = new ArrayBuffer(strXml.length*2); +var bufView = new Uint8Array(arrayBuffer); +var strLen = strXml.length; +for (var i = 0; i < strLen; ++i) { + bufView[i] = strXml.charCodeAt(i); +} +var that = new xml.XmlPullParser(arrayBuffer); +var arrTag = {}; +arrTag[0] = '132'; +var i = 1; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); + i++; + return true; +} +var options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); ## 相关仓 [js_api_module子系统](https://gitee.com/OHOS_STD/js_api_module) [base/compileruntime/js_api_module/](base/compileruntime/js_api_module/readme.md) - -### 许可证 - -URL在[Mozilla许可证](https://www.mozilla.org/en-US/MPL/)下可用,说明文档详见[说明文档](https://gitee.com/openharmony/js_api_module/blob/master/mozilla_docs.txt)。有关完整的许可证文本,有关完整的许可证文本,请参见[许可证](https://gitee.com/openharmony/js_api_module/blob/master/LICENSE) \ No newline at end of file diff --git a/convertxml/build_ts_js.py b/build_ts_js.py old mode 100755 new mode 100644 similarity index 71% rename from convertxml/build_ts_js.py rename to build_ts_js.py index 14f085a8..93af1187 --- a/convertxml/build_ts_js.py +++ b/build_ts_js.py @@ -13,10 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. import os +import shutil import platform import argparse import subprocess + def run_command(in_cmd): print(" ".join(in_cmd)) proc = subprocess.Popen(in_cmd, stdout=subprocess.PIPE, @@ -25,30 +27,34 @@ def run_command(in_cmd): shell=False) stdout, stderr = proc.communicate() if stdout != "": - print(stdout) - exit(1) + raise Exception(stdout) if __name__ == '__main__': - BUILD_PATH = os.path.abspath(os.path.join(os.getcwd(), "../..")) - os.chdir("%s/base/compileruntime/js_api_module/convertxml" % BUILD_PATH) PARSER_INST = argparse.ArgumentParser() PARSER_INST.add_argument('--dst-file', help='the converted target file') + PARSER_INST.add_argument('--module-path', + help='the module path') + PARSER_INST.add_argument('--out-file', + help='js output file') INPUT_ARGUMENTS = PARSER_INST.parse_args() - + BUILD_PATH = os.path.abspath(os.path.join(os.getcwd(), "../..")) + os.chdir(("%s" + INPUT_ARGUMENTS.module_path) % BUILD_PATH) NODE_PATH = '../../../../prebuilts/build-tools/common/nodejs/\ node-v12.18.4-linux-x64/bin/node' + if not os.path.exists(NODE_PATH): + raise Exception('NO souch file or directory') TSC_PATH = '../../../../ark/ts2abc/ts2panda/node_modules/\ typescript/bin/tsc' CMD_INST = [NODE_PATH, TSC_PATH] run_command(CMD_INST) + if not os.path.exists(INPUT_ARGUMENTS.out_file): + raise Exception('error:NO souch file or directory') + CMD_INST = shutil.copy(INPUT_ARGUMENTS.out_file, INPUT_ARGUMENTS.dst_file) - CMD_INST = ['cp', "-r", './out/js_convertxml.js', INPUT_ARGUMENTS.dst_file] - run_command(CMD_INST) + CMD_INST = shutil.rmtree('./out') - CMD_INST = ['rm', "-rf", './out'] - run_command(CMD_INST) exit(0) \ No newline at end of file diff --git a/convertxml/BUILD.gn b/convertxml/BUILD.gn index 90787f57..11ae5745 100755 --- a/convertxml/BUILD.gn +++ b/convertxml/BUILD.gn @@ -1,111 +1,113 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and # limitations under the License. - -import("//ark/ts2abc/ts2panda/ts2abc_config.gni") -import("//build/ohos.gni") -import("//build/ohos/ace/ace.gni") -import("//foundation/ace/ace_engine/ace_config.gni") - -# compile .ts to .js. -action("build_ts_js") { - script = "//base/compileruntime/js_api_module/convertxml/build_ts_js.py" - - args = [ - "--dst-file", - rebase_path(target_out_dir + "/js_convertxml.js"), - ] - depfile = "$target_gen_dir/$target_name.d" - outputs = [ target_out_dir + "/js_convertxml.js" ] -} - -base_output_path = get_label_info(":js_convertxml", "target_out_dir") -js_xml_obj_path = base_output_path + "/convertxml.o" -gen_js_obj("js_convertxml") { - input = "$target_out_dir/js_convertxml.js" - output = js_xml_obj_path - dep = ":build_ts_js" -} - -# compile .js to .abc. -action("gen_convertxml_abc") { - visibility = [ ":*" ] - script = "//ark/ts2abc/ts2panda/scripts/generate_js_bytecode.py" - - args = [ - "--src-js", - rebase_path(target_out_dir + "/js_convertxml.js"), - "--dst-file", - rebase_path(target_out_dir + "/convertxml.abc"), - "--node", - rebase_path("${node_path}"), - "--frontend-tool-path", - rebase_path("${ts2abc_build_path}"), - "--node-modules", - rebase_path("${node_modules}"), - ] - deps = [ - ":build_ts_js", - "//ark/ts2abc/ts2panda:ark_ts2abc_build", - ] - - inputs = [ target_out_dir + "/js_convertxml.js" ] - outputs = [ target_out_dir + "/convertxml.abc" ] -} - -abc_output_path = get_label_info(":convertxml_abc", "target_out_dir") -convertxml_abc_obj_path = abc_output_path + "/convertxml_abc.o" -gen_js_obj("convertxml_abc") { - input = "$target_out_dir/convertxml.abc" - output = convertxml_abc_obj_path - dep = ":gen_convertxml_abc" -} - -ohos_shared_library("convertxml") { - include_dirs = [ - "//third_party/icu/icu4c/source/common", - "//third_party/node/src", - "//third_party/libxml2/include", - "//foundation/ace/napi/interfaces/kits", - "//base/compileruntime/js_api_module/convertxml", - ] - - sources = [ - "js_convertxml.cpp", - "native_module_convertxml.cpp", - ] - - deps = [ - ":convertxml_abc", - ":js_convertxml", - "//base/compileruntime/js_api_module/convertxml/:js_convertxml", - "//foundation/ace/napi/:ace_napi", - "//foundation/ace/napi/:ace_napi_quickjs", - "//third_party/icu/icu4c:static_icuuc", - "//third_party/libxml2:xml2", - "//utils/native/base:utils", - ] - - if (is_standard_system) { - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - } else { - external_deps = [ "hilog:libhilog" ] - } - subsystem_name = "ccruntime" - part_name = "jsapi_api" - - relative_install_dir = "module" -} - -group("convertxml_packages") { - deps = [ ":convertxml" ] -} + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/ace/ace.gni") +import("//foundation/ace/ace_engine/ace_config.gni") + +# compile .ts to .js. +action("build_ts_js") { + script = "//base/compileruntime/js_api_module/build_ts_js.py" + args = [ + "--dst-file", + rebase_path(target_out_dir + "/js_convertxml.js"), + "--module-path", + rebase_path("/base/compileruntime/js_api_module/convertxml"), + "--out-file", + rebase_path("./out/js_convertxml.js"), + ] + depfile = "$target_gen_dir/$target_name.d" + outputs = [ target_out_dir + "/js_convertxml.js" ] +} +base_output_path = get_label_info(":js_convertxml", "target_out_dir") +js_xml_obj_path = base_output_path + "/convertxml.o" +gen_js_obj("js_convertxml") { + input = "$target_out_dir/js_convertxml.js" + output = js_xml_obj_path + dep = ":build_ts_js" +} + +# compile .js to .abc. +action("gen_convertxml_abc") { + visibility = [ ":*" ] + script = "//ark/ts2abc/ts2panda/scripts/generate_js_bytecode.py" + + args = [ + "--src-js", + rebase_path(target_out_dir + "/js_convertxml.js"), + "--dst-file", + rebase_path(target_out_dir + "/convertxml.abc"), + "--node", + rebase_path("${node_path}"), + "--frontend-tool-path", + rebase_path("${ts2abc_build_path}"), + "--node-modules", + rebase_path("${node_modules}"), + ] + deps = [ + ":build_ts_js", + "//ark/ts2abc/ts2panda:ark_ts2abc_build", + ] + + inputs = [ target_out_dir + "/js_convertxml.js" ] + outputs = [ target_out_dir + "/convertxml.abc" ] +} + +abc_output_path = get_label_info(":convertxml_abc", "target_out_dir") +convertxml_abc_obj_path = abc_output_path + "/convertxml_abc.o" +gen_js_obj("convertxml_abc") { + input = "$target_out_dir/convertxml.abc" + output = convertxml_abc_obj_path + dep = ":gen_convertxml_abc" +} + +ohos_shared_library("convertxml") { + include_dirs = [ + "//third_party/icu/icu4c/source/common", + "//third_party/node/src", + "//third_party/libxml2/include", + "//foundation/ace/napi/interfaces/kits", + "//base/compileruntime/js_api_module/convertxml", + ] + + sources = [ + "js_convertxml.cpp", + "native_module_convertxml.cpp", + ] + + deps = [ + ":convertxml_abc", + ":js_convertxml", + "//base/compileruntime/js_api_module/convertxml/:js_convertxml", + "//foundation/ace/napi/:ace_napi", + "//foundation/ace/napi/:ace_napi_quickjs", + "//third_party/icu/icu4c:static_icuuc", + "//third_party/libxml2:xml2", + "//utils/native/base:utils", + ] + + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } + subsystem_name = "ccruntime" + part_name = "jsapi_api" + + relative_install_dir = "module" +} + +group("convertxml_packages") { + deps = [ ":convertxml" ] +} diff --git a/convertxml/js_convertxml.cpp b/convertxml/js_convertxml.cpp index 190c2bb8..86002109 100755 --- a/convertxml/js_convertxml.cpp +++ b/convertxml/js_convertxml.cpp @@ -16,11 +16,11 @@ #include "securec.h" #include "utils/log.h" namespace OHOS::Xml { -ConvertXml::ConvertXml(napi_env env): env_(env) -{ - spaceType_ = SpaceType::T_INIT; - strSpace_ = ""; - iSpace_ = 0; + ConvertXml::ConvertXml(napi_env env): env_(env) + { + spaceType_ = SpaceType::T_INIT; + strSpace_ = ""; + iSpace_ = 0; } std::string ConvertXml::GetNodeType(const xmlElementType enumType) const { diff --git a/convertxml/js_convertxml.h b/convertxml/js_convertxml.h index 2fb1a684..a72c9889 100755 --- a/convertxml/js_convertxml.h +++ b/convertxml/js_convertxml.h @@ -29,77 +29,77 @@ namespace OHOS::Xml { T_INIT = -1 }; -struct Options { - std::string declaration = "_declaration"; - std::string instruction = "_instruction"; - std::string attributes = "_attributes"; - std::string text = "_text"; - std::string cdata = "_cdata"; - std::string doctype = "_doctype"; - std::string comment = "_comment"; - std::string parent = "_parent"; - std::string type = "_type"; - std::string name = "_name"; - std::string elements = "_elements"; - bool compact = false; - bool trim = false; - bool nativetype = false; - bool nativetypeattributes = false; - bool addparent = false; - bool alwaysArray = false; - bool alwaysChildren = false; - bool instructionHasAttributes = false; - bool ignoreDeclaration = false; - bool ignoreInstruction = false; - bool ignoreAttributes = false; - bool ignoreComment = false; - bool ignoreCdata = false; - bool ignoreDoctype = false; - bool ignoreText = false; - bool spaces = false; -}; + struct Options { + std::string declaration = "_declaration"; + std::string instruction = "_instruction"; + std::string attributes = "_attributes"; + std::string text = "_text"; + std::string cdata = "_cdata"; + std::string doctype = "_doctype"; + std::string comment = "_comment"; + std::string parent = "_parent"; + std::string type = "_type"; + std::string name = "_name"; + std::string elements = "_elements"; + bool compact = false; + bool trim = false; + bool nativetype = false; + bool nativetypeattributes = false; + bool addparent = false; + bool alwaysArray = false; + bool alwaysChildren = false; + bool instructionHasAttributes = false; + bool ignoreDeclaration = false; + bool ignoreInstruction = false; + bool ignoreAttributes = false; + bool ignoreComment = false; + bool ignoreCdata = false; + bool ignoreDoctype = false; + bool ignoreText = false; + bool spaces = false; + }; -struct XmlInfo { - bool bXml = false; - bool bVersion = false; - std::string strVersion = ""; - bool bEncoding = false; - std::string strEncoding = ""; -}; + struct XmlInfo { + bool bXml = false; + bool bVersion = false; + std::string strVersion = ""; + bool bEncoding = false; + std::string strEncoding = ""; + }; class ConvertXml { public: - explicit ConvertXml(napi_env env); - virtual ~ConvertXml() {} - void SetAttributes(xmlNodePtr curNode, const napi_value &elementsObject) const; - void SetXmlElementType(xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const; - void SetNodeInfo(xmlNodePtr curNode, const napi_value &elementsObject) const; - void SetEndInfo(xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const; - void GetXMLInfo(xmlNodePtr curNode, const napi_value &object, int flag = 0); - napi_value Convert(std::string strXml); - std::string GetNodeType(const xmlElementType enumType) const; - napi_status DealNapiStrValue(const napi_value napi_StrValue, std::string &result) const; - void SetKeyValue(const napi_value &object, const std::string strKey, const std::string strValue) const; - void DealOptions(const napi_value napiObj); - std::string Trim(std::string strXmltrim) const; - void GetPrevNodeList(xmlNodePtr curNode); - void DealSpaces(const napi_value napiObj); - void DealIgnore(const napi_value napiObj); - void SetPrevInfo(const napi_value &recvElement, int flag, int32_t &index1) const; - void SetDefaultKey(size_t i, const std::string strRecv); - void SetSpacesInfo(const napi_value &object) const; - void DealSingleLine(std::string &strXml, const napi_value &object); - void DealComplex(std::string &strXml, const napi_value &object) const; - void Replace(std::string &str, const std::string src, const std::string dst) const; - void DealCDataInfo(bool bCData, xmlNodePtr &curNode) const; + explicit ConvertXml(napi_env env); + virtual ~ConvertXml() {} + void SetAttributes(xmlNodePtr curNode, const napi_value &elementsObject) const; + void SetXmlElementType(xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const; + void SetNodeInfo(xmlNodePtr curNode, const napi_value &elementsObject) const; + void SetEndInfo(xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const; + void GetXMLInfo(xmlNodePtr curNode, const napi_value &object, int flag = 0); + napi_value Convert(std::string strXml); + std::string GetNodeType(const xmlElementType enumType) const; + napi_status DealNapiStrValue(const napi_value napi_StrValue, std::string &result) const; + void SetKeyValue(const napi_value &object, const std::string strKey, const std::string strValue) const; + void DealOptions(const napi_value napiObj); + std::string Trim(std::string strXmltrim) const; + void GetPrevNodeList(xmlNodePtr curNode); + void DealSpaces(const napi_value napiObj); + void DealIgnore(const napi_value napiObj); + void SetPrevInfo(const napi_value &recvElement, int flag, int32_t &index1) const; + void SetDefaultKey(size_t i, const std::string strRecv); + void SetSpacesInfo(const napi_value &object) const; + void DealSingleLine(std::string &strXml, const napi_value &object); + void DealComplex(std::string &strXml, const napi_value &object) const; + void Replace(std::string &str, const std::string src, const std::string dst) const; + void DealCDataInfo(bool bCData, xmlNodePtr &curNode) const; private: - napi_env env_; - SpaceType spaceType_; - int32_t iSpace_; - std::string strSpace_; - Options options_; - std::vector prevObj_; - XmlInfo xmlInfo_; + napi_env env_; + SpaceType spaceType_; + int32_t iSpace_; + std::string strSpace_; + Options options_; + std::vector prevObj_; + XmlInfo xmlInfo_; }; } // namespace #endif \ No newline at end of file diff --git a/convertxml/native_module_convertxml.cpp b/convertxml/native_module_convertxml.cpp index 4568b838..e1320a56 100755 --- a/convertxml/native_module_convertxml.cpp +++ b/convertxml/native_module_convertxml.cpp @@ -88,13 +88,27 @@ namespace OHOS::Xml { return exports; } + static napi_module convertXmlModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = ConvertXmlInit, + .nm_modname = "ConvertXML", + .nm_priv = ((void*)0), + .reserved = { 0 }, + }; + + extern "C" __attribute__ ((constructor)) void RegisterModule() + { + napi_module_register(&convertXmlModule); + } + extern "C" __attribute__((visibility("default"))) void NAPI_convertxml_GetJSCode(const char **buf, int *bufLen) { if (buf != nullptr) { *buf = _binary_js_convertxml_js_start; } - if (bufLen != nullptr) { *bufLen = _binary_js_convertxml_js_end - _binary_js_convertxml_js_start; } @@ -109,19 +123,4 @@ namespace OHOS::Xml { *buflen = _binary_convertxml_abc_end - _binary_convertxml_abc_start; } } - - static napi_module convertXmlModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = ConvertXmlInit, - .nm_modname = "ConvertXML", - .nm_priv = ((void*)0), - .reserved = { 0 }, - }; - - extern "C" __attribute__ ((constructor)) void RegisterModule() - { - napi_module_register(&convertXmlModule); - } -} // namespace \ No newline at end of file +} // namespace diff --git a/convertxml/src/js_convertxml.ts b/convertxml/src/js_convertxml.ts index 33dadea6..16c9185b 100644 --- a/convertxml/src/js_convertxml.ts +++ b/convertxml/src/js_convertxml.ts @@ -15,7 +15,7 @@ declare function requireInternal(s : string) : any; const convertXml = requireInternal("ConvertXML"); -class ConvertXml { +class ConvertXML { convertxmlclass : any; constructor() { this.convertxmlclass = new convertXml.ConvertXml(); @@ -130,7 +130,7 @@ function DealLaterReplace(strXml : string, idx : any, idxThir : any) } export default { - ConvertXml : ConvertXml + ConvertXML : ConvertXML } diff --git a/convertxml/tsconfig.json b/convertxml/tsconfig.json index c86e350c..825df281 100644 --- a/convertxml/tsconfig.json +++ b/convertxml/tsconfig.json @@ -1,8 +1,8 @@ { "compilerOptions": { "target": "es6", - "module": "es6", - "rootDir": "./src", + "module": "es6", + "rootDir": "./src", //"outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ "outDir": "./out", /* Specify an output folder for all emitted files. */ "esModuleInterop": true, diff --git a/mgit.info b/mgit.info new file mode 100644 index 00000000..da19ada8 --- /dev/null +++ b/mgit.info @@ -0,0 +1 @@ +hmf/js_api_module diff --git a/mozilla_docs.txt b/mozilla_docs.txt deleted file mode 100644 index ab6f2a65..00000000 --- a/mozilla_docs.txt +++ /dev/null @@ -1,44 +0,0 @@ - -The definitions of some interfaces implemented in jsapi/api/js_url.cpp are released under Mozilla license. - -The definitions and functions of these interfaces are consistent with the standard interfaces under mozila license, -but the implementation of specific functions is independent and self-developed. - -All interfaces are described in d.ts, the following is the interface written in d.ts under to Mozilla license - -class URLSearchParams { - - constructor(init?: string[][] | Record | string | URLSearchParams); - append(name: string, value: string): void; - delete(name: string): void; - getAll(name: string): string[]; - entries(): IterableIterator<[string, string]>; - forEach(callbackfn: (value: string, key: string, searchParams: this) => void): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; - sort(): void; - keys(): IterableIterator; - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[string, string]>; - toString(): string; -} - -class URL { - - constructor(url: string, base?: string | URL); - toString(): string; - toJSON(): string; - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - readonly searchParams: URLSearchParams; - username: string; -} \ No newline at end of file diff --git a/ohos.build b/ohos.build index 78ce498f..703ffa4d 100755 --- a/ohos.build +++ b/ohos.build @@ -9,12 +9,14 @@ "module_list": [ "//base/compileruntime/js_api_module/uri:uri_packages", "//base/compileruntime/js_api_module/url:url_packages", - "//base/compileruntime/js_api_module/convertxml:convertxml_packages" + "//base/compileruntime/js_api_module/convertxml:convertxml_packages", + "//base/compileruntime/js_api_module/xml:xml_packages" ], "inner_kits": [ ], "test_list": [ - "//base/compileruntime/js_api_module/test_uri/unittest:unittest" + "//base/compileruntime/js_api_module/test_uri/unittest:unittest", + "//base/compileruntime/js_api_module/test_xml/unittest:unittest" ] } } diff --git a/test_uri/unittest/BUILD.gn b/test_uri/unittest/BUILD.gn index d214df25..11429576 100755 --- a/test_uri/unittest/BUILD.gn +++ b/test_uri/unittest/BUILD.gn @@ -10,6 +10,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + import("//build/test.gni") if (is_standard_system) { @@ -20,7 +21,6 @@ ohos_unittest("test_uri_unittest") { module_out_path = module_output_path configs = [ "//ark/js_runtime:ark_jsruntime_public_config" ] - include_dirs = [ "//base/compileruntime/js_api_module/uri", "//ark/js_runtime", diff --git a/test_uri/unittest/test_ark.cpp b/test_uri/unittest/test_ark.cpp index f7e90b87..c2fc82bf 100644 --- a/test_uri/unittest/test_ark.cpp +++ b/test_uri/unittest/test_ark.cpp @@ -55,7 +55,7 @@ int main(int argc, char **argv) delete g_nativeEngine; g_nativeEngine = nullptr; - panda::JSNApi::DestoryJSVM(vm); + panda::JSNApi::DestroyJSVM(vm); vm = nullptr; return ret; diff --git a/uri/build_ts_js.py b/test_xml/unittest/BUILD.gn old mode 100755 new mode 100644 similarity index 31% rename from uri/build_ts_js.py rename to test_xml/unittest/BUILD.gn index 5bdd8d0b..2bcd367a --- a/uri/build_ts_js.py +++ b/test_xml/unittest/BUILD.gn @@ -1,5 +1,3 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- # Copyright (c) 2021 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,46 +10,57 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# - -import os -import platform -import argparse -import subprocess -def run_command(in_cmd): - print(" ".join(in_cmd)) - proc = subprocess.Popen(in_cmd, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - universal_newlines=True, - shell=False) - stdout, stderr = proc.communicate() - if stdout != "": - print(stdout) - exit(1) +import("//build/test.gni") +if (is_standard_system) { + module_output_path = "jsapi_api/napi" +} -if __name__ == '__main__': +ohos_unittest("test_xml_unittest") { + module_out_path = module_output_path - BUILD_PATH = os.path.abspath(os.path.join(os.getcwd(), "../..")) - os.chdir("%s/base/compileruntime/js_api_module/uri" % BUILD_PATH) + configs = [ "//ark/js_runtime:ark_jsruntime_public_config" ] + include_dirs = [ + "//base/compileruntime/js_api_module/xml", + "//ark/js_runtime", + "//foundation/ace/napi", + "//foundation/ace/napi/interfaces/kits", + "//foundation/ace/napi/native_engine", + "//foundation/ace/napi/native_engine/impl/ark", + "//third_party/googletest/include", + "//third_party/node/src", + "//utils/native/base/include", + ] - PARSER_INST = argparse.ArgumentParser() - PARSER_INST.add_argument('--dst-file', - help='the converted target file') - INPUT_ARGUMENTS = PARSER_INST.parse_args() + cflags = [ "-g3" ] + sources = [ + "test_ark.cpp", + "test_xml.cpp", + ] - NODE_PATH = '../../../../prebuilts/build-tools/common/nodejs/\ -node-v12.18.4-linux-x64/bin/node' - TSC_PATH = '../../../../ark/ts2abc/ts2panda/node_modules/\ -typescript/bin/tsc' - CMD_INST = [NODE_PATH, TSC_PATH] - run_command(CMD_INST) + deps = [ + "//ark/js_runtime:libark_jsruntime", + "//base/compileruntime/js_api_module/xml:xml_packages", + "//foundation/ace/napi/:ace_napi", + "//foundation/ace/napi/:ace_napi_ark", + "//third_party/googletest:gtest", + "//third_party/googletest:gtest_main", + "//third_party/icu/icu4c:static_icuuc", + "//third_party/libuv:uv_static", + "//utils/native/base:utils", + "//utils/native/base:utilsecurec", + ] - CMD_INST = ['cp', "-r", './out/js_uri.js', INPUT_ARGUMENTS.dst_file] - run_command(CMD_INST) + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } +} - CMD_INST = ['rm', "-rf", './out'] - run_command(CMD_INST) - exit(0) +group("unittest") { + testonly = true + deps = [ ":test_xml_unittest" ] +} diff --git a/test_xml/unittest/test.h b/test_xml/unittest/test.h new file mode 100644 index 00000000..753199cf --- /dev/null +++ b/test_xml/unittest/test.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_ACE_NAPI_TEST_UNITTEST_TEST_H +#define FOUNDATION_ACE_NAPI_TEST_UNITTEST_TEST_H + +#include "native_engine.h" + +#include "gtest/gtest.h" + +class NativeEngineTest : public testing::Test { +public: + NativeEngineTest(); + virtual ~NativeEngineTest(); + void SetUp() override {} + void TearDown() override {} +protected: + NativeEngine *engine_; +}; + +#endif /* FOUNDATION_ACE_NAPI_TEST_UNITTEST_TEST_H */ \ No newline at end of file diff --git a/test_xml/unittest/test_ark.cpp b/test_xml/unittest/test_ark.cpp new file mode 100644 index 00000000..3ce213ce --- /dev/null +++ b/test_xml/unittest/test_ark.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "test.h" +#include "ark_native_engine.h" +#include "utils/log.h" + +using panda::RuntimeOption; +static NativeEngine *g_nativeEngine = nullptr; + +NativeEngineTest::NativeEngineTest() +{ + engine_ = g_nativeEngine; +} + +NativeEngineTest::~NativeEngineTest() {} + +int main(int argc, char **argv) +{ + testing::GTEST_FLAG(output) = "xml:./"; + testing::InitGoogleTest(&argc, argv); + + // Setup + RuntimeOption option; + option.SetGcType(RuntimeOption::GC_TYPE::GEN_GC); + + const int64_t poolSize = 0x1000000; // 16M + option.SetGcPoolSize(poolSize); + + option.SetLogLevel(RuntimeOption::LOG_LEVEL::ERROR); + option.SetDebuggerLibraryPath(""); + EcmaVM *vm = panda::JSNApi::CreateJSVM(option); + if (vm == nullptr) { + return 0; + } + + g_nativeEngine = new ArkNativeEngine(vm, nullptr); + + int ret = testing::UnitTest::GetInstance()->Run(); + + g_nativeEngine->Loop(LOOP_NOWAIT); + if (g_nativeEngine) { + delete g_nativeEngine; + g_nativeEngine = nullptr; + } + panda::JSNApi::DestroyJSVM(vm); + vm = nullptr; + + return ret; +} diff --git a/test_xml/unittest/test_xml.cpp b/test_xml/unittest/test_xml.cpp new file mode 100644 index 00000000..554060cc --- /dev/null +++ b/test_xml/unittest/test_xml.cpp @@ -0,0 +1,961 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "test.h" + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +#include "js_xml.h" +#include "utils/log.h" + +#define ASSERT_CHECK_CALL(call) \ + { \ + ASSERT_EQ(call, napi_ok); \ + } + +#define ASSERT_CHECK_VALUE_TYPE(env, value, type) \ + { \ + napi_valuetype valueType = napi_undefined; \ + ASSERT_TRUE(value != nullptr); \ + ASSERT_CHECK_CALL(napi_typeof(env, value, &valueType)); \ + ASSERT_EQ(valueType, type); \ + } + +/* @tc.name: StartElementTest001 + * @tc.desc: Test whether write a elemnet start tag with the given name successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, StartElementTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note1"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: StartElementTest002 + * @tc.desc: Test whether write a elemnet start tag with the given name successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, StartElementTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note1"); + xmlSerializer.EndElement(); + xmlSerializer.StartElement("note2"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n"); +} + +/* @tc.name: StartElementTest003 + * @tc.desc: Test whether write a elemnet start tag with the given name successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, StartElementTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note1"); + xmlSerializer.StartElement("note2"); + xmlSerializer.EndElement(); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n \r\n"); +} + +/* @tc.name: StartElementTest004 + * @tc.desc: Test whether write a elemnet start tag with the given name successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, StartElementTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note1"); + xmlSerializer.StartElement("note2"); + xmlSerializer.StartElement("note3"); + xmlSerializer.EndElement(); + xmlSerializer.EndElement(); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n \r\n \r\n \r\n"); +} + +/* @tc.name: StartElementTest005 + * @tc.desc: Test whether write a elemnet start tag with the given name successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, StartElementTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note1"); + xmlSerializer.StartElement("note2"); + xmlSerializer.EndElement(); + xmlSerializer.StartElement("note3"); + xmlSerializer.EndElement(); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n \r\n \r\n"); +} + +/* @tc.name: SetAttributesTest001 + * @tc.desc: Test whether write an attribute successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetAttributesTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance1", "high1"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetAttributesTest002 + * @tc.desc: Test whether write an attribute successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetAttributesTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance1", "high1"); + xmlSerializer.SetAttributes("importance2", "high2"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetAttributesTest003 + * @tc.desc: Test whether write an attribute successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetAttributesTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance1", "high1"); + xmlSerializer.SetAttributes("importance2", "high2"); + xmlSerializer.SetAttributes("importance3", "high3"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), + ""); +} + +/* @tc.name: SetAttributesTest004 + * @tc.desc: Test whether write an attribute successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetAttributesTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance1", "high1"); + xmlSerializer.SetAttributes("importance2", "high2"); + xmlSerializer.SetAttributes("importance3", "high3"); + xmlSerializer.SetAttributes("importance4", "high4"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), + ""); +} + +/* @tc.name: SetAttributesTest005 + * @tc.desc: Test whether write an attribute successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetAttributesTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance1", "high1"); + xmlSerializer.SetAttributes("importance2", "high2"); + xmlSerializer.SetAttributes("importance3", "high3"); + xmlSerializer.SetAttributes("importance4", "high4"); + xmlSerializer.SetAttributes("importance5", "high5"); + xmlSerializer.EndElement(); + std::string strPrior = ""; + std::string strEnd = strPrior + strBack; + ASSERT_STREQ(reinterpret_cast(pBuffer), strEnd.c_str()); +} + +/* @tc.name: AddEmptyElementTest001 + * @tc.desc: Test whether add an empty element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, AddEmptyElementTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.AddEmptyElement("a"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n \r\n"); +} + +/* @tc.name: AddEmptyElementTest002 + * @tc.desc: Test whether add an empty element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, AddEmptyElementTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + xmlSerializer.AddEmptyElement("b"); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n"); +} + +/* @tc.name: AddEmptyElementTest003 + * @tc.desc: Test whether add an empty element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, AddEmptyElementTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.AddEmptyElement("c"); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n"); +} + +/* @tc.name: AddEmptyElementTest004 + * @tc.desc: Test whether add an empty element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, AddEmptyElementTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.AddEmptyElement("d"); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: AddEmptyElementTest005 + * @tc.desc: Test whether add an empty element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, AddEmptyElementTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.AddEmptyElement("c"); + xmlSerializer.AddEmptyElement("d"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n \r\n \r\n"); +} + +/* @tc.name: SetDeclarationTest001 + * @tc.desc: Test whether write xml declaration with encoding successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDeclarationTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetDeclarationTest002 + * @tc.desc: Test whether write xml declaration with encoding successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDeclarationTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetDeclarationTest003 + * @tc.desc: Test whether write xml declaration with encoding successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDeclarationTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetDeclarationTest004 + * @tc.desc: Test whether write xml declaration with encoding successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDeclarationTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetDeclarationTest005 + * @tc.desc: Test whether write xml declaration with encoding successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDeclarationTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: EndElementTest001 + * @tc.desc: Test whether write end tag of the element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, EndElementTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: EndElementTest002 + * @tc.desc: Test whether write end tag of the element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, EndElementTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance", "high"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: EndElementTest003 + * @tc.desc: Test whether write end tag of the element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, EndElementTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("impo", "hi"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: EndElementTest004 + * @tc.desc: Test whether write end tag of the element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, EndElementTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note1"); + xmlSerializer.StartElement("note2"); + xmlSerializer.EndElement(); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n \r\n"); +} + +/* @tc.name: EndElementTest005 + * @tc.desc: Test whether write end tag of the element successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, EndElementTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note2"); + xmlSerializer.SetAttributes("importance", "high"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetNamespaceTest001 + * @tc.desc: Test whether write the namespace of the current element tag successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetNamespaceTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + xmlSerializer.SetNamespace("h", "http://www.w3.org/TR/html4/"); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), + "\r\n"); +} + +/* @tc.name: SetNamespaceTest002 + * @tc.desc: Test whether write the namespace of the current element tag successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetNamespaceTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + xmlSerializer.SetNamespace("b", "http://www.w3.org/TR/html4/"); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), + "\r\n"); +} + +/* @tc.name: SetNamespaceTest003 + * @tc.desc: Test whether write the namespace of the current element tag successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetNamespaceTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + xmlSerializer.SetNamespace("h", "http://www.111/"); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), + "\r\n"); +} + +/* @tc.name: SetNamespaceTest004 + * @tc.desc: Test whether write the namespace of the current element tag successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetNamespaceTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + xmlSerializer.SetNamespace("h", "http://www.w3.org/TR/html4/"); + xmlSerializer.StartElement("note1"); + xmlSerializer.StartElement("note2"); + xmlSerializer.EndElement(); + xmlSerializer.EndElement(); + std::string strPrior = "\r\n"; + std::string strBack = "\r\n \r\n"; + std::string strEnd = strPrior + strBack; + ASSERT_STREQ(reinterpret_cast(pBuffer), strEnd.c_str()); +} + +/* @tc.name: SetNamespaceTest005 + * @tc.desc: Test whether write the namespace of the current element tag successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetNamespaceTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDeclaration(); + xmlSerializer.SetNamespace("h", "http://www.w3.org/TR/html4/"); + xmlSerializer.StartElement("note1"); + xmlSerializer.StartElement("note2"); + xmlSerializer.EndElement(); + xmlSerializer.EndElement(); + std::string strPrior = "\r\n"; + std::string strBack = "\r\n \r\n"; + std::string strEnd = strPrior + strBack; + ASSERT_STREQ(reinterpret_cast(pBuffer), strEnd.c_str()); +} + +/* @tc.name: SetCommnetTest001 + * @tc.desc: Test write the commnet successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCommnetTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetCommnet("Hi!"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n \r\n"); +} + +/* @tc.name: SetCommnetTest002 + * @tc.desc: Test write the commnet successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCommnetTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetCommnet("Hello, World!"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n \r\n"); +} + +/* @tc.name: SetCommnetTest003 + * @tc.desc: Test write the commnet successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCommnetTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetCommnet("Hello, World!"); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetCommnetTest004 + * @tc.desc: Test write the commnet successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCommnetTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetCommnet("Hello, World!"); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetCommnetTest005 + * @tc.desc: Test write the commnet successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCommnetTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetCommnet("Hello, World!"); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "\r\n"); +} + +/* @tc.name: Test001 + * @tc.desc: Test . + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCDataTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetCData("root SYSTEM"); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetCDataTest002 + * @tc.desc: Test whether Writes the CDATA successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCDataTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetCData("root SYSTEM \"http://www.test.org/test.dtd\""); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetCDataTest003 + * @tc.desc: Test whether Writes the CDATA successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCDataTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + xmlSerializer.SetCData("root SYSTEM \"http://www.test.org/test.dtd\""); + ASSERT_STREQ(reinterpret_cast(pBuffer), + "\r\n"); +} + +/* @tc.name: SetCDataTest004 + * @tc.desc: Test whether Writes the CDATA successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCDataTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetCData("root SYSTEM \"http://www.test.org/test.dtd\""); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), + "\r\n"); +} + +/* @tc.name: SetCDataTest005 + * @tc.desc: Test whether Writes the CDATA successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetCDataTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetCData("root SYSTEM \"http://www.test.org/test.dtd\""); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), + "\r\n \r\n"); +} + +/* @tc.name: SetTextTest001 + * @tc.desc: Test whether Writes the text successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetTextTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance", "high"); + xmlSerializer.SetText("Happy1"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "Happy1"); +} + +/* @tc.name: SetTextTest002 + * @tc.desc: Test whether Writes the text successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetTextTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance", "high"); + xmlSerializer.SetText("Happy2"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "Happy2"); +} + +/* @tc.name: SetTextTest003 + * @tc.desc: Test whether Writes the text successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetTextTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance", "high"); + xmlSerializer.SetText("Happy3"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "Happy3"); +} + +/* @tc.name: SetTextTest004 + * @tc.desc: Test whether Writes the text successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetTextTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance", "high"); + xmlSerializer.SetText("Happy4"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "Happy4"); +} + +/* @tc.name: SetTextTest005 + * @tc.desc: Test whether Writes the text successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetTextTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetAttributes("importance", "high"); + xmlSerializer.SetText("Happy5"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), "Happy5"); +} +/* @tc.name: SetDocTypeTest001 + * @tc.desc: Test whether rites the DOCTYPE successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDocTypeTest001, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDocType("root SYSTEM"); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} +/* @tc.name: SetDocTypeTest002 + * @tc.desc: Test whether rites the DOCTYPE successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDocTypeTest002, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDocType("root SYSTEM \"http://www.test.org/test.dtd\""); + ASSERT_STREQ(reinterpret_cast(pBuffer), ""); +} + +/* @tc.name: SetDocTypeTest003 + * @tc.desc: Test whether rites the DOCTYPE successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDocTypeTest003, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + xmlSerializer.SetDocType("root SYSTEM \"http://www.test.org/test.dtd\""); + ASSERT_STREQ(reinterpret_cast(pBuffer), + "\r\n"); +} + +/* @tc.name: SetDocTypeTest004 + * @tc.desc: Test whether rites the DOCTYPE successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDocTypeTest004, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.SetDocType("root SYSTEM \"http://www.test.org/test.dtd\""); + xmlSerializer.StartElement("note"); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), + "\r\n"); +} + +/* @tc.name: SetDocTypeTest005 + * @tc.desc: Test whether rites the DOCTYPE successfully. + * @tc.type: FUNC + */ +HWTEST_F(NativeEngineTest, SetDocTypeTest005, testing::ext::TestSize.Level0) +{ + napi_env env = (napi_env)engine_; + napi_value arrayBuffer = nullptr; + void* pBuffer = nullptr; + size_t size = 1024; + napi_create_arraybuffer(env, size, &pBuffer, &arrayBuffer); + OHOS::xml::XmlSerializer xmlSerializer(reinterpret_cast(pBuffer), size, "utf-8"); + xmlSerializer.StartElement("note"); + xmlSerializer.SetDocType("root SYSTEM \"http://www.test.org/test.dtd\""); + xmlSerializer.EndElement(); + ASSERT_STREQ(reinterpret_cast(pBuffer), + "\r\n \r\n"); +} diff --git a/uri/BUILD.gn b/uri/BUILD.gn index f110df36..ec123e6e 100755 --- a/uri/BUILD.gn +++ b/uri/BUILD.gn @@ -17,16 +17,18 @@ import("//foundation/ace/ace_engine/ace_config.gni") # compile .ts to .js. action("build_ts_js") { - script = "//base/compileruntime/js_api_module/uri/build_ts_js.py" - + script = "//base/compileruntime/js_api_module/build_ts_js.py" args = [ "--dst-file", rebase_path(target_out_dir + "/js_uri.js"), + "--module-path", + rebase_path("/base/compileruntime/js_api_module/uri"), + "--out-file", + rebase_path("./out/js_uri.js"), ] depfile = "$target_gen_dir/$target_name.d" outputs = [ target_out_dir + "/js_uri.js" ] } - base_output_path = get_label_info(":js_uri", "target_out_dir") js_uri_obj_path = base_output_path + "/uri.o" gen_js_obj("js_uri") { diff --git a/uri/js_uri.cpp b/uri/js_uri.cpp index 34452121..100cddb1 100755 --- a/uri/js_uri.cpp +++ b/uri/js_uri.cpp @@ -133,7 +133,7 @@ namespace OHOS::Uri { { size_t dataLen = data.size(); for (size_t i = 0; i < dataLen; ++i) { - if (data[i] >= 0 && data[i] < 128) { // 128:Maximum value of char + if (static_cast(data[i]) >= 0 && static_cast(data[i]) < 128) { // 128:ASCII Max Number bool isLegal = rule.test(data[i]); if (!isLegal) { return false; @@ -530,4 +530,4 @@ namespace OHOS::Uri { } return uriData_.fragment; } -} // namespace \ No newline at end of file +} // namespace diff --git a/uri/native_module_uri.cpp b/uri/native_module_uri.cpp index 23eb1c6f..d5d22200 100755 --- a/uri/native_module_uri.cpp +++ b/uri/native_module_uri.cpp @@ -32,12 +32,12 @@ namespace OHOS::Uri { size_t argc = 1; napi_value argv[1] = { 0 }; Uri *object = nullptr; + std::string input = ""; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); if (valuetype == napi_string) { char *type = nullptr; - std::string input = ""; size_t typelen = 0; NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typelen)); if (typelen > 0) { @@ -253,7 +253,7 @@ namespace OHOS::Uri { static napi_property_descriptor uriDesc[] = { DECLARE_NAPI_FUNCTION("normalize", Normalize), DECLARE_NAPI_FUNCTION("equals", Equals), - DECLARE_NAPI_FUNCTION("isAbsolute", IsAbsolute), + DECLARE_NAPI_FUNCTION("checkIsAbsolute", IsAbsolute), DECLARE_NAPI_FUNCTION("toString", UriToString), DECLARE_NAPI_GETTER("scheme", GetScheme), DECLARE_NAPI_GETTER("authority", GetAuthority), @@ -275,13 +275,26 @@ namespace OHOS::Uri { return exports; } + + static napi_module UriModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = UriInit, + .nm_modname = "uri", + .nm_priv = ((void*)0), + .reserved = {0}, + }; + extern "C" __attribute__((constructor)) void RegisterModule() + { + napi_module_register(&UriModule); + } extern "C" __attribute__((visibility("default"))) void NAPI_uri_GetJSCode(const char **buf, int *bufLen) { if (buf != nullptr) { *buf = _binary_js_uri_js_start; } - if (bufLen != nullptr) { *bufLen = _binary_js_uri_js_end - _binary_js_uri_js_start; } @@ -296,17 +309,4 @@ namespace OHOS::Uri { *buflen = _binary_uri_abc_end - _binary_uri_abc_start; } } - static napi_module UriModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = UriInit, - .nm_modname = "uri", - .nm_priv = ((void*)0), - .reserved = {0}, - }; - extern "C" __attribute__((constructor)) void RegisterModule() - { - napi_module_register(&UriModule); - } -} // namespace \ No newline at end of file +} // namespace diff --git a/uri/src/js_uri.ts b/uri/src/js_uri.ts index d5a1c0d9..1fed4e79 100644 --- a/uri/src/js_uri.ts +++ b/uri/src/js_uri.ts @@ -35,8 +35,8 @@ class URI { return this.uricalss.equals(other.uricalss); } - isAbsolute() { - return this.uricalss.isAbsolute(); + checkIsAbsolute() { + return this.uricalss.checkIsAbsolute(); } normalize() { diff --git a/uri/tsconfig.json b/uri/tsconfig.json index 66ad1485..eff2af40 100644 --- a/uri/tsconfig.json +++ b/uri/tsconfig.json @@ -1,8 +1,8 @@ { "compilerOptions": { "target": "es6", - "module": "es6", - "rootDir": "./src", + "module": "es6", + "rootDir": "./src", //"outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ "outDir": "./out", /* Specify an output folder for all emitted files. */ "esModuleInterop": true, @@ -10,5 +10,5 @@ "strict": true, "skipLibCheck": true, "noImplicitThis": false, - } + } } diff --git a/url/BUILD.gn b/url/BUILD.gn index 3107843f..bd4a9776 100755 --- a/url/BUILD.gn +++ b/url/BUILD.gn @@ -10,27 +10,27 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - import("//ark/ts2abc/ts2panda/ts2abc_config.gni") import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") import("//foundation/ace/ace_engine/ace_config.gni") # compile .ts to .js. - action("build_ts_js") { - script = "//base/compileruntime/js_api_module/url/build_ts_js.py" - + script = "//base/compileruntime/js_api_module/build_ts_js.py" args = [ "--dst-file", rebase_path(target_out_dir + "/js_url.js"), + "--module-path", + rebase_path("/base/compileruntime/js_api_module/url"), + "--out-file", + rebase_path("./out/js_url.js"), ] depfile = "$target_gen_dir/$target_name.d" outputs = [ target_out_dir + "/js_url.js" ] } base_output_path = get_label_info(":js_url", "target_out_dir") js_url_obj_path = base_output_path + "/url.o" - gen_js_obj("js_url") { input = "$target_out_dir/js_url.js" output = js_url_obj_path diff --git a/url/build_ts_js.py b/url/build_ts_js.py deleted file mode 100755 index 8a4a5b4a..00000000 --- a/url/build_ts_js.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import os -import platform -import argparse -import subprocess - -def run_command(in_cmd): - print(" ".join(in_cmd)) - proc = subprocess.Popen(in_cmd, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - universal_newlines=True, - shell=False) - stdout, stderr = proc.communicate() - if stdout != "": - print(stdout) - exit(1) - - -if __name__ == '__main__': - - BUILD_PATH = os.path.abspath(os.path.join(os.getcwd(), "../..")) - os.chdir("%s/base/compileruntime/js_api_module/url" % BUILD_PATH) - - PARSER_INST = argparse.ArgumentParser() - PARSER_INST.add_argument('--dst-file', - help='the converted target file') - INPUT_ARGUMENTS = PARSER_INST.parse_args() - - - NODE_PATH = '../../../../prebuilts/build-tools/common/nodejs/\ -node-v12.18.4-linux-x64/bin/node' - TSC_PATH = '../../../../ark/ts2abc/ts2panda/node_modules/\ -typescript/bin/tsc' - CMD_INST = [NODE_PATH, TSC_PATH] - run_command(CMD_INST) - - CMD_INST = ['cp', "-r", './out/js_url.js', INPUT_ARGUMENTS.dst_file] - run_command(CMD_INST) - - CMD_INST = ['rm', "-rf", './out'] - run_command(CMD_INST) - exit(0) diff --git a/url/js_url.cpp b/url/js_url.cpp index 67ab9a75..cfbeccb4 100755 --- a/url/js_url.cpp +++ b/url/js_url.cpp @@ -23,15 +23,17 @@ namespace OHOS::Url { {"ftp:", 21}, {"file:", -1}, {"gopher:", 70}, {"http:", 80}, {"https:", 443}, {"ws:", 80}, {"wss:", 443} }; + std::vector g_doubleSegment = { "..", ".%2e", ".%2E", "%2e.", "%2E.", "%2e%2e", "%2E%2E", "%2e%2E", "%2E%2e" }; + + std::vector g_singlesegment = { ".", "%2e", "%2E" }; std::vector g_specialSymbols = { "@", "%40", "#", "%23", "=", "%3D", ":", "%3A", "/", "%2F", ";", "%3B", "?", "%3F" }; - std::vector g_singlesegment = { ".", "%2e", "%2E" }; std::vector g_specialcharacter = { '\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']' @@ -46,7 +48,7 @@ namespace OHOS::Url { input.replace(pos, oldlen, newstr); continue; } - break; + break; } } @@ -117,7 +119,7 @@ namespace OHOS::Url { i++; continue; } - break; + break; } str = str.substr(i); strlen = str.size(); @@ -126,7 +128,7 @@ namespace OHOS::Url { str.pop_back(); continue; } - break; + break; } } @@ -214,6 +216,7 @@ namespace OHOS::Url { } } } + if (userAndPasswd.find(':') != std::string::npos) { size_t i = userAndPasswd.find(':'); std::string user = userAndPasswd.substr(0, i); @@ -329,10 +332,10 @@ namespace OHOS::Url { if (sprintf_s(hexVal, sizeof(hexVal), "%02x", stoi(val)) < 0) { HILOG_ERROR("sprintf_s is falie"); } - + temp.push_back(hexVal); left = pos + 1; - } + } val = str.substr(left); if (sprintf_s(hexVal, sizeof(hexVal), "%02x", stoi(val)) < 0) { HILOG_ERROR("sprintf_s is falie"); @@ -347,24 +350,23 @@ namespace OHOS::Url { { size_t pos = str.find("::"); size_t index = pos; - if (pos == std::string::npos) { - return; - } - size_t left = 0; - int count = 0; - while ((pos = str.find(":", left)) != std::string::npos) { - count++; - left = pos + 1; - } - int size = 7 - (count - 2); // 7:point number 2:Continuous colon number - std::string temp = ""; - for (int i = 0; i < size - 1; ++i) { - temp += ":0"; - } - temp += ":"; - str.replace(index, 2, temp); // 2:jump"::" - if (index == 0) { - str = "0" + str; + if (pos != std::string::npos) { + size_t left = 0; + int count = 0; + while ((pos = str.find(":", left)) != std::string::npos) { + count++; + left = pos + 1; + } + int size = 7 - (count - 2); // 7:point number 2:Continuous colon number + std::string temp = ""; + for (int i = 0; i < size - 1; ++i) { + temp += ":0"; + } + temp += ":"; + str.replace(index, 2, temp); // 2:jump"::" + if (index == 0) { + str = "0" + str; + } } } @@ -378,16 +380,16 @@ namespace OHOS::Url { for (j = 0; j < strLen; ++j) { if (ipv6[i][j] != '0') { break; + } + count++; } - count++; - } if (count == strLen) { ipv6[i] = "0"; } else if (count != 0) { ipv6[i] = ipv6[i].substr(j); + } } } - } std::string ZeroCompression(std::vector &ipv6) { @@ -404,24 +406,24 @@ namespace OHOS::Url { isNeedZeroCompression = true; size++; i++; - } + } if (maxSize < size) { maxSize = size; maxIndex = index; } - } + } std::string res = ""; size_t ipv6Len = ipv6.size(); for (size_t i = 0; i < ipv6Len; ++i) { if (isNeedZeroCompression && i == maxIndex) { if (maxIndex == 0) { res += "::"; - } else { + } else { res += ":"; - } + } i += maxSize - 1; continue; - } + } res += ipv6[i]; i != (ipv6Len - 1) ? res += ":" : ""; } @@ -434,9 +436,9 @@ namespace OHOS::Url { for (size_t i = 0; i < strLen; ++i) { if (isupper(str[i])) { str[i] = tolower(str[i]); - } } } + } std::string Compress(std::string str) { @@ -452,7 +454,7 @@ namespace OHOS::Url { std::string res = ZeroCompression(temp); ToLower(res); return res; - } + } void IPv6Host(std::string& input, std::string& host, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) @@ -468,9 +470,9 @@ namespace OHOS::Url { "(([0-9A-Fa-f]{1,4}:){5}:)|(([0-9A-Fa-f]{1,4}:){6}))((25[0-5]|2[0-4]\\d|1\\d{2}|" "[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)))(%[a-zA-Z0-9._]+)?"); if (!std::regex_match(input, ipv6)) { - flags.set(static_cast(BitsetStatusFlag::BIT0)); - return; - } + flags.set(static_cast(BitsetStatusFlag::BIT0)); + return; + } size_t pos = 0; pos = input.find('.'); if (pos != std::string::npos) { @@ -489,10 +491,10 @@ namespace OHOS::Url { for (size_t i = 0; i < len; ++i) { if (radix.find(num[i]) == std::string::npos) { return false; + } } - } return true; - } + } bool IsNumber(std::string num, int &radix) { @@ -506,27 +508,28 @@ namespace OHOS::Url { } else if (IsRadix(num, "0123456789")) { radix = 10; // 10:decimal return true; - } - return false; } + return false; + } + std::string BinaryConversion(std::string num, int radix) { int val = 0; if (radix == 16) { // 16:hex if (sscanf_s(num.c_str(), "%x", &val) == 0) { HILOG_ERROR("sscanf_s is falie"); - } + } return std::to_string(val); } else if (radix == 8) { // 8:octal if (sscanf_s(num.c_str(), "%o", &val) == 0) { HILOG_ERROR("sscanf_s is falie"); - } + } return std::to_string(val); - } else { + } else { return num; } - } + } bool RemovalIpv4(std::vector &temp, std::string str) { @@ -535,7 +538,7 @@ namespace OHOS::Url { while ((pos = str.find(".", left)) != std::string::npos) { temp.push_back(str.substr(left, pos - left)); left = pos + 1; - } + } temp.push_back(str.substr(left)); size_t tmpLen = temp.size(); std::vector res; @@ -571,7 +574,7 @@ namespace OHOS::Url { int num = val % 256; // 256:ipv4 max value nums.push_back(std::to_string(num)); val /= 256; // 256:ipv4 max value - } + } for (int i = nums.size() - 1; i >= 0; --i) { res += nums[i] + "."; } @@ -580,7 +583,7 @@ namespace OHOS::Url { } void FormatIpv4(std::vector nums, std::string& host, - std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) + std::bitset(BitsetStatusFlag::BIT_STATUS_11)> &flags) { size_t len = nums.size(); int index = IsFormatIpv4(nums); @@ -588,7 +591,7 @@ namespace OHOS::Url { if (index == -1) { for (size_t i = 0; i < len - 1; ++i) { res += nums[i] + "."; - } + } for (size_t i = 0; i < 4 - len; ++i) { // 4:ipv4 max size res += "0."; } @@ -598,23 +601,23 @@ namespace OHOS::Url { } else if (index == static_cast(len - 1)) { for (size_t i = 0; i < len - 1; ++i) { res += nums[i] + "."; - } + } size_t number = 0; std::string temp = SplitNum(nums[index], number); if (number + (len - 1) > 4) { // 4:ipv4 max size flags.set(static_cast(BitsetStatusFlag::BIT0)); return; - } + } for (size_t i = 0; i < 4 - (len - 1 + number); ++i) { // 4:ipv4 max size temp = "0." + temp; - } + } host = res + temp; flags.set(static_cast(BitsetStatusFlag::BIT4)); } else { flags.set(static_cast(BitsetStatusFlag::BIT0)); return; - } - } + } + } void AnalyseIPv4(const std::string& input, std::string& host, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) @@ -639,7 +642,7 @@ namespace OHOS::Url { if (IsFormatIpv4(temp) == -1) { host = res; flags.set(static_cast(BitsetStatusFlag::BIT4)); - } else { + } else { flags.set(static_cast(BitsetStatusFlag::BIT0)); } } else { @@ -648,10 +651,9 @@ namespace OHOS::Url { } else { ToLower(res); host = res; - flags.set(static_cast(BitsetStatusFlag::BIT4)); + flags.set(static_cast(BitsetStatusFlag::BIT4)); } } - void AnalysisHost(std::string& input, std::string& host, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags, bool special) { @@ -693,7 +695,6 @@ namespace OHOS::Url { } return false; } - void AnalysisFilePath(std::string& input, UrlData& urlinfo, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { @@ -756,7 +757,6 @@ namespace OHOS::Url { AnalysisFilePath(temp, urlinfo, flags); } } - void AnalysisFile(std::string& input, UrlData& urlinfo, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { @@ -928,7 +928,7 @@ namespace OHOS::Url { pos++; continue; } - break; + break; } input = input.substr(pos); if (input.size() == 0) { @@ -1032,7 +1032,6 @@ namespace OHOS::Url { } baseData.path.pop_back(); } - void InitOnlyInput(std::string& input, UrlData& urlData, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { @@ -1070,7 +1069,6 @@ namespace OHOS::Url { return; } } - void ToolHasBase(std::string input, std::string &strInput, UrlData &urlData, std::bitset(BitsetStatusFlag::BIT_STATUS_11)> &flags) { @@ -1285,6 +1283,7 @@ namespace OHOS::Url { return result; } + napi_value URL::GetPort() const { napi_value result; @@ -1558,13 +1557,13 @@ namespace OHOS::Url { urlData_.username = ""; flags_.set(static_cast(BitsetStatusFlag::BIT2), 0); } else { - std::string usname = input; + std::string usname = input; size_t len = g_specialSymbols.size() - 2; // 2:Maximum position of subscript for (int i = 0; i <= len; i += 2) { // 2:Shift subscript right 2 - ReplaceSpecialSymbols(usname, g_specialSymbols[i], g_specialSymbols[i + 1]); + ReplaceSpecialSymbols(usname, g_specialSymbols[i], g_specialSymbols[i + 1]); } - urlData_.username = usname; - flags_.set(static_cast(BitsetStatusFlag::BIT2)); + urlData_.username = usname; + flags_.set(static_cast(BitsetStatusFlag::BIT2)); } } @@ -1574,16 +1573,17 @@ namespace OHOS::Url { urlData_.password = ""; flags_.set(static_cast(BitsetStatusFlag::BIT3), 0); } else { - std::string keyWord = input; + std::string keyWord = input; size_t len = g_specialSymbols.size() - 2; // 2:Maximum position of subscript for (int i = 0; i <= len; i += 2) { // 2:Shift subscript right 2 - ReplaceSpecialSymbols(keyWord, g_specialSymbols[i], g_specialSymbols[i + 1]); + ReplaceSpecialSymbols(keyWord, g_specialSymbols[i], g_specialSymbols[i + 1]); } - urlData_.password = keyWord; - flags_.set(static_cast(BitsetStatusFlag::BIT3)); + urlData_.password = keyWord; + flags_.set(static_cast(BitsetStatusFlag::BIT3)); } } + URLSearchParams::URLSearchParams(napi_env env) : env(env) {} std::wstring StrToWstr(const std::string& str) @@ -1601,7 +1601,7 @@ namespace OHOS::Url { delete[] wch; p = setlocale(LC_ALL, ""); if (p == nullptr) { - return L""; + return L""; } return wstr; } @@ -1627,7 +1627,6 @@ namespace OHOS::Url { auto charaEncode = static_cast(wch); return charaEncode; } - std::string ReviseStr(std::string str, std::string *reviseChar) { const size_t lenStr = str.length(); @@ -1643,6 +1642,7 @@ namespace OHOS::Url { charaEncode = CharToUnicode(str, i); } if (charaEncode >= 0 && charaEncode < numOfAscii) { + // 2:Defines the escape range of ASCII characters if (IsEscapeRange(charaEncode)) { output += reviseChar[charaEncode]; } else { @@ -1709,7 +1709,6 @@ namespace OHOS::Url { napi_create_string_utf8(env, output.c_str(), output.size(), &result); return result; } - void URLSearchParams::HandleIllegalChar(std::wstring& inputStr, std::wstring::const_iterator it) { std::wstring::iterator iter = inputStr.begin(); @@ -1779,7 +1778,6 @@ namespace OHOS::Url { delete[] rePtr; return reStr; } - napi_value URLSearchParams::Get(napi_value buffer) { char *name = nullptr; @@ -1807,7 +1805,6 @@ namespace OHOS::Url { } return result; } - napi_value URLSearchParams::GetAll(napi_value buffer) { char *name = nullptr; @@ -1895,6 +1892,7 @@ namespace OHOS::Url { for (size_t i = 0; i < size; i += 2) { // 2:Searching for the number and number of keys and values napi_value result = nullptr; napi_create_array(env, &result); + napi_create_string_utf8(env, searchParams[i].c_str(), searchParams[i].length(), &firNapiStr); napi_create_string_utf8(env, searchParams[i + 1].c_str(), searchParams[i + 1].length(), &secNapiStr); napi_set_element(env, result, 0, firNapiStr); @@ -2050,4 +2048,4 @@ namespace OHOS::Url { } return arr; } -} // namespace \ No newline at end of file +} // namespace diff --git a/url/native_module_url.cpp b/url/native_module_url.cpp index 2ac63c95..1dea387d 100755 --- a/url/native_module_url.cpp +++ b/url/native_module_url.cpp @@ -616,6 +616,7 @@ namespace OHOS::Url { URLSearchParams *object = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&object)); object->Delete(args); + return nullptr; } @@ -892,13 +893,26 @@ namespace OHOS::Url { return exports; } + + static napi_module UrlModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "url", + .nm_priv = ((void*)0), + .reserved = {0}, + }; + extern "C" __attribute__((constructor)) void RegisterModule() + { + napi_module_register(&UrlModule); + } extern "C" __attribute__((visibility("default"))) void NAPI_url_GetJSCode(const char **buf, int *bufLen) { if (buf != nullptr) { *buf = _binary_js_url_js_start; } - if (bufLen != nullptr) { *bufLen = _binary_js_url_js_end - _binary_js_url_js_start; } @@ -913,17 +927,4 @@ namespace OHOS::Url { *buflen = _binary_url_abc_end - _binary_url_abc_start; } } - static napi_module UrlModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "url", - .nm_priv = ((void*)0), - .reserved = {0}, - }; - extern "C" __attribute__((constructor)) void RegisterModule() - { - napi_module_register(&UrlModule); - } -} // namespace \ No newline at end of file +} // namespace diff --git a/url/src/js_url.ts b/url/src/js_url.ts index 03e11831..e64ad2f7 100644 --- a/url/src/js_url.ts +++ b/url/src/js_url.ts @@ -76,7 +76,7 @@ class URLSearchParams { if (array.length == 0) { return; } - + let size = array.length - 1; for (let i = 0; i < size; i += 2) { // 2:Searching for the number and number of keys and values let key = array[i]; diff --git a/url/tsconfig.json b/url/tsconfig.json index 66ad1485..eff2af40 100644 --- a/url/tsconfig.json +++ b/url/tsconfig.json @@ -1,8 +1,8 @@ { "compilerOptions": { "target": "es6", - "module": "es6", - "rootDir": "./src", + "module": "es6", + "rootDir": "./src", //"outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ "outDir": "./out", /* Specify an output folder for all emitted files. */ "esModuleInterop": true, @@ -10,5 +10,5 @@ "strict": true, "skipLibCheck": true, "noImplicitThis": false, - } + } } diff --git a/xml/BUILD.gn b/xml/BUILD.gn index 43125393..b5110035 100644 --- a/xml/BUILD.gn +++ b/xml/BUILD.gn @@ -18,11 +18,15 @@ import("//foundation/ace/ace_engine/ace_config.gni") # compile .ts to .js. action("build_ts_js") { - script = "//base/compileruntime/js_api_module/xml/build_ts_js.py" + script = "//base/compileruntime/js_api_module/build_ts_js.py" args = [ "--dst-file", rebase_path(target_out_dir + "/js_xml.js"), + "--module-path", + rebase_path("/base/compileruntime/js_api_module/xml"), + "--out-file", + rebase_path("./out/js_xml.js"), ] depfile = "$target_gen_dir/$target_name.d" outputs = [ target_out_dir + "/js_xml.js" ] diff --git a/xml/build_ts_js.py b/xml/build_ts_js.py deleted file mode 100644 index 922907ce..00000000 --- a/xml/build_ts_js.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import os -import platform -import argparse -import subprocess - -def run_command(in_cmd): - print(" ".join(in_cmd)) - proc = subprocess.Popen(in_cmd, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - universal_newlines=True, - shell=False) - stdout, stderr = proc.communicate() - if stdout != "": - print(stdout) - exit(1) - -if __name__ == '__main__': - - BUILD_PATH = os.path.abspath(os.path.join(os.getcwd(), "../..")) - os.chdir("%s/base/compileruntime/js_api_module/xml" % BUILD_PATH) - - PARSER_INST = argparse.ArgumentParser() - PARSER_INST.add_argument('--dst-file', - help='the converted target file') - INPUT_ARGUMENTS = PARSER_INST.parse_args() - - - NODE_PATH = '../../../../prebuilts/build-tools/common/nodejs/\ -node-v12.18.4-linux-x64/bin/node' - TSC_PATH = '../../../../ark/ts2abc/ts2panda/node_modules/\ -typescript/bin/tsc' - CMD_INST = [NODE_PATH, TSC_PATH] - run_command(CMD_INST) - - CMD_INST = ['cp', "-r", './out/js_xml.js', INPUT_ARGUMENTS.dst_file] - run_command(CMD_INST) - - CMD_INST = ['rm', "-rf", './out'] - run_command(CMD_INST) - exit(0) \ No newline at end of file diff --git a/xml/js_xml.cpp b/xml/js_xml.cpp index 89c6a95f..1487efb0 100644 --- a/xml/js_xml.cpp +++ b/xml/js_xml.cpp @@ -16,26 +16,18 @@ #include "js_xml.h" #include "securec.h" namespace OHOS::xml { - XmlSerializer::XmlSerializer(napi_env env, char *pStart, size_t bufferLength, std::string encoding) - { - env_ = env; - encoding_ = encoding; - pStart_ = pStart; - iLength_ = bufferLength; - } - - napi_status XmlSerializer::DealNapiStrValue(napi_env env, const napi_value napi_StrValue, std::string &result) + napi_status XmlSerializer::DealNapiStrValue(napi_env env, const napi_value napiStr, std::string &result) { char *buffer = nullptr; size_t bufferSize = 0; napi_status status = napi_ok; - status = napi_get_value_string_utf8(env, napi_StrValue, nullptr, -1, &bufferSize); + status = napi_get_value_string_utf8(env, napiStr, nullptr, -1, &bufferSize); if (status != napi_ok) { return status; } if (bufferSize > 0) { buffer = new char[bufferSize + 1]; - napi_get_value_string_utf8(env, napi_StrValue, buffer, bufferSize + 1, &bufferSize); + napi_get_value_string_utf8(env, napiStr, buffer, bufferSize + 1, &bufferSize); } if (buffer != nullptr) { result = buffer; @@ -52,7 +44,7 @@ namespace OHOS::xml { return; } if (type == "isAttri" || type == "isStart") { - for (int i = 0; i< CurNspNum; ++i) { + for (int i = 0; i < CurNspNum; ++i) { out_.append(" xmlns:"); out_.append(multNsp[depth_ - 1][i * 2]); // 2: number of args out_.append("=\""); @@ -67,7 +59,7 @@ namespace OHOS::xml { void XmlSerializer::NextItem() { out_.append("\r\n"); - for (int i = 0; i < depth_; i++) { + for (size_t i = 0; i < depth_; i++) { out_.append(" "); } } @@ -81,6 +73,11 @@ namespace OHOS::xml { } void XmlSerializer::SetDeclaration() { + if (isHasDecl) { + xmlSerializerError_ = "illegal position for declaration"; + return; + } + isHasDecl = true; out_ = ""; out_.append(""); } elementStack[depth_ * 3] = prefix; // 3: number of args - elementStack[depth_ * 3 + 1] = ns_Temp; // 3: number of args - multNsp[depth_][CurNspNum*2] = elementStack[depth_ * 3]; // 3: number of args 2: number of args + elementStack[depth_ * 3 + 1] = nsTemp; // 3: number of args + multNsp[depth_][CurNspNum * 2] = elementStack[depth_ * 3]; // 3: number of args 2: number of args multNsp[depth_][CurNspNum * 2 + 1] = elementStack[depth_ * 3 + 1]; // 3: number of args 2: number of args ++CurNspNum; type = "isNsp"; @@ -124,7 +121,7 @@ namespace OHOS::xml { if (type != "" && type != "isDecl") { NextItem(); } - elementStack[depth_*3 + 2] = name; // 3: number of args 2: number of args + elementStack[depth_ * 3 + 2] = name; // 3: number of args 2: number of args out_.append("<"); if (elementStack[depth_ * 3] != "") { // 3: number of args out_.append(elementStack[depth_ * 3]); // 3: number of args @@ -245,7 +242,7 @@ namespace OHOS::xml { void XmlSerializer::SetCommnet(std::string comment) { out_ = ""; - if (type == "isStart" || type =="isAttri") { + if (type == "isStart" || type == "isAttri") { SplicNsp(); out_.append(">"); } @@ -335,8 +332,10 @@ namespace OHOS::xml { napi_value XmlPullParser::DealOptionInfo(napi_value napiObj, napi_callback_info info) { - std::vector vctOptions = {"supportDoctype", "ignoreNameSpace", "tagValueCallbackFunction", - "attributeValueCallbackFunction", "tokenValueCallbackFunction"}; + std::vector vctOptions = { + "supportDoctype", "ignoreNameSpace", "tagValueCallbackFunction", + "attributeValueCallbackFunction", "tokenValueCallbackFunction" + }; size_t vctLength = vctOptions.size(); for (size_t i = 0; i < vctLength; ++i) { napi_value recvTemp = nullptr; @@ -377,7 +376,7 @@ namespace OHOS::xml { void XmlPullParser::PushSrcLinkList(std::string strBuffer) { - SrcLinkList* pNew = new SrcLinkList; + auto pNew = new SrcLinkList; srcLinkList_->next = pNew; pNew->strBuffer = strBuffer; pNew->position = 0; @@ -388,14 +387,16 @@ namespace OHOS::xml { void XmlPullParser::PopSrcLinkList() { SrcLinkList* pTemp = srcLinkList_; - srcLinkList_ = srcLinkList_->next; + if (srcLinkList_) { + srcLinkList_ = srcLinkList_->next; + } if (pTemp != nullptr) { delete pTemp; pTemp = nullptr; } } - bool XmlPullParser::DealLength(int minimun) + bool XmlPullParser::DealLength(size_t minimun) { while (srcLinkList_->next != nullptr) { if (position_ < max_) { @@ -406,7 +407,7 @@ namespace OHOS::xml { return true; } } - for (int i = 0; i < position_; i++) { + for (size_t i = 0; i < position_; i++) { if (strXml_[i] == '\n') { bufferStartLine_++; bufferStartColumn_ = 0; @@ -438,7 +439,7 @@ namespace OHOS::xml { return false; } - int XmlPullParser::GetNSCount(int iTemp) + size_t XmlPullParser::GetNSCount(size_t iTemp) { if (iTemp > depth) { xmlPullParserError_ = " IndexOutOfBoundsException"; @@ -446,12 +447,12 @@ namespace OHOS::xml { return nspCounts_[depth]; } - std::string XmlPullParser::XmlPullParserError() + std::string XmlPullParser::XmlPullParserError() const { return xmlPullParserError_; } - bool XmlPullParser::ParseToken(napi_value thisVar) + bool XmlPullParser::ParseToken(napi_value thisVar) const { napi_value returnVal = nullptr; size_t argc = 2; // 2: number of args @@ -461,7 +462,7 @@ namespace OHOS::xml { napi_create_object(env_, &parseInfo); auto object = new ParseInfo(); napi_wrap(env_, parseInfo, object, nullptr, nullptr, nullptr); - static napi_property_descriptor XmlDesc[] = { + static napi_property_descriptor xmlDesc[] = { DECLARE_NAPI_FUNCTION("getDepth", XmlPullParser::ParseInfo::GetDepth), DECLARE_NAPI_FUNCTION("getColumnNumber", XmlPullParser::ParseInfo::GetColumnNumber), DECLARE_NAPI_FUNCTION("getLineNumber", XmlPullParser::ParseInfo::GetLineNumber), @@ -473,18 +474,22 @@ namespace OHOS::xml { DECLARE_NAPI_FUNCTION("isEmptyElementTag", XmlPullParser::ParseInfo::IsEmptyElementTag), DECLARE_NAPI_FUNCTION("isWhitespace", XmlPullParser::ParseInfo::IsWhitespace) }; - napi_define_properties(env_, parseInfo, sizeof(XmlDesc) / sizeof(XmlDesc[0]), XmlDesc); + napi_define_properties(env_, parseInfo, sizeof(xmlDesc) / sizeof(xmlDesc[0]), xmlDesc); napi_set_named_property(env_, parseInfo, "MainInfo", thisVar); napi_value argv[2] = {key, parseInfo}; // 2: number of args napi_call_function(env_, parseInfo, tokenFunc_, argc, argv, &returnVal); bool bRec = false; napi_get_value_bool(env_, returnVal, &bRec); + if (object != nullptr) { + delete object; + object = nullptr; + } return bRec; } - - bool XmlPullParser::ParseAttri(napi_value thisVar) + + bool XmlPullParser::ParseAttri(napi_value thisVar) const { - for (size_t i = 0 ; i< attriCount_ ; ++i) { + for (size_t i = 0; i < attriCount_; ++i) { napi_value returnVal = nullptr; size_t argc = 3; // 3: number of args napi_value global = nullptr; @@ -542,7 +547,7 @@ namespace OHOS::xml { } } - TagEnum XmlPullParser::ParseTagTypeFunc() + TagEnum XmlPullParser::DealExclamationGroup() { switch (strXml_[position_ + 2]) { // 2: number of args case 'D': @@ -567,6 +572,30 @@ namespace OHOS::xml { } return TagEnum::ERROR1; } + + TagEnum XmlPullParser::DealLtGroup() + { + if (position_ + 3 >= max_ && !DealLength(4)) { // 4: number of args 3: number of args + xmlPullParserError_ = ("Dangling <"); + } + char cTemp = strXml_[position_ + 1]; + if (cTemp == '/') { + return TagEnum::END_TAG; + } else if (cTemp == '?') { + std::string strXml = strXml_.substr(position_ + 2, 4); // 2 and 4:position and length + MakeStrUpper(strXml); + if (max_ >= position_ + 5 && strXml == tagText_.XML) { + return TagEnum::XML_DECLARATION; + } else { + return TagEnum::INSTRUCTION; + } + } else if (cTemp == '!') { + return DealExclamationGroup(); + } else { + return TagEnum::START_TAG; + } + } + TagEnum XmlPullParser::ParseTagType(bool inDeclaration) { if (bStartDoc_) { @@ -580,27 +609,7 @@ namespace OHOS::xml { case '&': return TagEnum::ENTITY_REFERENCE; case '<': - if (position_ + 3 >= max_ && !DealLength(4)) { // 4: number of args 3: number of args - xmlPullParserError_ = ("Dangling <"); - } - switch (strXml_[position_ + 1]) { - case '/': - return TagEnum::END_TAG; - case '?': - if ((position_ + 5 < max_ || DealLength(6)) // 5: number of args 6: number of args - && (strXml_[position_ + 2] == 'x' || strXml_[position_ + 2] == 'X') // 2: number of args - && (strXml_[position_ + 3] == 'm' || strXml_[position_ + 3] == 'M') // 3: number of args - && (strXml_[position_ + 4] == 'l' || strXml_[position_ + 4] == 'L') // 4: number of args - && (strXml_[position_ + 5] == ' ')) { // 5: number of args - return TagEnum::XML_DECLARATION; - } else { - return TagEnum::INSTRUCTION; - } - case '!': - return ParseTagTypeFunc(); - default: - return TagEnum::START_TAG; - } + return DealLtGroup(); case '%': return inDeclaration ? TagEnum::PARAMETER_ENTITY_REF : TagEnum::TEXT; default: @@ -608,6 +617,18 @@ namespace OHOS::xml { } } + void XmlPullParser::MakeStrUpper(std::string &src) const + { + size_t i = 0; + + while (i < src.size()) { + if (src[i] >= 'A' && src[i] <= 'Z') { + src[i] += 32; + } + ++i; + } + } + void XmlPullParser::SkipText(std::string chars) { if (position_ + chars.size() > max_ && !DealLength(chars.size())) { @@ -639,26 +660,11 @@ namespace OHOS::xml { } position_++; } - std::string XmlPullParser::ParseName() + + std::string XmlPullParser::ParseNameInner(int start) { - if (position_ >= max_ && !DealLength(1)) { - xmlPullParserError_ = "name expected"; - return ""; - } - int start = position_; std::string result = ""; - char c = strXml_[position_]; - if ((c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || c == '_' - || c == ':' - || relaxed) { - position_++; - } else { - xmlPullParserError_ = "name expected"; - return ""; - } - + char c = 0; while (true) { if (position_ >= max_) { result.append(strXml_, start, position_ - start); @@ -668,13 +674,9 @@ namespace OHOS::xml { start = position_; } c = strXml_[position_]; - if ((c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || (c >= '0' && c <= '9') - || c == '_' - || c == '-' - || c == ':' - || c == '.') { + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '_' || c == '-' || + c == ':' || c == '.') { position_++; continue; } @@ -687,6 +689,25 @@ namespace OHOS::xml { } } } + + std::string XmlPullParser::ParseName() + { + if (position_ >= max_ && !DealLength(1)) { + xmlPullParserError_ = "name expected"; + return ""; + } + int start = position_; + char c = strXml_[position_]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + c == '_' || c == ':' || relaxed) { + position_++; + } else { + xmlPullParserError_ = "name expected"; + return ""; + } + return ParseNameInner(start); + } + void XmlPullParser::SkipInvalidChar() { while (position_ < max_ || DealLength(1)) { @@ -706,7 +727,7 @@ namespace OHOS::xml { } if (strEntity.size() && strEntity[0] == '#') { int c = 0; - if (strEntity.size()>=2 && strEntity[1] == 'x') { // 2: number of args + if (strEntity.size() >= 2 && strEntity[1] == 'x') { // 2: number of args c = std::stoi(strEntity.substr(2), nullptr, 16); // 16: number of args 2: number of args } else { c = std::stoi(strEntity.substr(1), nullptr); @@ -756,13 +777,13 @@ namespace OHOS::xml { out += ';'; position_++; break; - } else if (c >= 128 // 128: number of args - || (c >= '0' && c <= '9') - || (c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || c == '_' - || c == '-' - || c == '#') { + } else if (c >= 128 || // 128: number of args + (c >= '0' && c <= '9') || + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + c == '_' || + c == '-' || + c == '#') { position_++; out.push_back(static_cast(c)); } else if (relaxed) { @@ -774,8 +795,8 @@ namespace OHOS::xml { ParseEntityFunc(start, out, isEntityToken, textEnum); } - bool XmlPullParser::ParseTagValueFunc(char c, bool throwOnResolveFailure, TextEnum textEnum, - int &start, std::string& result) + bool XmlPullParser::ParseTagValueFunc(char c, bool bFlag, TextEnum textEnum, + size_t &start, std::string& result) { if (c == '\r') { if ((position_ + 1 < max_ || DealLength(2)) && strXml_[position_ + 1] == '\n') { // 2: number of args @@ -786,7 +807,7 @@ namespace OHOS::xml { c = ' '; } else if (c == '&') { bWhitespace_ = false; - ParseEntity(result, false, throwOnResolveFailure, textEnum); + ParseEntity(result, false, bFlag, textEnum); start = position_; return false; } else if (c == '<') { @@ -795,8 +816,8 @@ namespace OHOS::xml { } bWhitespace_ = false; } else if (c == ']') { - if ((position_ + 2 < max_ || DealLength(3)) // 2: number of args 3: number of args - && strXml_[position_ + 1] == ']' && strXml_[position_ + 2] == '>') { // 2: number of args + if ((position_ + 2 < max_ || DealLength(3)) && // 2: number of args 3: number of args + strXml_[position_ + 1] == ']' && strXml_[position_ + 2] == '>') { // 2: number of args xmlPullParserError_ = "Illegal: \"]]>\" outside CDATA section"; } bWhitespace_ = false; @@ -807,44 +828,67 @@ namespace OHOS::xml { } return true; } - + + void XmlPullParser::DealWhiteSpace(char c) + { + if (bWhitespace_ && c <= ' ') { + bWhitespace_ = true; + } else { + bWhitespace_ = false; + } + } + + int XmlPullParser::ParseTagValueInner(size_t &start, std::string &result, + char delimiter, TextEnum textEnum, bool bFlag) + { + if (position_ >= max_) { + if (start < position_) { + result.append(strXml_, start, position_ - start); + } + if (!DealLength(1)) { + result = (result != "" ? result : ""); + return 0; + } + start = position_; + } + char c = strXml_[position_]; + if (c == delimiter || + (delimiter == ' ' && (c <= ' ' || c == '>')) || + (c == '&' && !bFlag)) { + return 1; + } + if (c != '\r' && (c != '\n' || textEnum != TextEnum::ATTRI) && + c != '&' && c != '<' && (c != ']' || textEnum != TextEnum::TEXT) + && (c != '%' || textEnum != TextEnum::ENTITY_DECL)) { + DealWhiteSpace(c); + position_++; + return 2; // 2: break flag + } + result.append(strXml_, start, position_ - start); + return c; + } + std::string XmlPullParser::ParseTagValue(char delimiter, bool resolveEntities, bool throwOnResolveFailure, TextEnum textEnum) { - int start = position_; + size_t start = position_; std::string result = " "; if (textEnum == TextEnum::TEXT && text_ != "") { result.append(text_); } while (true) { - if (position_ >= max_) { - if (start < position_) { - result.append(strXml_, start, position_ - start); - } - if (!DealLength(1)) { - return result != "" ? result : ""; - } - start = position_; - } - char c = strXml_[position_]; - if (c == delimiter - || (delimiter == ' ' && (c <= ' ' || c == '>')) - || (c == '&' && !resolveEntities)) { - break; - } - if (c != '\r' && (c != '\n' || textEnum != TextEnum::ATTRI) - && c != '&' && c != '<' && (c != ']' || textEnum != TextEnum::TEXT) - && (c != '%' || textEnum != TextEnum::ENTITY_DECL)) { - bWhitespace_ &= (c <= ' '); - position_++; + size_t iRecv = ParseTagValueInner(start, result, delimiter, textEnum, resolveEntities); + if (iRecv == 0) { + return result; + } else if (iRecv == 1) { + break; + } else if (iRecv == 2) { // 2: break flag continue; - } - result.append(strXml_, start, position_ - start); - if (!ParseTagValueFunc(c, throwOnResolveFailure, textEnum, start, result)) { + } else if (!ParseTagValueFunc(static_cast(iRecv), throwOnResolveFailure, textEnum, start, result)) { continue; } - position_++; - result = result + c; + ++position_; + result = result + static_cast(iRecv); start = position_; } result.append(strXml_, start, position_ - start); @@ -853,13 +897,8 @@ namespace OHOS::xml { std::string XmlPullParser::GetNamespace(std::string prefix) { - if (prefix == "xml") { - return "http://www.w3.org/XML/1998/namespace"; - } - if (prefix == "xmlns") { - return "http://www.w3.org/2000/xmlns/"; - } - for (int i = (GetNSCount(depth) << 1) - 2; i >= 0; i -= 2) { // 2: number of args + int i = (GetNSCount(depth) << 1) - 2; // 2: number of args + for (; i >= 0; i -= 2) { // 2: number of args if (prefix == "") { if (nspStack_[i] == "") { return nspStack_[i + 1]; @@ -871,18 +910,18 @@ namespace OHOS::xml { return ""; } - void XmlPullParser::Replace(std::string& strTemp, std::string strSrc, std::string strDes) + void XmlPullParser::Replace(std::string& strTemp, std::string strSrc, std::string strDes) const { size_t iPos = 0; while ((iPos = strTemp.find(strSrc)) != std::string::npos) { strTemp.replace(iPos, strSrc.size(), strDes); } } - void XmlPullParser::ParseNspFunc(int &i, std::string &attrName, bool &any) + void XmlPullParser::ParseNspFunc(size_t &i, std::string &attrName, bool &any) { - int j = (nspCounts_[depth]++) << 1; - size_t ui_size = nspStack_.size(); - if (ui_size < j + 2) { // 2: number of args + size_t j = (nspCounts_[depth]++) << 1; + size_t uiSize = nspStack_.size(); + if (uiSize < j + 2) { // 2: number of args nspStack_.resize(j + 16); // 16: number of args } nspStack_[j] = attrName; @@ -900,9 +939,10 @@ namespace OHOS::xml { i -= 4; // 4: } } - void XmlPullParser::ParseNspFunc_() + void XmlPullParser::ParseNspFunction() { - for (int i = (attriCount_ << 2) - 4; i >= 0; i -= 4) { // 4: number of args 2: number of args + int i = (attriCount_ << 2) - 4; // 4: number of args 2: number of args + for (; i >= 0; i -= 4) { // 4: number of args std::string attrName = attributes[i + 2]; // 2: number of args int cut = attrName.find(':'); if (cut == 0 && !relaxed) { @@ -923,7 +963,7 @@ namespace OHOS::xml { bool XmlPullParser::ParseNsp() { bool any = false; - for (int i = 0; i < (attriCount_ << 2); i += 4) { // 2 and 4: number of args + for (size_t i = 0; i < (attriCount_ << 2); i += 4) { // 2 and 4: number of args std::string attrName = attributes[i + 2]; // 2: number of args int cut = attrName.find(':'); std::string prefix; @@ -943,7 +983,7 @@ namespace OHOS::xml { } } if (any) { - ParseNspFunc_(); + ParseNspFunction(); } int cut = name_.find(':'); if (cut == 0) { @@ -1047,7 +1087,7 @@ namespace OHOS::xml { if (!bRecv) { return; } - int sp = depth++ * 4; // 4: number of args + size_t sp = depth++ * 4; // 4: number of args elementStack_.resize(sp + 4); // 4: number of args elementStack_[sp + 3] = name_; // 3: number of args if (depth >= nspCounts_.size()) { @@ -1083,7 +1123,7 @@ namespace OHOS::xml { xmlPullParserError_ = "version expected"; } version_ = attributes[3]; // 3: number of args - int pos = 1; + size_t pos = 1; if (pos < attriCount_ && (attributes[2 + 4]) == "encoding") { // 4: number of args 2: number of args encoding_ = attributes[3 + 4]; // 3: number of args 4: number of args pos++; @@ -1130,7 +1170,7 @@ namespace OHOS::xml { std::string XmlPullParser::ParseDelimiterInfo(std::string delimiter, bool returnText) { - int start = position_; + size_t start = position_; std::string result = ""; if (returnText && text_ != "") { result.append(text_); @@ -1147,7 +1187,7 @@ namespace OHOS::xml { } start = position_; } - int i = 0; + size_t i = 0; for (; i < delimiter.length(); i++) { if (strXml_[position_ + i] != delimiter[i]) { position_++; @@ -1269,7 +1309,7 @@ namespace OHOS::xml { SkipInvalidChar(); SkipChar('>'); } - + void XmlPullParser::ParseInnerAttriDeclFunc(int &c) { if (c == '(') { @@ -1388,7 +1428,7 @@ namespace OHOS::xml { SkipInvalidChar(); SkipChar('>'); } - void XmlPullParser::readInternalSubset() + void XmlPullParser::ReadInternalSubset() { SkipChar('['); while (true) { @@ -1440,7 +1480,7 @@ namespace OHOS::xml { ParserDoctInnerInfo(true, true); SkipInvalidChar(); if (PriorDealChar() == '[') { - readInternalSubset(); + ReadInternalSubset(); } SkipInvalidChar(); if (saveDtdText) { @@ -1568,10 +1608,10 @@ namespace OHOS::xml { text_ = ParseDelimiterInfo(tagText_.END_PROCESSING_INSTRUCTION, true); } - int XmlPullParser::GetColumnNumber() + int XmlPullParser::GetColumnNumber() const { - int result = bufferStartColumn_; - for (int i = 0; i < position_; i++) { + size_t result = bufferStartColumn_; + for (size_t i = 0; i < position_; i++) { if (strXml_[i] == '\n') { result = 0; } else { @@ -1580,30 +1620,30 @@ namespace OHOS::xml { } return result + 1; } - int XmlPullParser::GetDepth() + int XmlPullParser::GetDepth() const { return depth; } - int XmlPullParser::GetLineNumber() + int XmlPullParser::GetLineNumber() const { int result = bufferStartLine_; - for (int i = 0; i < position_; i++) { + for (size_t i = 0; i < position_; i++) { if (strXml_[i] == '\n') { result++; } } return result + 1; } - std::string XmlPullParser::GetName() + std::string XmlPullParser::GetName() const { return name_; } - std::string XmlPullParser::GetPrefix() + std::string XmlPullParser::GetPrefix() const { return prefix_; } - std::string XmlPullParser::GetText() + std::string XmlPullParser::GetText() const { if (type < TagEnum::TEXT || (type == TagEnum::ENTITY_REFERENCE && bUnresolved_)) { return ""; @@ -1611,22 +1651,22 @@ namespace OHOS::xml { return text_; } } - bool XmlPullParser::IsEmptyElementTag() + bool XmlPullParser::IsEmptyElementTag() const { return bEndFlag_; } - int XmlPullParser::GetAttributeCount() + int XmlPullParser::GetAttributeCount() const { return attriCount_; } - bool XmlPullParser::IsWhitespace() + bool XmlPullParser::IsWhitespace() const { return bWhitespace_; } - - std::string XmlPullParser::GetNamespace() + + std::string XmlPullParser::GetNamespace() const { return namespace_; } @@ -1639,9 +1679,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - int temp = (reinterpret_cast(obj))->GetColumnNumber(); napi_value result = nullptr; - napi_create_int32(env, temp, &result); + if (obj != nullptr) { + int temp = (reinterpret_cast(obj))->GetColumnNumber(); + napi_create_int32(env, temp, &result); + } return result; } @@ -1653,9 +1695,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - int tempDepth = (reinterpret_cast(obj))->GetDepth(); napi_value result = nullptr; - napi_create_int32(env, tempDepth, &result); + if (obj != nullptr) { + int temp = (reinterpret_cast(obj))->GetDepth(); + napi_create_int32(env, temp, &result); + } return result; } @@ -1667,9 +1711,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - int temp = (reinterpret_cast(obj))->GetLineNumber(); napi_value result = nullptr; - napi_create_int32(env, temp, &result); + if (obj != nullptr) { + int temp = (reinterpret_cast(obj))->GetLineNumber(); + napi_create_int32(env, temp, &result); + } return result; } @@ -1681,9 +1727,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - std::string temp = (reinterpret_cast(obj))->GetName(); napi_value result = nullptr; - napi_create_string_utf8(env, temp.c_str(), temp.length(), &result); + if (obj != nullptr) { + std::string temp = (reinterpret_cast(obj))->GetName(); + napi_create_string_utf8(env, temp.c_str(), temp.length(), &result); + } return result; } @@ -1695,9 +1743,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - std::string temp = (reinterpret_cast(obj))->GetNamespace(); napi_value result = nullptr; - napi_create_string_utf8(env, temp.c_str(), temp.length(), &result); + if (obj != nullptr) { + std::string temp = (reinterpret_cast(obj))->GetNamespace(); + napi_create_string_utf8(env, temp.c_str(), temp.length(), &result); + } return result; } @@ -1709,9 +1759,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - std::string temp = (reinterpret_cast(obj))->GetPrefix(); napi_value result = nullptr; - napi_create_string_utf8(env, temp.c_str(), temp.length(), &result); + if (obj != nullptr) { + std::string temp = (reinterpret_cast(obj))->GetPrefix(); + napi_create_string_utf8(env, temp.c_str(), temp.length(), &result); + } return result; } @@ -1723,9 +1775,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - std::string temp = (reinterpret_cast(obj))->GetText(); napi_value result = nullptr; - napi_create_string_utf8(env, temp.c_str(), temp.length(), &result); + if (obj != nullptr) { + std::string temp = (reinterpret_cast(obj))->GetText(); + napi_create_string_utf8(env, temp.c_str(), temp.length(), &result); + } return result; } @@ -1737,9 +1791,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - bool temp = (reinterpret_cast(obj))->IsEmptyElementTag(); napi_value result = nullptr; - napi_get_boolean(env, temp, &result); + if (obj != nullptr) { + bool temp = (reinterpret_cast(obj))->IsEmptyElementTag(); + napi_get_boolean(env, temp, &result); + } return result; } @@ -1751,9 +1807,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - bool temp = (reinterpret_cast(obj))->IsWhitespace(); napi_value result = nullptr; - napi_get_boolean(env, temp, &result); + if (obj != nullptr) { + bool temp = (reinterpret_cast(obj))->IsWhitespace(); + napi_get_boolean(env, temp, &result); + } return result; } @@ -1765,9 +1823,11 @@ namespace OHOS::xml { void *obj = nullptr; napi_get_named_property(env, thisVar, "MainInfo", &mainVar); NAPI_CALL(env, napi_unwrap(env, mainVar, &obj)); - int temp = (reinterpret_cast(obj))->GetAttributeCount(); napi_value result = nullptr; - napi_create_int32(env, temp, &result); + if (obj != nullptr) { + int temp = (reinterpret_cast(obj))->GetAttributeCount(); + napi_create_int32(env, temp, &result); + } return result; } } // namespace diff --git a/xml/js_xml.h b/xml/js_xml.h index 33db009c..7afb004c 100644 --- a/xml/js_xml.h +++ b/xml/js_xml.h @@ -15,12 +15,11 @@ #ifndef FOUNDATION_ACE_CCRUNTIME_XML_CLASS_H #define FOUNDATION_ACE_CCRUNTIME_XML_CLASS_H +#include +#include #include #include #include -#include -#include -#include #include "napi/native_api.h" #include "napi/native_node_api.h" #include "utils/log.h" @@ -28,13 +27,15 @@ namespace OHOS::xml { class XmlSerializer { public: - XmlSerializer(napi_env env, char *pStart, size_t bufferLength, std::string encoding = "utf-8"); + XmlSerializer(char *pStart, size_t bufferLength, std::string encoding = "utf-8") :pStart_(pStart), + iLength_(bufferLength), encoding_(encoding){}; + ~XmlSerializer(){} void SetAttributes(std::string name, std::string value); void AddEmptyElement(std::string name); void SetDeclaration(); void StartElement(std::string name); void EndElement(); - void SetNamespace(std::string prefix, std::string ns_Temp); + void SetNamespace(std::string prefix, std::string nsTemp); void SetCommnet(std::string comment); void SetCData(std::string data); void SetText(std::string text); @@ -43,20 +44,20 @@ namespace OHOS::xml { void SplicNsp(); void NextItem(); std::string XmlSerializerError(); - static napi_status DealNapiStrValue(napi_env env, const napi_value napi_StrValue, std::string &result); + static napi_status DealNapiStrValue(napi_env env, const napi_value napiStr, std::string &result); private: - napi_env env_; char *pStart_; size_t iPos_ = 0; size_t iLength_; std::string xmlSerializerError_; std::string encoding_; - int depth_ = 0; + size_t depth_ = 0; std::string type; std::vector elementStack = { "", "", ""}; std::map> multNsp; int CurNspNum = 0; std::string out_; + bool isHasDecl = false; }; enum class TagEnum { @@ -80,7 +81,7 @@ namespace OHOS::xml { OK, ERROR1 }; - + enum class TextEnum { ATTRI, TEXT, @@ -126,6 +127,7 @@ namespace OHOS::xml { const std::string START_NOTATION = "position = -1; this->max = -1; }; - SrcLinkList(SrcLinkList* next, std::string strBuffer, int position, int max) - { - this->next = next; - this->strBuffer = strBuffer; - this->position = position; - this->max = max; - } + SrcLinkList(SrcLinkList* pNext, std::string strTemp, int iPos, int iMax) :next(pNext), + strBuffer(strTemp), position(iPos), max(iMax){} }; - XmlPullParser(napi_env env, std::string strXml, std::string encoding) :env_(env), + XmlPullParser(napi_env env, std::string strXml, std::string encoding) : env_(env), strXml_(strXml), encoding_(encoding) {}; - ~XmlPullParser() {}; - int GetDepth(); - int GetColumnNumber(); - int GetLineNumber(); - int GetAttributeCount(); - std::string GetName(); - std::string GetNamespace(); - std::string GetPrefix(); - std::string GetText(); - bool IsEmptyElementTag(); - bool IsWhitespace(); + ~XmlPullParser() + { + while (srcLinkList_) { + PopSrcLinkList(); + } + }; + int GetDepth() const; + int GetColumnNumber() const; + int GetLineNumber() const; + int GetAttributeCount() const; + std::string GetName() const; + std::string GetNamespace() const; + std::string GetPrefix() const; + std::string GetText() const; + bool IsEmptyElementTag() const; + bool IsWhitespace() const; void PushSrcLinkList(std::string strBuffer); void PopSrcLinkList(); - bool DealLength(int minimun); - void Replace(std::string &strTemp, std::string strSrc, std::string strDes); - int GetNSCount(int iTemp); + bool DealLength(size_t minimun); + void Replace(std::string &strTemp, std::string strSrc, std::string strDes) const; + size_t GetNSCount(size_t iTemp); void Parse(napi_value thisVar); std::string GetNamespace(std::string prefix); napi_value DealOptionInfo(napi_value napiObj, napi_callback_info info); @@ -172,6 +174,7 @@ namespace OHOS::xml { void SkipText(std::string chars); int PriorDealChar(); void SkipChar(char expected); + std::string ParseNameInner(int start); std::string ParseName(); void SkipInvalidChar(); void ParseEntity(std::string& out, bool isEntityToken, bool throwOnResolveFailure, TextEnum textEnum); @@ -189,25 +192,29 @@ namespace OHOS::xml { void ParseInnerAttriDecl(); void ParseEntityDecl(); void ParseInneNotaDecl(); - void readInternalSubset(); + void ReadInternalSubset(); void ParseDoctype(bool saveDtdText); TagEnum ParseOneTag(); void ParserPriorDeal(); void ParseInstruction(); void ParseText(); void ParseCdect(); - std::string XmlPullParserError(); - bool ParseAttri(napi_value thisVar); - bool ParseToken(napi_value thisVar); - void ParseNspFunc_(); - void ParseNspFunc(int &i, std::string &attrName, bool &any); + std::string XmlPullParserError() const; + bool ParseAttri(napi_value thisVar) const; + bool ParseToken(napi_value thisVar) const; + void ParseNspFunction(); + void ParseNspFunc(size_t &i, std::string &attrName, bool &any); void ParseInnerAttriDeclFunc(int &c); - TagEnum ParseTagTypeFunc(); + TagEnum DealExclamationGroup(); void ParseEntityFunc(int start, std::string &out, bool isEntityToken, TextEnum textEnum); bool ParseStartTagFuncDeal(bool throwOnResolveFailure); bool ParseStartTagFunc(bool xmldecl, bool throwOnResolveFailure); TagEnum ParseOneTagFunc(); - bool ParseTagValueFunc(char c, bool throwOnResolveFailure, TextEnum textEnum, int &start, std::string &result); + int ParseTagValueInner(size_t &start, std::string &result, char delimiter, TextEnum textEnum, bool bFlag); + bool ParseTagValueFunc(char c, bool bFlag, TextEnum textEnum, size_t &start, std::string &result); + void MakeStrUpper(std::string &src) const; + TagEnum DealLtGroup(); + void DealWhiteSpace(char c); private: napi_env env_; bool bDoctype_ = false; @@ -227,22 +234,22 @@ namespace OHOS::xml { std::string sysInfo_ = ""; std::string pubInfo_ = ""; std::string keyInfo_ = ""; - std::string xmlPullParserError_; - std::vector nspCounts_; + std::string xmlPullParserError_ = ""; + std::vector nspCounts_; std::vector nspStack_; std::vector elementStack_; std::vector attributes; std::map documentEntities; std::map> defaultAttributes; std::map DEFAULT_ENTITIES = { - {"lt;", "<"}, {"gt;", ">"}, {"amp;", "&"}, {"apos;", "'"}, {"quot;", "\""} + {"lt;", "<"}, {"gt;", ">"}, {"amp;", "&"}, {"apos;", "'"}, {"quot;", "\""} }; - int position_ = 0; - int depth = 0; - int max_ = 0; - int bufferStartLine_ = 0; - int bufferStartColumn_ = 0; - int attriCount_ = 0; + size_t position_ = 0; + size_t depth = 0; + size_t max_ = 0; + size_t bufferStartLine_ = 0; + size_t bufferStartColumn_ = 0; + size_t attriCount_ = 0; TagEnum type = TagEnum::START_DOCUMENT; bool bWhitespace_ = false; SrcLinkList* srcLinkList_ = new SrcLinkList; diff --git a/xml/native_module_xml.cpp b/xml/native_module_xml.cpp index 401b6244..0eb05372 100644 --- a/xml/native_module_xml.cpp +++ b/xml/native_module_xml.cpp @@ -50,7 +50,7 @@ namespace OHOS::xml { } } if (argc == 1) { - object = new XmlSerializer(env, reinterpret_cast(data), iLength); + object = new XmlSerializer(reinterpret_cast(data), iLength); } else if (argc == 2) { // 2:When the input parameter is set to 2 std::string encoding = ""; napi_valuetype valuetype; @@ -59,7 +59,7 @@ namespace OHOS::xml { napi_status status = napi_ok; status = XmlSerializer::DealNapiStrValue(env, args[1], encoding); if (status == napi_ok) { - object = new XmlSerializer(env, reinterpret_cast(data), iLength, encoding); + object = new XmlSerializer(reinterpret_cast(data), iLength, encoding); } } napi_wrap( @@ -174,7 +174,7 @@ namespace OHOS::xml { NAPI_CALL(env, napi_get_undefined(env, &result)); return result; } - + static napi_value SetDeclaration(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; @@ -349,7 +349,7 @@ namespace OHOS::xml { { const char *xmlSerializerClass = "XmlSerializer"; napi_value xmlClass = nullptr; - static napi_property_descriptor XmlDesc[] = { + static napi_property_descriptor xmlDesc[] = { DECLARE_NAPI_FUNCTION("setAttributes", SetAttributes), DECLARE_NAPI_FUNCTION("addEmptyElement", AddEmptyElement), DECLARE_NAPI_FUNCTION("setDeclaration", SetDeclaration), @@ -360,10 +360,10 @@ namespace OHOS::xml { DECLARE_NAPI_FUNCTION("setCData", SetCData), DECLARE_NAPI_FUNCTION("setText", SetText), DECLARE_NAPI_FUNCTION("setDocType", SetDocType), - DECLARE_NAPI_FUNCTION("xmlSerializerError", XmlSerializerError) + DECLARE_NAPI_FUNCTION("XmlSerializerError", XmlSerializerError) }; NAPI_CALL(env, napi_define_class(env, xmlSerializerClass, strlen(xmlSerializerClass), XmlSerializerConstructor, - nullptr, sizeof(XmlDesc) / sizeof(XmlDesc[0]), XmlDesc, &xmlClass)); + nullptr, sizeof(xmlDesc) / sizeof(xmlDesc[0]), xmlDesc, &xmlClass)); static napi_property_descriptor desc[] = { DECLARE_NAPI_PROPERTY("XmlSerializer", xmlClass) }; @@ -409,13 +409,13 @@ namespace OHOS::xml { { const char *xmlPullParserClass = "XmlPullParser"; napi_value xmlClass = nullptr; - static napi_property_descriptor XmlDesc[] = { + static napi_property_descriptor xmlDesc[] = { DECLARE_NAPI_FUNCTION("parse", Parse), - DECLARE_NAPI_FUNCTION("xmlPullParserError", XmlPullParserError) + DECLARE_NAPI_FUNCTION("XmlPullParserError", XmlPullParserError) }; NAPI_CALL(env, napi_define_class(env, xmlPullParserClass, strlen(xmlPullParserClass), - XmlPullParserConstructor, nullptr, sizeof(XmlDesc) / sizeof(XmlDesc[0]), - XmlDesc, &xmlClass)); + XmlPullParserConstructor, nullptr, sizeof(xmlDesc) / sizeof(xmlDesc[0]), + xmlDesc, &xmlClass)); static napi_property_descriptor desc[] = { DECLARE_NAPI_PROPERTY("XmlPullParser", xmlClass) }; @@ -423,7 +423,6 @@ namespace OHOS::xml { return exports; }; - static napi_value Init(napi_env env, napi_value exports) { XmlSerializerInit(env, exports); @@ -454,7 +453,7 @@ namespace OHOS::xml { } - static napi_module XmlModule = { + static napi_module xmlModule = { .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, @@ -465,6 +464,6 @@ namespace OHOS::xml { }; extern "C" __attribute__((constructor)) void RegisterModule() { - napi_module_register(&XmlModule); + napi_module_register(&xmlModule); } } // namespace diff --git a/xml/src/js_xml.ts b/xml/src/js_xml.ts index b7544ae0..5e3cb607 100644 --- a/xml/src/js_xml.ts +++ b/xml/src/js_xml.ts @@ -13,27 +13,60 @@ * limitations under the License. */ -declare function requireInternal(s : string) : any; -const Xml = requireInternal('xml'); +interface NativeXmlPullParser{ + new(value : object, strEncoding? : string) : NativeXmlPullParser; + parse(options : object) : void; + XmlPullParserError() : string; +} +interface NativeXMLSerializer{ + new(value : object, strEncoding? : string) : NativeXMLSerializer; + setAttributes(name : string, value : string) : void; + addEmptyElement(name : string) : void; + setDeclaration() : void; + startElement(name : string) : void; + endElement() : void; + setNamespace(prefix : string, namespace : string) : void; + setCommnet(text : string) : void; + setCData(text : string) : void; + setText(text : string) : void; + setDocType(text : string) : void; + XmlSerializerError() : string; +} +interface Xml{ + XmlSerializer : NativeXMLSerializer; + XmlPullParser : NativeXmlPullParser; +} +declare function requireInternal(s : string) : Xml; +const XML = requireInternal('xml'); class XmlSerializer { - xmlserializerclass : any; - constructor(input:any, str:string) { - if(typeof input !== 'object' || typeof str !== 'string' || str.length === 0) { - throw new Error("input type err"); - } - this.xmlserializerclass = new Xml.XmlSerializer(input, str); - let errStr = this.xmlserializerclass.xmlSerializerError(); - if (errStr.length !== 0) { - throw new Error(errStr); + xmlSerializerClass : NativeXMLSerializer; + constructor() { + if(typeof arguments[0] !== 'object') { + throw new Error("input type err"); + } + if (arguments.length === 1) { + let str = 'utf-8'; + this.xmlSerializerClass = new XML.XmlSerializer(arguments[0], str); + } else if (arguments.length === 2 && (typeof arguments[1] === 'string' && arguments[1].length !== 0)) { + var strTemp = arguments[1]; + if (strTemp.toLowerCase() !== 'utf-8') { + throw new Error("Just support utf-8"); } + this.xmlSerializerClass = new XML.XmlSerializer(arguments[0], arguments[1]); + } else { + throw new Error("input type err"); + } + let errStr = this.xmlSerializerClass.XmlSerializerError(); + if (errStr.length !== 0) { + throw new Error(errStr); + } } - - setAttributes(name: string, value: string) { + setAttributes(name : string, value : string) { if (typeof name !== 'string' || name.length === 0 || typeof value !== 'string' || name.length === 0 ) { throw new Error("name or value type err"); } - this.xmlserializerclass.setAttributes(name, value); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.setAttributes(name, value); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } @@ -42,16 +75,15 @@ class XmlSerializer { if (typeof name !== 'string' || name.length === 0) { throw new Error("name type err"); } - this.xmlserializerclass.addEmptyElement(name); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.addEmptyElement(name); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } - } setDeclaration() { - this.xmlserializerclass.setDeclaration(); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.setDeclaration(); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } @@ -60,25 +92,25 @@ class XmlSerializer { if (typeof name !== 'string' || name.length === 0) { throw new Error("name type err"); } - this.xmlserializerclass.startElement(name); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.startElement(name); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } } endElement() { - this.xmlserializerclass.endElement(); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.endElement(); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } } - setNamespace(prefix: string, namespace: string) { - if (typeof prefix !== 'string' || prefix.length === 0 || typeof namespace !== 'string' || namespace.length === 0 ) { + setNamespace(prefix : string, ns : string) { + if (typeof prefix !== 'string' || prefix.length === 0 || typeof ns !== 'string' || ns.length === 0 ) { throw new Error("prefix or namespace type err"); } - this.xmlserializerclass.setNamespace(prefix, namespace); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.setNamespace(prefix, ns); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } @@ -87,8 +119,8 @@ class XmlSerializer { if (typeof text !== 'string' || text.length === 0) { throw new Error("text type err"); } - this.xmlserializerclass.setCommnet(text); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.setCommnet(text); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } @@ -97,8 +129,8 @@ class XmlSerializer { if (typeof text !== 'string' || text.length === 0) { throw new Error("text type err"); } - this.xmlserializerclass.setCData(text); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.setCData(text); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } @@ -107,8 +139,8 @@ class XmlSerializer { if (typeof text !== 'string' || text.length === 0) { throw new Error("text type err"); } - this.xmlserializerclass.setText(text); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.setText(text); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } @@ -117,8 +149,8 @@ class XmlSerializer { if (typeof text !== 'string' || text.length === 0) { throw new Error("text type err"); } - this.xmlserializerclass.setDocType(text); - let errStr = this.xmlserializerclass.xmlSerializerError(); + this.xmlSerializerClass.setDocType(text); + let errStr = this.xmlSerializerClass.XmlSerializerError(); if (errStr.length !== 0) { throw new Error(errStr); } @@ -126,32 +158,41 @@ class XmlSerializer { } class XmlPullParser { - xmlpullparsercalss : any; - constructor(input:any, str:string) { - if(typeof input !== 'object' || typeof str !== 'string' || str.length === 0) { + xmlPullParserClass : NativeXmlPullParser; + constructor() { + if(typeof arguments[0] !== 'object') { + throw new Error("input type err"); + } + if (arguments.length === 1) { + let str = 'utf-8'; + this.xmlPullParserClass = new XML.XmlPullParser(arguments[0], str); + } else if (arguments.length === 2 && (typeof arguments[1] === 'string' && arguments[1].length !== 0)) { + var strTemp = arguments[1]; + if (strTemp.toLowerCase() !== 'utf-8') { + throw new Error("Just support utf-8"); + } + this.xmlPullParserClass = new XML.XmlPullParser(arguments[0], arguments[1]); + } else { throw new Error("input type err"); } - this.xmlpullparsercalss = new Xml.XmlPullParser(input, str); - var err = this.xmlpullparsercalss.xmlPullParserError(); - if (err.length !== 0) { - throw new Error(err); + let errStr = this.xmlPullParserClass.XmlPullParserError(); + if (errStr.length !== 0) { + throw new Error(errStr); } } - parse(options : any) { + parse(options : object) { if(typeof options !== 'object') { throw new Error("options type err"); } - this.xmlpullparsercalss.parse(options); - let errStr = this.xmlpullparsercalss.xmlPullParserError(); + this.xmlPullParserClass.parse(options); + let errStr = this.xmlPullParserClass.XmlPullParserError(); if (errStr.length !== 0) { throw new Error(errStr); } - } } +} export default { XmlSerializer : XmlSerializer, XmlPullParser : XmlPullParser, } - - diff --git a/xml/tsconfig.json b/xml/tsconfig.json index c86e350c..825df281 100644 --- a/xml/tsconfig.json +++ b/xml/tsconfig.json @@ -1,8 +1,8 @@ { "compilerOptions": { "target": "es6", - "module": "es6", - "rootDir": "./src", + "module": "es6", + "rootDir": "./src", //"outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ "outDir": "./out", /* Specify an output folder for all emitted files. */ "esModuleInterop": true, -- Gitee From d6f9f4843de08174ddc207817fe579ae30ae5e9f Mon Sep 17 00:00:00 2001 From: lifansheng Date: Tue, 21 Dec 2021 19:11:19 +0800 Subject: [PATCH 2/5] Signed-off-by: lifansheng Please enter the commit message for your changes. Lines starting with '#' will be ignored, and an empty message aborts the commit. --- build_ts_js.py | 0 xml/js_xml.cpp | 4 ++-- xml/js_xml.h | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) mode change 100644 => 100755 build_ts_js.py diff --git a/build_ts_js.py b/build_ts_js.py old mode 100644 new mode 100755 diff --git a/xml/js_xml.cpp b/xml/js_xml.cpp index 1487efb0..5ab0d84f 100644 --- a/xml/js_xml.cpp +++ b/xml/js_xml.cpp @@ -584,7 +584,7 @@ namespace OHOS::xml { } else if (cTemp == '?') { std::string strXml = strXml_.substr(position_ + 2, 4); // 2 and 4:position and length MakeStrUpper(strXml); - if (max_ >= position_ + 5 && strXml == tagText_.XML) { + if (max_ >= position_ + 5 && strXml == tagText_.XML) { // 5: number of args return TagEnum::XML_DECLARATION; } else { return TagEnum::INSTRUCTION; @@ -623,7 +623,7 @@ namespace OHOS::xml { while (i < src.size()) { if (src[i] >= 'A' && src[i] <= 'Z') { - src[i] += 32; + src[i] += 32; // 32: number of args } ++i; } diff --git a/xml/js_xml.h b/xml/js_xml.h index 7afb004c..ac592ebb 100644 --- a/xml/js_xml.h +++ b/xml/js_xml.h @@ -28,8 +28,8 @@ namespace OHOS::xml { class XmlSerializer { public: XmlSerializer(char *pStart, size_t bufferLength, std::string encoding = "utf-8") :pStart_(pStart), - iLength_(bufferLength), encoding_(encoding){}; - ~XmlSerializer(){} + iLength_(bufferLength), encoding_(encoding) {}; + ~XmlSerializer() {} void SetAttributes(std::string name, std::string value); void AddEmptyElement(std::string name); void SetDeclaration(); @@ -142,7 +142,7 @@ namespace OHOS::xml { this->max = -1; }; SrcLinkList(SrcLinkList* pNext, std::string strTemp, int iPos, int iMax) :next(pNext), - strBuffer(strTemp), position(iPos), max(iMax){} + strBuffer(strTemp), position(iPos), max(iMax) {} }; XmlPullParser(napi_env env, std::string strXml, std::string encoding) : env_(env), strXml_(strXml), encoding_(encoding) {}; -- Gitee From df9a5311a834c9f7f43e087c58af4f93fde38401 Mon Sep 17 00:00:00 2001 From: lifansheng Date: Tue, 21 Dec 2021 19:37:56 +0800 Subject: [PATCH 3/5] Signed-off-by: lifansheng On branch master Your branch is up to date with 'origin/master'. --- convertxml/BUILD.gn | 224 ++++++++++++++++++++++---------------------- 1 file changed, 112 insertions(+), 112 deletions(-) diff --git a/convertxml/BUILD.gn b/convertxml/BUILD.gn index 11ae5745..dc820249 100755 --- a/convertxml/BUILD.gn +++ b/convertxml/BUILD.gn @@ -1,113 +1,113 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and # limitations under the License. - -import("//ark/ts2abc/ts2panda/ts2abc_config.gni") -import("//build/ohos.gni") -import("//build/ohos/ace/ace.gni") -import("//foundation/ace/ace_engine/ace_config.gni") - -# compile .ts to .js. -action("build_ts_js") { - script = "//base/compileruntime/js_api_module/build_ts_js.py" - args = [ - "--dst-file", - rebase_path(target_out_dir + "/js_convertxml.js"), - "--module-path", - rebase_path("/base/compileruntime/js_api_module/convertxml"), - "--out-file", - rebase_path("./out/js_convertxml.js"), - ] - depfile = "$target_gen_dir/$target_name.d" - outputs = [ target_out_dir + "/js_convertxml.js" ] -} -base_output_path = get_label_info(":js_convertxml", "target_out_dir") -js_xml_obj_path = base_output_path + "/convertxml.o" -gen_js_obj("js_convertxml") { - input = "$target_out_dir/js_convertxml.js" - output = js_xml_obj_path - dep = ":build_ts_js" -} - -# compile .js to .abc. -action("gen_convertxml_abc") { - visibility = [ ":*" ] - script = "//ark/ts2abc/ts2panda/scripts/generate_js_bytecode.py" - - args = [ - "--src-js", - rebase_path(target_out_dir + "/js_convertxml.js"), - "--dst-file", - rebase_path(target_out_dir + "/convertxml.abc"), - "--node", - rebase_path("${node_path}"), - "--frontend-tool-path", - rebase_path("${ts2abc_build_path}"), - "--node-modules", - rebase_path("${node_modules}"), - ] - deps = [ - ":build_ts_js", - "//ark/ts2abc/ts2panda:ark_ts2abc_build", - ] - - inputs = [ target_out_dir + "/js_convertxml.js" ] - outputs = [ target_out_dir + "/convertxml.abc" ] -} - -abc_output_path = get_label_info(":convertxml_abc", "target_out_dir") -convertxml_abc_obj_path = abc_output_path + "/convertxml_abc.o" -gen_js_obj("convertxml_abc") { - input = "$target_out_dir/convertxml.abc" - output = convertxml_abc_obj_path - dep = ":gen_convertxml_abc" -} - -ohos_shared_library("convertxml") { - include_dirs = [ - "//third_party/icu/icu4c/source/common", - "//third_party/node/src", - "//third_party/libxml2/include", - "//foundation/ace/napi/interfaces/kits", - "//base/compileruntime/js_api_module/convertxml", - ] - - sources = [ - "js_convertxml.cpp", - "native_module_convertxml.cpp", - ] - - deps = [ - ":convertxml_abc", - ":js_convertxml", - "//base/compileruntime/js_api_module/convertxml/:js_convertxml", - "//foundation/ace/napi/:ace_napi", - "//foundation/ace/napi/:ace_napi_quickjs", - "//third_party/icu/icu4c:static_icuuc", - "//third_party/libxml2:xml2", - "//utils/native/base:utils", - ] - - if (is_standard_system) { - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - } else { - external_deps = [ "hilog:libhilog" ] - } - subsystem_name = "ccruntime" - part_name = "jsapi_api" - - relative_install_dir = "module" -} - -group("convertxml_packages") { - deps = [ ":convertxml" ] -} + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/ace/ace.gni") +import("//foundation/ace/ace_engine/ace_config.gni") + +# compile .ts to .js. +action("build_ts_js") { + script = "//base/compileruntime/js_api_module/build_ts_js.py" + args = [ + "--dst-file", + rebase_path(target_out_dir + "/js_convertxml.js"), + "--module-path", + rebase_path("/base/compileruntime/js_api_module/convertxml"), + "--out-file", + rebase_path("./out/js_convertxml.js"), + ] + depfile = "$target_gen_dir/$target_name.d" + outputs = [ target_out_dir + "/js_convertxml.js" ] +} +base_output_path = get_label_info(":js_convertxml", "target_out_dir") +js_xml_obj_path = base_output_path + "/convertxml.o" +gen_js_obj("js_convertxml") { + input = "$target_out_dir/js_convertxml.js" + output = js_xml_obj_path + dep = ":build_ts_js" +} + +# compile .js to .abc. +action("gen_convertxml_abc") { + visibility = [ ":*" ] + script = "//ark/ts2abc/ts2panda/scripts/generate_js_bytecode.py" + + args = [ + "--src-js", + rebase_path(target_out_dir + "/js_convertxml.js"), + "--dst-file", + rebase_path(target_out_dir + "/convertxml.abc"), + "--node", + rebase_path("${node_path}"), + "--frontend-tool-path", + rebase_path("${ts2abc_build_path}"), + "--node-modules", + rebase_path("${node_modules}"), + ] + deps = [ + ":build_ts_js", + "//ark/ts2abc/ts2panda:ark_ts2abc_build", + ] + + inputs = [ target_out_dir + "/js_convertxml.js" ] + outputs = [ target_out_dir + "/convertxml.abc" ] +} + +abc_output_path = get_label_info(":convertxml_abc", "target_out_dir") +convertxml_abc_obj_path = abc_output_path + "/convertxml_abc.o" +gen_js_obj("convertxml_abc") { + input = "$target_out_dir/convertxml.abc" + output = convertxml_abc_obj_path + dep = ":gen_convertxml_abc" +} + +ohos_shared_library("convertxml") { + include_dirs = [ + "//third_party/icu/icu4c/source/common", + "//third_party/node/src", + "//third_party/libxml2/include", + "//foundation/ace/napi/interfaces/kits", + "//base/compileruntime/js_api_module/convertxml", + ] + + sources = [ + "js_convertxml.cpp", + "native_module_convertxml.cpp", + ] + + deps = [ + ":convertxml_abc", + ":js_convertxml", + "//base/compileruntime/js_api_module/convertxml/:js_convertxml", + "//foundation/ace/napi/:ace_napi", + "//foundation/ace/napi/:ace_napi_quickjs", + "//third_party/icu/icu4c:static_icuuc", + "//third_party/libxml2:xml2", + "//utils/native/base:utils", + ] + + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } + subsystem_name = "ccruntime" + part_name = "jsapi_api" + + relative_install_dir = "module" +} + +group("convertxml_packages") { + deps = [ ":convertxml" ] +} -- Gitee From 79a539389c6f8dfc06f327d5dded11eebd6ba4de Mon Sep 17 00:00:00 2001 From: lifansheng Date: Wed, 22 Dec 2021 11:03:29 +0800 Subject: [PATCH 4/5] Signed-off-by: lifansheng On branch master Your branch is up to date with 'origin/master'. --- README.md | 4 ++++ README_zh.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/README.md b/README.md index 4df80fe2..e07f1738 100755 --- a/README.md +++ b/README.md @@ -457,3 +457,7 @@ that.parse(options); [js_api_module Subsystem](https://gitee.com/OHOS_STD/js_api_module) [base/compileruntime/js_api_module/](base/compileruntime/js_api_module-readme.md) + +## License + +URL is available under [Mozilla license](https://www.mozilla.org/en-US/MPL/), and the documentation is detailed in [documentation](https://gitee.com/openharmony/js_api_module/blob/master/mozilla_docs.txt). See [LICENSE](https://gitee.com/openharmony/js_api_module/blob/master/LICENSE) for the full license text. \ No newline at end of file diff --git a/README_zh.md b/README_zh.md index 991f5c2e..f5fd90eb 100755 --- a/README_zh.md +++ b/README_zh.md @@ -456,3 +456,7 @@ that.parse(options); [js_api_module子系统](https://gitee.com/OHOS_STD/js_api_module) [base/compileruntime/js_api_module/](base/compileruntime/js_api_module/readme.md) + +### 许可证 + +URL在[Mozilla许可证](https://www.mozilla.org/en-US/MPL/)下可用,说明文档详见[说明文档](https://gitee.com/openharmony/js_api_module/blob/master/mozilla_docs.txt)。有关完整的许可证文本,有关完整的许可证文本,请参见[许可证](https://gitee.com/openharmony/js_api_module/blob/master/LICENSE) \ No newline at end of file -- Gitee From 2c6c4b8ff16d00df577638449cf498d6c657bb6f Mon Sep 17 00:00:00 2001 From: lifansheng Date: Wed, 22 Dec 2021 12:26:10 +0800 Subject: [PATCH 5/5] Signed-off-by: lifansheng On branch master Your branch is up to date with 'origin/master'. --- mgit.info | 1 - mozilla_docs.txt | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) delete mode 100644 mgit.info create mode 100644 mozilla_docs.txt diff --git a/mgit.info b/mgit.info deleted file mode 100644 index da19ada8..00000000 --- a/mgit.info +++ /dev/null @@ -1 +0,0 @@ -hmf/js_api_module diff --git a/mozilla_docs.txt b/mozilla_docs.txt new file mode 100644 index 00000000..ab6f2a65 --- /dev/null +++ b/mozilla_docs.txt @@ -0,0 +1,44 @@ + +The definitions of some interfaces implemented in jsapi/api/js_url.cpp are released under Mozilla license. + +The definitions and functions of these interfaces are consistent with the standard interfaces under mozila license, +but the implementation of specific functions is independent and self-developed. + +All interfaces are described in d.ts, the following is the interface written in d.ts under to Mozilla license + +class URLSearchParams { + + constructor(init?: string[][] | Record | string | URLSearchParams); + append(name: string, value: string): void; + delete(name: string): void; + getAll(name: string): string[]; + entries(): IterableIterator<[string, string]>; + forEach(callbackfn: (value: string, key: string, searchParams: this) => void): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + toString(): string; +} + +class URL { + + constructor(url: string, base?: string | URL); + toString(): string; + toJSON(): string; + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; +} \ No newline at end of file -- Gitee