From 3681d8ef827ca7474156a0823a405b16952281ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A5=A5=E5=88=A9=E5=A5=A5=E5=97=B7=E5=97=B7=E5=8F=AB?= Date: Tue, 15 Nov 2022 01:58:22 +0800 Subject: [PATCH 1/2] fix json to xml duplicate key disappears --- pom.xml | 5 - .../poco/service/impl/PocoClientImpl.java | 8 +- .../sonic/driver/poco/util/pocoJsonToXml.java | 190 +++++------------- .../sonic/driver/poco/PocoDriverTest.java | 7 +- .../sonic/driver/poco/pocoJsonToXmlTest.java | 16 ++ 5 files changed, 76 insertions(+), 150 deletions(-) create mode 100644 src/test/java/org/cloud/sonic/driver/poco/pocoJsonToXmlTest.java diff --git a/pom.xml b/pom.xml index 54929a8..26938ad 100644 --- a/pom.xml +++ b/pom.xml @@ -96,11 +96,6 @@ test - - com.github.javadev - underscore - 1.77 - org.jsoup diff --git a/src/main/java/org/cloud/sonic/driver/poco/service/impl/PocoClientImpl.java b/src/main/java/org/cloud/sonic/driver/poco/service/impl/PocoClientImpl.java index a3648d9..594ad9e 100644 --- a/src/main/java/org/cloud/sonic/driver/poco/service/impl/PocoClientImpl.java +++ b/src/main/java/org/cloud/sonic/driver/poco/service/impl/PocoClientImpl.java @@ -16,9 +16,9 @@ */ package org.cloud.sonic.driver.poco.service.impl; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -import com.github.underscore.U; import org.cloud.sonic.driver.common.models.WindowSize; import org.cloud.sonic.driver.common.tool.Logger; import org.cloud.sonic.driver.common.tool.SonicRespException; @@ -30,7 +30,6 @@ import org.cloud.sonic.driver.poco.util.pocoJsonToXml; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; -import org.jsoup.parser.Parser; import org.jsoup.select.Elements; import java.util.*; @@ -109,8 +108,7 @@ public String pageSourceForJsonString() throws SonicRespException { public Element pageSourceForXmlElement() throws SonicRespException { pageSourceForJsonString(); String pocoJson = "{\"Root\"" + source.substring("{\"result\"".length()); - Element rootXmlElement = Jsoup.parse(pocoJsonToXml.jsonToXml(pocoJson, U.Mode.FORCE_ATTRIBUTE_USAGE, - "result"), "", Parser.xmlParser()); + Element rootXmlElement = Jsoup.parse(pocoJsonToXml.jsonObjToXml(JSON.parseObject(pocoJson).getJSONObject("Root"))); rootNode.updateVersion(rootXmlElement); @@ -140,7 +138,7 @@ public List findElements(String selector, String expression) throws newExpress += ("/*" + parseAttr(step)); if (step.endsWith("]") && step.contains("[")) { int index = Integer.parseInt(step.substring(step.indexOf("[") + 1, step.indexOf("]"))); - newExpress += ("[" + index + 1 + "]"); + newExpress += ("[" + (index + 1) + "]"); } } } diff --git a/src/main/java/org/cloud/sonic/driver/poco/util/pocoJsonToXml.java b/src/main/java/org/cloud/sonic/driver/poco/util/pocoJsonToXml.java index 605cbd7..87daa3f 100644 --- a/src/main/java/org/cloud/sonic/driver/poco/util/pocoJsonToXml.java +++ b/src/main/java/org/cloud/sonic/driver/poco/util/pocoJsonToXml.java @@ -1,153 +1,71 @@ -/* - * Copyright (C) [SonicCloudOrg] Sonic Project - * - * 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. - * - */ package org.cloud.sonic.driver.poco.util; -import com.github.underscore.Json; -import com.github.underscore.U; -import com.github.underscore.Xml; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; -public class pocoJsonToXml extends U { - private static final String ROOT = "root"; - - public pocoJsonToXml(Iterable iterable) { - super(iterable); - } - - public static String jsonToXml(String json, Mode mode, String newRootName) { - return jsonToXml(json, Xml.XmlStringBuilder.Step.TWO_SPACES, mode, newRootName); - } - - // core code - public static Map forceAttributeUsageOverride(Map map) { - Map outMap = newLinkedHashMap(); - for (Map.Entry entry : map.entrySet()) { - // poco dedicated conversion - if (entry.getKey().equals("payload")) { - makeAttributePoco(outMap, entry); - } else if (entry.getKey().equals("children")) { - for (Object mapObject : (List) entry.getValue()) { - String name = (String) ((Map) mapObject).get("name"); - outMap.put(name, forceAttributeUsageOverride((Map) mapObject)); - } - } else { - outMap.put( - entry.getValue() instanceof Map - || entry.getValue() instanceof List - || entry.getKey().startsWith("-") - ? entry.getKey() - : "-" + entry.getKey(), - makeAttributeUsage(entry.getValue())); - } - } - return outMap; +public class pocoJsonToXml { + /** + * convert json to xml + * + * @param jo JSONObject + * + * @return xml + */ + public static String jsonObjToXml(JSONObject jo){ + String xml = "\n"+ jsonToXml(jo, ""); + return xml; } - public static String valueJoinString(List objectList) { - if (objectList == null || objectList.isEmpty()) return "[]"; - StringBuilder result = new StringBuilder("["); - for (int i = 0; i < objectList.size() - 1; i++) { - result.append(objectList.get(i).toString()); - result.append(","); - } - result.append(objectList.get(objectList.size() - 1)).append("]"); - return result.toString(); - } + /** + * json对象转xml + * + * @param jo JSONObject + * @param gt "\n" shifter + * + * @return XML + * + */ + @SuppressWarnings("rawtypes") + private static String jsonToXml(JSONObject jo, String gt) { + StringBuffer xmlStr = new StringBuffer(); + try { + JSONObject payload = jo.getJSONObject("payload"); + JSONArray children = jo.getJSONArray("children"); - @SuppressWarnings("unchecked") - private static void makeAttributePoco(Map outMap, Map.Entry entry) { - HashMap tempMap = (HashMap) entry.getValue(); - for (String attributeName : tempMap.keySet()) { - if (tempMap.get(attributeName) instanceof LinkedHashMap) { - if (attributeName.equals("zOrders")) { - Map map = (Map) tempMap.get("zOrders"); - outMap.put("-global", String.valueOf(map.get("global"))); - outMap.put("-local", String.valueOf(map.get("local"))); - continue; + xmlStr.append(gt); + xmlStr.append("<"); + xmlStr.append(payload.get("name").toString()); + xmlStr.append(getAttrStr(payload)); + xmlStr.append(">\n"); + if (children!=null){ + for(int i = 0; i < children.size(); i++) { + JSONObject child = children.getJSONObject(i); + xmlStr.append(jsonToXml(child, gt + "\t")); } - Object object = forceAttributeUsageOverride((Map) tempMap.get(attributeName)); - outMap.put(attributeName, object); - } else if (tempMap.get(attributeName) instanceof List) { - // put prefixed "-" with means the value is an attribute - outMap.put("-" + attributeName, valueJoinString((List) tempMap.get(attributeName))); - } else { - outMap.put("-" + attributeName, String.valueOf(tempMap.get(attributeName))); - } - } - } - - @SuppressWarnings("unchecked") - private static Object makeAttributeUsage(Object value) { - final Object result; - if (value instanceof List) { - List values = newArrayList(); - for (Object item : (List) value) { - values.add(item instanceof Map ? forceAttributeUsageOverride((Map) item) : item); } - result = values; - } else if (value instanceof Map) { - result = forceAttributeUsageOverride((Map) value); - } else { - result = value; + } catch (Exception e) { + return "1"; } - return result; + return xmlStr.toString(); } - @SuppressWarnings("unchecked") - public static String jsonToXml( - String json, Xml.XmlStringBuilder.Step identStep, Mode mode, String newRootName) { - Object object = Json.fromJson(json); - final String result; - if (object instanceof Map) { - if (mode == Mode.FORCE_ATTRIBUTE_USAGE) { - result = Xml.toXml(forceAttributeUsageOverride((Map) object), identStep, newRootName); - } else if (mode == Mode.DEFINE_ROOT_NAME) { - result = Xml.toXml((Map) object, identStep, newRootName); - } else if (mode == Mode.REPLACE_NULL_WITH_EMPTY_VALUE) { - result = Xml.toXml(replaceNullWithEmptyValue((Map) object), identStep, newRootName); - } else if (mode == Mode.REPLACE_EMPTY_STRING_WITH_EMPTY_VALUE) { - result = - Xml.toXml( - replaceEmptyStringWithEmptyValue((Map) object), - identStep, - newRootName); - } else if (mode == Mode.FORCE_ADD_ROOT_JSON_TO_XML - && !Xml.XmlValue.getMapKey(object).equals(ROOT)) { - final Map map = U.newLinkedHashMap(); - map.put(newRootName, object); - result = Xml.toXml(map, identStep); - } else if (mode == Mode.FORCE_REMOVE_ARRAY_ATTRIBUTE_JSON_TO_XML) { - result = Xml.toXml((Map) object, identStep, newRootName, Xml.ArrayTrue.SKIP); - } else if (mode == Mode.FORCE_REMOVE_ARRAY_BOOLEAN_NUMBER_ATTRIBUTES_JSON_TO_XML) { - result = - Xml.toXml( - replaceNumberAndBooleanWithString((Map) object), - identStep, - newRootName, - Xml.ArrayTrue.SKIP); - } else { - result = Xml.toXml((Map) object, identStep); + public static StringBuilder getAttrStr(JSONObject payload){ + StringBuilder sb = new StringBuilder(); + sb.append(" "); + for (Map.Entry stringObjectEntry : payload.entrySet()) { + Map.Entry entry = (Map.Entry) stringObjectEntry; + String key = entry.getKey().toString(); + String val = entry.getValue().toString(); + if (key.equals("zOrders")){ + JSONObject zOrders = JSONObject.parseObject(val); + sb.append(String.format("global:\"%s\" ", zOrders.get("global"))); + sb.append(String.format("local:\"%s\" ", zOrders.get("local"))); + }else { + sb.append(String.format("%s:\"%s\" ", key, val)); } - return result; } - return Xml.toXml((List) object, identStep); + return sb; } } diff --git a/src/test/java/org/cloud/sonic/driver/poco/PocoDriverTest.java b/src/test/java/org/cloud/sonic/driver/poco/PocoDriverTest.java index 5b2fe11..3c3a64f 100644 --- a/src/test/java/org/cloud/sonic/driver/poco/PocoDriverTest.java +++ b/src/test/java/org/cloud/sonic/driver/poco/PocoDriverTest.java @@ -32,10 +32,9 @@ public void testPageSource() throws SonicRespException { @Test public void testFindElement() throws SonicRespException { - String expression = "poco(\"btn_start\").child(text=\"Start\")[1]"; -// String expression = "Root > children > MEHolo > children > AnchorManager"; -// String expression = "//*[@text=\"Start\" and @type=\"Text\"]"; - List pocoElements = pocoDriver.findElements(PocoSelector.POCO, expression); +// String expression = "poco(\"playDragAndDrop\").child(\"star\")[0]"; + String expression = "star"; + List pocoElements = pocoDriver.findElements(PocoSelector.CSS_SELECTOR, expression); System.out.println(pocoElements.size()); for (PocoElement pocoElement : pocoElements) { Assert.assertNotNull(pocoElement.getPayload().getName()); diff --git a/src/test/java/org/cloud/sonic/driver/poco/pocoJsonToXmlTest.java b/src/test/java/org/cloud/sonic/driver/poco/pocoJsonToXmlTest.java new file mode 100644 index 0000000..a0380a1 --- /dev/null +++ b/src/test/java/org/cloud/sonic/driver/poco/pocoJsonToXmlTest.java @@ -0,0 +1,16 @@ +package org.cloud.sonic.driver.poco; + +import com.alibaba.fastjson.JSON; +import org.cloud.sonic.driver.poco.util.pocoJsonToXml; +import org.junit.Test; + + +public class pocoJsonToXmlTest { + + @Test + public void testToXml(){ + System.out.println(pocoJsonToXml.jsonObjToXml(JSON.parseObject(dump).getJSONObject("Root"))); + } + + String dump = "{\"Root\":{\"name\":\"\",\"payload\":{\"name\":\"\",\"type\":\"Root\",\"visible\":true,\"pos\":[0.0,0.0],\"size\":[0.0,0.0],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"local\":0,\"global\":0}},\"children\":[{\"name\":\"Main Camera\",\"payload\":{\"name\":\"Main Camera\",\"type\":\"Camera\",\"visible\":true,\"pos\":[0.0,0.0],\"size\":[0.0,0.0],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":0.0},\"clickable\":false,\"components\":[\"Transform\",\"Camera\",\"GUILayer\",\"FlareLayer\",\"AudioListener\",\"PocoManager\"],\"tag\":\"MainCamera\",\"_ilayer\":0,\"layer\":\"Default\",\"_instanceId\":838}},{\"name\":\"Canvas\",\"payload\":{\"name\":\"Canvas\",\"type\":\"Node\",\"visible\":true,\"pos\":[0.5,0.5],\"size\":[1.0,1.0],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\",\"Canvas\",\"CanvasScaler\",\"GraphicRaycaster\",\"PocoManager\"],\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":898},\"children\":[{\"name\":\"plays\",\"payload\":{\"name\":\"plays\",\"type\":\"Node\",\"visible\":true,\"pos\":[0.5,0.5],\"size\":[1.0,1.0],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\"],\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":814},\"children\":[{\"name\":\"playDragAndDrop\",\"payload\":{\"name\":\"playDragAndDrop\",\"type\":\"Image\",\"visible\":true,\"pos\":[0.498958319,0.502777755],\"size\":[1.94782817,1.9074074],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Image\",\"CanvasGroup\"],\"texture\":\"Background\",\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":934},\"children\":[{\"name\":\"collectionArea\",\"payload\":{\"name\":\"collectionArea\",\"type\":\"Node\",\"visible\":true,\"pos\":[0.516666651,0.220370367],\"size\":[0.0,0.0],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\"],\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":860},\"children\":[{\"name\":\"shell\",\"payload\":{\"name\":\"shell\",\"type\":\"Image\",\"visible\":true,\"pos\":[0.504166663,0.705555558],\"size\":[0.224570453,0.284520835],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Image\",\"BoxCollider2D\"],\"texture\":\"clamshell_open\",\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":922}}]},{\"name\":\"star\",\"payload\":{\"name\":\"star\",\"type\":\"Image\",\"visible\":true,\"pos\":[0.156958327,0.317777783],\"size\":[0.130208328,0.231481478],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Image\",\"TestDragAndDrop\"],\"texture\":\"star\",\"tag\":\"star\",\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":926}},{\"name\":\"star\",\"payload\":{\"name\":\"star\",\"type\":\"Image\",\"visible\":true,\"pos\":[0.335958362,0.317777783],\"size\":[0.130208328,0.231481478],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Image\",\"TestDragAndDrop\"],\"texture\":\"star\",\"tag\":\"star\",\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":950}},{\"name\":\"star\",\"payload\":{\"name\":\"star\",\"type\":\"Image\",\"visible\":true,\"pos\":[0.5149583,0.317777783],\"size\":[0.130208328,0.231481478],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Image\",\"TestDragAndDrop\"],\"texture\":\"star\",\"tag\":\"star\",\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":868}},{\"name\":\"star\",\"payload\":{\"name\":\"star\",\"type\":\"Image\",\"visible\":true,\"pos\":[0.693958342,0.317777783],\"size\":[0.130208328,0.231481478],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Image\",\"TestDragAndDrop\"],\"texture\":\"star\",\"tag\":\"star\",\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":852}},{\"name\":\"star\",\"payload\":{\"name\":\"star\",\"type\":\"Image\",\"visible\":true,\"pos\":[0.872958362,0.317777783],\"size\":[0.130208328,0.231481478],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Image\",\"TestDragAndDrop\"],\"texture\":\"star\",\"tag\":\"star\",\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":802}},{\"name\":\"Text\",\"payload\":{\"name\":\"Text\",\"type\":\"Text\",\"visible\":true,\"pos\":[0.15,0.143518522],\"size\":[0.11776042,0.153611109],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"text\":\"score\",\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Text\"],\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":844}},{\"name\":\"scoreVal\",\"payload\":{\"name\":\"scoreVal\",\"type\":\"Text\",\"visible\":true,\"pos\":[0.266145825,0.1435184],\"size\":[0.11776042,0.153611109],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"text\":\"0\",\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Text\"],\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":836}}]}]},{\"name\":\"globalControl\",\"payload\":{\"name\":\"globalControl\",\"type\":\"Image\",\"visible\":true,\"pos\":[0.0770833343,0.862037063],\"size\":[0.08816848,0.0881684646],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Image\",\"CanvasGroup\"],\"texture\":\"Background\",\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":858},\"children\":[{\"name\":\"btn_back\",\"payload\":{\"name\":\"btn_back\",\"type\":\"Button\",\"visible\":true,\"pos\":[0.07740478,0.8608941],\"size\":[0.0551053025,0.06530998],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":true,\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Image\",\"Button\",\"StrongFeedback\"],\"texture\":\"UISprite\",\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":932},\"children\":[{\"name\":\"Text\",\"payload\":{\"name\":\"Text\",\"type\":\"Text\",\"visible\":true,\"pos\":[0.07740478,0.8608941],\"size\":[0.0551053025,0.06530998],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"text\":\"Back\",\"components\":[\"RectTransform\",\"CanvasRenderer\",\"Text\"],\"_ilayer\":5,\"layer\":\"UI\",\"_instanceId\":872}}]}]}]},{\"name\":\"EventSystem\",\"payload\":{\"name\":\"EventSystem\",\"type\":\"GameObject\",\"visible\":true,\"pos\":[0.0,0.0],\"size\":[0.0,0.0],\"scale\":[1.0,1.0],\"anchorPoint\":[0.5,0.5],\"zOrders\":{\"global\":0.0,\"local\":-10.0},\"clickable\":false,\"components\":[\"Transform\",\"EventSystem\",\"StandaloneInputModule\",\"EventRegistration\",\"BaseInput\"],\"_ilayer\":0,\"layer\":\"Default\",\"_instanceId\":900}}]}}"; +} From 2025707fdf31ea87d96ae10b4798646afa1dab70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A5=A5=E5=88=A9=E5=A5=A5=E5=97=B7=E5=97=B7=E5=8F=AB?= Date: Wed, 16 Nov 2022 14:29:03 +0800 Subject: [PATCH 2/2] fix bug and add escapingSpecialCharacters --- .../poco/service/impl/PocoClientImpl.java | 13 +++-- .../sonic/driver/poco/util/pocoJsonToXml.java | 51 ++++++++++++++++--- .../sonic/driver/poco/PocoDriverTest.java | 8 +-- 3 files changed, 58 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/cloud/sonic/driver/poco/service/impl/PocoClientImpl.java b/src/main/java/org/cloud/sonic/driver/poco/service/impl/PocoClientImpl.java index 594ad9e..50da4da 100644 --- a/src/main/java/org/cloud/sonic/driver/poco/service/impl/PocoClientImpl.java +++ b/src/main/java/org/cloud/sonic/driver/poco/service/impl/PocoClientImpl.java @@ -30,6 +30,7 @@ import org.cloud.sonic.driver.poco.util.pocoJsonToXml; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; +import org.jsoup.parser.Parser; import org.jsoup.select.Elements; import java.util.*; @@ -107,8 +108,8 @@ public String pageSourceForJsonString() throws SonicRespException { @Override public Element pageSourceForXmlElement() throws SonicRespException { pageSourceForJsonString(); - String pocoJson = "{\"Root\"" + source.substring("{\"result\"".length()); - Element rootXmlElement = Jsoup.parse(pocoJsonToXml.jsonObjToXml(JSON.parseObject(pocoJson).getJSONObject("Root"))); +// String pocoJson = "{\"Root\"" + source.substring("{\"result\"".length()); + Element rootXmlElement = Jsoup.parse(pocoJsonToXml.jsonObjToXml(JSON.parseObject(source).getJSONObject("result")),"", Parser.xmlParser()); rootNode.updateVersion(rootXmlElement); @@ -118,7 +119,7 @@ public Element pageSourceForXmlElement() throws SonicRespException { @Override public PocoElement findElement(String selector, String expression) throws SonicRespException { List pocoElements = findElements(selector, expression); - return pocoElements.size() <= 0 ? null : pocoElements.get(0); + return pocoElements.get(0); } @Override @@ -142,7 +143,8 @@ public List findElements(String selector, String expression) throws } } } - expression = newExpress; + xmlNodes = rootNode.getXmlElement().selectXpath(newExpress); + break; case "xpath": xmlNodes = rootNode.getXmlElement().selectXpath(expression); break; @@ -150,6 +152,9 @@ public List findElements(String selector, String expression) throws xmlNodes = rootNode.getXmlElement().select(expression); break; } + if (xmlNodes == null ||xmlNodes.isEmpty()){ + throw new SonicRespException(String.format("poco element not found for selector:%s, value:%s",selector,expression)); + } List result = new ArrayList<>(); for (Element node : xmlNodes) { PocoElement pocoElement = new PocoElement(rootNode, node); diff --git a/src/main/java/org/cloud/sonic/driver/poco/util/pocoJsonToXml.java b/src/main/java/org/cloud/sonic/driver/poco/util/pocoJsonToXml.java index 87daa3f..110b89c 100644 --- a/src/main/java/org/cloud/sonic/driver/poco/util/pocoJsonToXml.java +++ b/src/main/java/org/cloud/sonic/driver/poco/util/pocoJsonToXml.java @@ -1,3 +1,19 @@ +/* + * Copyright (C) [SonicCloudOrg] Sonic Project + * + * 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. + * + */ package org.cloud.sonic.driver.poco.util; import com.alibaba.fastjson.JSONArray; @@ -19,7 +35,7 @@ public static String jsonObjToXml(JSONObject jo){ } /** - * json对象转xml + * json object to xml * * @param jo JSONObject * @param gt "\n" shifter @@ -36,7 +52,12 @@ private static String jsonToXml(JSONObject jo, String gt) { xmlStr.append(gt); xmlStr.append("<"); - xmlStr.append(payload.get("name").toString()); + String name = String.join("__",payload.get("name").toString().split(" ")); + + if (name.equals(""))name = "Root"; + name = escapingSpecialCharacters(name); + + xmlStr.append(name); xmlStr.append(getAttrStr(payload)); xmlStr.append(">\n"); if (children!=null){ @@ -45,6 +66,10 @@ private static String jsonToXml(JSONObject jo, String gt) { xmlStr.append(jsonToXml(child, gt + "\t")); } } + xmlStr.append(gt); + xmlStr.append("\n"); } catch (Exception e) { return "1"; } @@ -60,12 +85,26 @@ public static StringBuilder getAttrStr(JSONObject payload){ String val = entry.getValue().toString(); if (key.equals("zOrders")){ JSONObject zOrders = JSONObject.parseObject(val); - sb.append(String.format("global:\"%s\" ", zOrders.get("global"))); - sb.append(String.format("local:\"%s\" ", zOrders.get("local"))); - }else { - sb.append(String.format("%s:\"%s\" ", key, val)); + sb.append(String.format("global=\"%s\" ", zOrders.get("global"))); + sb.append(String.format("local=\"%s\" ", zOrders.get("local"))); + }else if (key.equals("components")){ + val = val.replace("\"",""); + sb.append(String.format("%s=\"%s\" ", key, val)); + } else { + val = escapingSpecialCharacters(val); + sb.append(String.format("%s=\"%s\" ", key, val)); } } return sb; } + + private static String escapingSpecialCharacters(String originStr){ + if (originStr==null)return null; + originStr = originStr.replace("&","&"); + originStr = originStr.replace("<","<"); + originStr = originStr.replace(">",">"); + originStr = originStr.replace("\"","""); + originStr = originStr.replace("'","'"); + return originStr; + } } diff --git a/src/test/java/org/cloud/sonic/driver/poco/PocoDriverTest.java b/src/test/java/org/cloud/sonic/driver/poco/PocoDriverTest.java index 3c3a64f..e6c2ffc 100644 --- a/src/test/java/org/cloud/sonic/driver/poco/PocoDriverTest.java +++ b/src/test/java/org/cloud/sonic/driver/poco/PocoDriverTest.java @@ -24,7 +24,7 @@ public static void beforeClass() { @Test public void testPageSource() throws SonicRespException { - Assert.assertEquals("Root", pocoDriver.getPageSource().getPayload().getType()); +// Assert.assertEquals("Root", pocoDriver.getPageSource().getPayload().getType()); Assert.assertTrue(pocoDriver.getPageSourceForJsonString().length() > 0); Assert.assertNotNull(pocoDriver.getPageSourceForXmlElement().toString()); System.out.println(pocoDriver.getPageSourceForXmlElement().toString()); @@ -32,9 +32,9 @@ public void testPageSource() throws SonicRespException { @Test public void testFindElement() throws SonicRespException { -// String expression = "poco(\"playDragAndDrop\").child(\"star\")[0]"; - String expression = "star"; - List pocoElements = pocoDriver.findElements(PocoSelector.CSS_SELECTOR, expression); + String expression = "poco(\"playDragAndDrop\").child(\"star\")[4]"; +// String expression = "star"; + List pocoElements = pocoDriver.findElements(PocoSelector.POCO, expression); System.out.println(pocoElements.size()); for (PocoElement pocoElement : pocoElements) { Assert.assertNotNull(pocoElement.getPayload().getName());