From d9172d1362f4355b409e82652c62dec8ed0b9878 Mon Sep 17 00:00:00 2001 From: rajihul Date: Fri, 22 Jan 2021 22:03:52 -0800 Subject: [PATCH 01/11] Added first toJSONObject(Reader reader, JSONPointer path) class. Also added test cases in XMLTest_SWE262 under tests folder. --- src/main/java/org/json/XML.java | 28 +++ .../java/org/json/junit/XMLTest_SWE262.java | 49 +++++ src/test/resources/file.xml | 169 ++++++++++++++++++ 3 files changed, 246 insertions(+) create mode 100644 src/test/java/org/json/junit/XMLTest_SWE262.java create mode 100644 src/test/resources/file.xml diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 805a5c376..befeacb6b 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -709,6 +709,34 @@ public static JSONObject toJSONObject(String string, XMLParserConfiguration conf return toJSONObject(new StringReader(string), config); } + //[RJ ADDED] Overloaded static method + public static JSONObject toJSONObject(Reader reader, JSONPointer path) + { + //System.out.println("instantiated Rahul method"); + JSONObject jo = new JSONObject(); + XMLParserConfiguration config = new XMLParserConfiguration(); + XMLTokener x = new XMLTokener(reader); + while (x.more()) { + x.skipPast("<"); + if(x.more()) { + parse(x, jo, null, XMLParserConfiguration.ORIGINAL); + //System.out.println(x.toString()); + } + } + + //System.out.println("PrintingJSON"); + + Object query = jo.query(path.toString()); + System.out.println(query); + return (JSONObject) query; + + //System.out.println(checkPath); + // return XML.toJSONObject(checkPath.toString()); + // System.out.println(checkPath); + //return jo;//(new JSONObject((jo.query(path.toString())))); + + } + /** * Convert a JSONObject into a well-formed, element-normal XML string. * diff --git a/src/test/java/org/json/junit/XMLTest_SWE262.java b/src/test/java/org/json/junit/XMLTest_SWE262.java new file mode 100644 index 000000000..e80ccc490 --- /dev/null +++ b/src/test/java/org/json/junit/XMLTest_SWE262.java @@ -0,0 +1,49 @@ +package org.json.junit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.*; +import java.util.HashMap; +import java.util.Map; + +import org.json.*; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +public class XMLTest_SWE262 { + /** + * JUnit supports temporary files and folders that are cleaned up after the test. + * https://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/ + */ + @Rule + public TemporaryFolder testFolder = new TemporaryFolder(); + + + /** + * Empty JSONObject from a non-XML string. + */ + @Test + public void testMethodOne() { + + System.out.println("Rahul Hello World"); + + try { + FileReader filereader = new FileReader("src/test/resources/file.xml"); + JSONObject jo = XML.toJSONObject(filereader, new JSONPointer("/clinical_study")); + + System.out.println(jo); + + } catch (FileNotFoundException e) { + System.out.println("File not found"); + e.printStackTrace(); + } + //String xmlStr = "{ \"this is\": \"not xml\"}"; + //JSONObject jsonObject = XML.toJSONObject(xmlStr); + //assertTrue("xml string should be empty", jsonObject.isEmpty()); + } +} diff --git a/src/test/resources/file.xml b/src/test/resources/file.xml new file mode 100644 index 000000000..29f02095c --- /dev/null +++ b/src/test/resources/file.xml @@ -0,0 +1,169 @@ + + + + + ClinicalTrials.gov processed this data on July 19, 2020 + Link to the current ClinicalTrials.gov record. + https://clinicaltrials.gov/show/NCT03874338 + + + 18-01323 + 1R01HL146206 + NCT03874338 + + CLEAR SYNERGY Neutrophil Substudy + Studies on the Effects of Colchicine on Neutrophil Biology in Acute Myocardial Infarction: A Substudy of the CLEAR SYNERGY (OASIS 9) Trial + + + NYU Langone Health + Other + + + Population Health Research Institute + Other + + + National Heart, Lung, and Blood Institute (NHLBI) + NIH + + + NYU Langone Health + + No + No + No + + + + CLEAR SYNERGY is an international multi center 2x2 randomized placebo controlled trial of + + + Recruiting + March 4, 2019 + February 1, 2022 + February 1, 2021 + Observational + No + + Other + Prospective + + + soluble L-selectin + between baseline and 3 months + Change in soluble L-selectin between baseline and 3 mo after STEMI in the placebo vs. colchicine groups. + + + Other soluble markers of neutrophil activity + between baseline and 3 months + Other markers of neutrophil activity will be evaluated at baseline and 3 months after STEMI (myeloperoxidase, matrix metalloproteinase-9, neutrophil gelatinase-associated lipocalin, neutrophil elastase, intercellular/vascular cellular adhesion molecules) + + + Markers of systemic inflammation + between baseline and 3 months + Markers of systemic inflammation will be evaluated at baseline and 3 months after STEMI (high sensitive CRP, IL-1β) + + + Neutrophil-driven responses that may further propagate injury + between baseline and 3 months + Neutrophil-driven responses that may further propagate injury will be evaluated at baseline and 3 months after STEMI (neutrophil extracellular traps, neutrophil-derived microparticles) + + 2 + 670 + Neutrophils.Hypersegmented ; Bld-Ser-Plas + STEMI - ST Elevation Myocardial Infarction + + Colchicine + + + Placebo + + + Drug + Colchicine Pill + Participants in the main CLEAR SYNERGY trial are randomized to colchicine/spironolactone versus placebo in a 2x2 factorial design. The substudy is interested in the evaluation of biospecimens obtained from patients in the colchicine vs placebo group. + Colchicine + Placebo + + + + + Patients who are randomized to the drug RCT portion of the CLEAR SYNERGY (OASIS 9) trial + + + Non-Probability Sample + + + Inclusion Criteria: + + + All + 19 Years + 110 Years + No + + + Binita Shah, MD + Principal Investigator + NYU School of Medicine + + + Fatmira Curovic + 646-501-9648 + fatmira.curovic@nyumc.org + + + Binita Shah, MD + + + + NYU School of Medicine +
+ New York + New York + 10016 + United States +
+
+ Recruiting + + Fatmira Curovic + 646-501-9648 + fatmira.curovic@nyumc.org + + + Binita Shah, MD + +
+ + United States + + September 2019 + March 12, 2019 + March 12, 2019 + March 14, 2019 + September 10, 2019 + September 10, 2019 + September 12, 2019 + + Principal Investigator + NYU Langone Health + Binita Shah + Assistant Professor of Medicine + + + + Myocardial Infarction + ST Elevation Myocardial Infarction + Infarction + + + + Colchicine + + + No + + +
From ffc1e32232d5a416b69df43b568f89b124aecc81 Mon Sep 17 00:00:00 2001 From: rajihul Date: Sat, 23 Jan 2021 23:13:30 -0800 Subject: [PATCH 02/11] Updated toJSONObject(Reader reader, JSONPointer path) method to be more efficient. --- src/main/java/org/json/XML.java | 101 +++++++++-- .../java/org/json/junit/XMLTest_SWE262.java | 2 +- src/test/resources/file.xml | 163 ++---------------- 3 files changed, 106 insertions(+), 160 deletions(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index befeacb6b..f9df4b6db 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -712,29 +712,108 @@ public static JSONObject toJSONObject(String string, XMLParserConfiguration conf //[RJ ADDED] Overloaded static method public static JSONObject toJSONObject(Reader reader, JSONPointer path) { - //System.out.println("instantiated Rahul method"); + //Need substring to take out first / so can use split successfully. + String[] pathArray = path.toString().substring(1).split("[\\\\/]", -1); + int pathSize = pathArray.length; + + JSONObject jo = new JSONObject(); XMLParserConfiguration config = new XMLParserConfiguration(); XMLTokener x = new XMLTokener(reader); + + //Find the last non-numerical tag in pathArray + int containsNumber = 0; //index of array where number is + for(int i = 0; i < pathSize; i ++) + { + if(pathArray[i].matches("-?\\d+(\\.\\d+)?")) + { + containsNumber = i; + } + } +System.out.println("Contains number: " + containsNumber); + String parseTag;// = (containsNumber == 0) ? pathArray[pathSize - 1] : pathArray[containsNumber - 1]; + if(containsNumber == 0) + { + parseTag = pathArray[pathSize -1]; + } + else + { + if(pathSize < 2) + { + parseTag = pathArray[0]; + } + else + { + parseTag = pathArray[containsNumber - 1]; + } + } + String remArr = ""; + + //Need to get the new string array that can use JSONPointer to solve + if(containsNumber != 0) + { + for(int z = containsNumber-1; z < pathSize; z ++) + remArr += "/" + pathArray[z]; + } + + System.out.println("remArr: " + remArr); + System.out.println("Parse Tag: " + parseTag); + + //rebuild the sub xml + String rebuildXML = ""; + boolean cycle = false; + + String currTag =""; + + String startString = "<" + parseTag + ">"; + String exitString = ""; + while (x.more()) { x.skipPast("<"); - if(x.more()) { - parse(x, jo, null, XMLParserConfiguration.ORIGINAL); - //System.out.println(x.toString()); + currTag = "<" + x.nextContent(); + //System.out.println(currTag); + + //Start recording after start string reached. + if(currTag.equalsIgnoreCase(startString)) + cycle = true; + + + if(cycle) + { + rebuildXML += currTag; + //System.out.println("Pre If: " + currTag); } + + //Start recording after start string reached. + if(currTag.equalsIgnoreCase(exitString)) + { + if(containsNumber != 0) + cycle = false; + else + break; + } + } + + System.out.println(rebuildXML); + JSONObject query = XML.toJSONObject(rebuildXML); + System.out.println(query.toString()); + + if(containsNumber != 0) + { + Object jsquery = query.query(remArr); + //System.out.println(jsquery); + query = (JSONObject) jsquery; } //System.out.println("PrintingJSON"); - Object query = jo.query(path.toString()); - System.out.println(query); - return (JSONObject) query; + return query; - //System.out.println(checkPath); - // return XML.toJSONObject(checkPath.toString()); - // System.out.println(checkPath); - //return jo;//(new JSONObject((jo.query(path.toString())))); + } + public static JSONObject toJSONObject(Reader reader, JSONPointer path, JSONObject replacement) + { + return null; } /** diff --git a/src/test/java/org/json/junit/XMLTest_SWE262.java b/src/test/java/org/json/junit/XMLTest_SWE262.java index e80ccc490..7d7fbce70 100644 --- a/src/test/java/org/json/junit/XMLTest_SWE262.java +++ b/src/test/java/org/json/junit/XMLTest_SWE262.java @@ -34,7 +34,7 @@ public void testMethodOne() { try { FileReader filereader = new FileReader("src/test/resources/file.xml"); - JSONObject jo = XML.toJSONObject(filereader, new JSONPointer("/clinical_study")); + JSONObject jo = XML.toJSONObject(filereader, new JSONPointer("/clinical_study/required_header/1")); System.out.println(jo); diff --git a/src/test/resources/file.xml b/src/test/resources/file.xml index 29f02095c..bb550d162 100644 --- a/src/test/resources/file.xml +++ b/src/test/resources/file.xml @@ -1,19 +1,24 @@ - - ClinicalTrials.gov processed this data on July 19, 2020 + 11ClinicalTrials.gov processed this data on July 19, 2020 + Link to the current ClinicalTrials.gov record. + https://clinicaltrials.gov/show/NCT03874338 + + + 22ClinicalTrials.gov processed this data on July 19, 2020 Link to the current ClinicalTrials.gov record. https://clinicaltrials.gov/show/NCT03874338 - - 18-01323 - 1R01HL146206 - NCT03874338 - - CLEAR SYNERGY Neutrophil Substudy - Studies on the Effects of Colchicine on Neutrophil Biology in Acute Myocardial Infarction: A Substudy of the CLEAR SYNERGY (OASIS 9) Trial + + ClinicalTrials.gov processed this data on July 19, 2020 + Link to the current ClinicalTrials.gov record. + https://clinicaltrials.gov/show/NCT03874338 + + ClinicalTrials.gov processed this data on July 19, 2020 + Link to the current ClinicalTrials.gov record. + https://clinicaltrials.gov/show/NCT03874338 + NYU Langone Health @@ -28,142 +33,4 @@ NIH - NYU Langone Health - - No - No - No - - - - CLEAR SYNERGY is an international multi center 2x2 randomized placebo controlled trial of - - - Recruiting - March 4, 2019 - February 1, 2022 - February 1, 2021 - Observational - No - - Other - Prospective - - - soluble L-selectin - between baseline and 3 months - Change in soluble L-selectin between baseline and 3 mo after STEMI in the placebo vs. colchicine groups. - - - Other soluble markers of neutrophil activity - between baseline and 3 months - Other markers of neutrophil activity will be evaluated at baseline and 3 months after STEMI (myeloperoxidase, matrix metalloproteinase-9, neutrophil gelatinase-associated lipocalin, neutrophil elastase, intercellular/vascular cellular adhesion molecules) - - - Markers of systemic inflammation - between baseline and 3 months - Markers of systemic inflammation will be evaluated at baseline and 3 months after STEMI (high sensitive CRP, IL-1β) - - - Neutrophil-driven responses that may further propagate injury - between baseline and 3 months - Neutrophil-driven responses that may further propagate injury will be evaluated at baseline and 3 months after STEMI (neutrophil extracellular traps, neutrophil-derived microparticles) - - 2 - 670 - Neutrophils.Hypersegmented ; Bld-Ser-Plas - STEMI - ST Elevation Myocardial Infarction - - Colchicine - - - Placebo - - - Drug - Colchicine Pill - Participants in the main CLEAR SYNERGY trial are randomized to colchicine/spironolactone versus placebo in a 2x2 factorial design. The substudy is interested in the evaluation of biospecimens obtained from patients in the colchicine vs placebo group. - Colchicine - Placebo - - - - - Patients who are randomized to the drug RCT portion of the CLEAR SYNERGY (OASIS 9) trial - - - Non-Probability Sample - - - Inclusion Criteria: - - - All - 19 Years - 110 Years - No - - - Binita Shah, MD - Principal Investigator - NYU School of Medicine - - - Fatmira Curovic - 646-501-9648 - fatmira.curovic@nyumc.org - - - Binita Shah, MD - - - - NYU School of Medicine -
- New York - New York - 10016 - United States -
-
- Recruiting - - Fatmira Curovic - 646-501-9648 - fatmira.curovic@nyumc.org - - - Binita Shah, MD - -
- - United States - - September 2019 - March 12, 2019 - March 12, 2019 - March 14, 2019 - September 10, 2019 - September 10, 2019 - September 12, 2019 - - Principal Investigator - NYU Langone Health - Binita Shah - Assistant Professor of Medicine - - - - Myocardial Infarction - ST Elevation Myocardial Infarction - Infarction - - - - Colchicine - - - No - -
From 95fcdb24f17491c5f6b9420efd14c701d5878599 Mon Sep 17 00:00:00 2001 From: rahul Date: Sun, 24 Jan 2021 18:17:23 -0800 Subject: [PATCH 03/11] Added another overloaded static method to XML class: static JSONObject toJSONObject(Reader reader, JSONPointer path, JSONObject replacement) Added testMethodTwo() in XMLTest_SWE262 test. Added Catalog.xml for testing purposes. Updated methods to handle tag attributes. --- src/main/java/org/json/XML.java | 135 +++++++++++++++++- .../java/org/json/junit/XMLTest_SWE262.java | 22 +++ src/test/resources/Catalog.xml | 120 ++++++++++++++++ 3 files changed, 271 insertions(+), 6 deletions(-) create mode 100644 src/test/resources/Catalog.xml diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index f9df4b6db..f0233dfd3 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -730,7 +730,9 @@ public static JSONObject toJSONObject(Reader reader, JSONPointer path) containsNumber = i; } } -System.out.println("Contains number: " + containsNumber); + + System.out.println("Contains number: " + containsNumber); + String parseTag;// = (containsNumber == 0) ? pathArray[pathSize - 1] : pathArray[containsNumber - 1]; if(containsNumber == 0) { @@ -765,8 +767,8 @@ public static JSONObject toJSONObject(Reader reader, JSONPointer path) String currTag =""; - String startString = "<" + parseTag + ">"; - String exitString = ""; + String startString = "<" + parseTag; + String exitString = "rahul jain")); + + System.out.println(jo); + + System.out.println("Testing out JSON to XML Conversion"); + + System.out.println(XML.toString(jo)); + + } catch (FileNotFoundException e) { + System.out.println("File not found"); + e.printStackTrace(); + } + + } } diff --git a/src/test/resources/Catalog.xml b/src/test/resources/Catalog.xml new file mode 100644 index 000000000..06889bd6c --- /dev/null +++ b/src/test/resources/Catalog.xml @@ -0,0 +1,120 @@ + + + + Gambardella, Matthew + XML Developer's Guide + Computer + 44.95 + 2000-10-01 + An in-depth look at creating applications + with XML. + + + Ralls, Kim + Midnight Rain + Fantasy + 5.95 + 2000-12-16 + A former architect battles corporate zombies, + an evil sorceress, and her own childhood to become queen + of the world. + + + Corets, Eva + Maeve Ascendant + Fantasy + 5.95 + 2000-11-17 + After the collapse of a nanotechnology + society in England, the young survivors lay the + foundation for a new society. + + + Corets, Eva + Oberon's Legacy + Fantasy + 5.95 + 2001-03-10 + In post-apocalypse England, the mysterious + agent known only as Oberon helps to create a new life + for the inhabitants of London. Sequel to Maeve + Ascendant. + + + Corets, Eva + The Sundered Grail + Fantasy + 5.95 + 2001-09-10 + The two daughters of Maeve, half-sisters, + battle one another for control of England. Sequel to + Oberon's Legacy. + + + Randall, Cynthia + Lover Birds + Romance + 4.95 + 2000-09-02 + When Carla meets Paul at an ornithology + conference, tempers fly as feathers get ruffled. + + + Thurman, Paula + Splish Splash + Romance + 4.95 + 2000-11-02 + A deep sea diver finds true love twenty + thousand leagues beneath the sea. + + + Knorr, Stefan + Creepy Crawlies + Horror + 4.95 + 2000-12-06 + An anthology of horror stories about roaches, + centipedes, scorpions and other insects. + + + Kress, Peter + Paradox Lost + Science Fiction + 6.95 + 2000-11-02 + After an inadvertant trip through a Heisenberg + Uncertainty Device, James Salway discovers the problems + of being quantum. + + + O'Brien, Tim + Microsoft .NET: The Programming Bible + Computer + 36.95 + 2000-12-09 + Microsoft's .NET initiative is explored in + detail in this deep programmer's reference. + + + O'Brien, Tim + MSXML3: A Comprehensive Guide + Computer + 36.95 + 2000-12-01 + The Microsoft MSXML3 parser is covered in + detail, with attention to XML DOM interfaces, XSLT processing, + SAX and more. + + + Galos, Mike + Visual Studio 7: A Comprehensive Guide + Computer + 49.95 + 2001-04-16 + Microsoft Visual Studio 7 is explored in depth, + looking at how Visual Basic, Visual C++, C#, and ASP+ are + integrated into a comprehensive development + environment. + + \ No newline at end of file From 75582f22e74359072974e2c06613212a5a046227 Mon Sep 17 00:00:00 2001 From: rahul Date: Tue, 26 Jan 2021 14:50:00 -0800 Subject: [PATCH 04/11] Updated XMLTest_SWE262 with additional unit tests. --- src/main/java/org/json/XML.java | 42 +++++++-- .../java/org/json/junit/XMLTest_SWE262.java | 88 ++++++++++++++++--- src/test/resources/Catalog.xml | 4 +- src/test/resources/file.xml | 2 +- 4 files changed, 113 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index f0233dfd3..21a85938e 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -765,6 +765,8 @@ public static JSONObject toJSONObject(Reader reader, JSONPointer path) String rebuildXML = ""; boolean cycle = false; + boolean exitLoop = false; + String currTag =""; String startString = "<" + parseTag; @@ -776,12 +778,18 @@ public static JSONObject toJSONObject(Reader reader, JSONPointer path) //System.out.println(currTag); //Start recording after start string reached. - if(currTag.contains(startString)) + if(currTag.contains(startString)) { cycle = true; - + //Needed in case XML has array structure + //e.g. ...... + exitLoop = false; //Needed incase JSON has array structure. + } if(cycle) { + if(exitLoop) + break; + rebuildXML += currTag; //System.out.println("Pre If: " + currTag); } @@ -789,22 +797,28 @@ public static JSONObject toJSONObject(Reader reader, JSONPointer path) //Start recording after start string reached. if(currTag.contains(exitString)) { + exitLoop = true; if(containsNumber != 0) cycle = false; else - break; + cycle = true; } } - System.out.println(rebuildXML); + //System.out.println(rebuildXML); JSONObject query = XML.toJSONObject(rebuildXML); - System.out.println(query.toString()); + //System.out.println(query.toString()); if(containsNumber != 0) { Object jsquery = query.query(remArr); //System.out.println(jsquery); - query = (JSONObject) jsquery; + if(jsquery instanceof String) + query = new JSONObject().put(pathArray[pathSize - 1], jsquery); + else if(jsquery instanceof BigDecimal) + query = new JSONObject().put(pathArray[pathSize - 1], jsquery.toString()); + else + query = (JSONObject) jsquery; } //System.out.println("PrintingJSON"); @@ -820,6 +834,11 @@ public static JSONObject toJSONObject(Reader reader, JSONPointer path, JSONObjec //Concert the replacement to a JSONObject //Merge the tw + if(path.toString().equals("/")) + { + return XML.toJSONObject(XML.toString(replacement)); + } + //Need substring to take out first / so can use split successfully. String[] pathArray = path.toString().substring(1).split("[\\\\/]", -1); int pathSize = pathArray.length; @@ -876,12 +895,17 @@ public static JSONObject toJSONObject(Reader reader, JSONPointer path, JSONObjec //boolean replacementPast = false; boolean firstPass = false; - + boolean replaceEverything = false; String currTag =""; String startString = "<" + parseTag; String exitString = "" + replacementXML + exitString + ">"; + break; + } //Stop recording after start string reached. if(currTag.contains(startString)) cycle = false; diff --git a/src/test/java/org/json/junit/XMLTest_SWE262.java b/src/test/java/org/json/junit/XMLTest_SWE262.java index 5debdf15d..b9ea16182 100644 --- a/src/test/java/org/json/junit/XMLTest_SWE262.java +++ b/src/test/java/org/json/junit/XMLTest_SWE262.java @@ -28,44 +28,108 @@ public class XMLTest_SWE262 { * Empty JSONObject from a non-XML string. */ @Test - public void testMethodOne() { + public void testMethodOne_singleValue() { System.out.println("Rahul Hello World"); + String expectedStr = + "{\"author\":\"Gambardella, Matthew\"}"; + String actualStr = ""; + + try { + FileReader filereader = new FileReader("src/test/resources/Catalog.xml"); + JSONObject jo = XML.toJSONObject(filereader, new JSONPointer("/catalog/book/0/author")); + + actualStr = jo.toString(); + + System.out.println("Actual: " + actualStr); + System.out.println("Expected: " + expectedStr); + assertEquals(expectedStr, actualStr); + + } catch (FileNotFoundException e) { + System.out.println("File not found"); + e.printStackTrace(); + } + } + + /** + * Empty JSONObject from a non-XML string. + */ + @Test + public void testMethodOne_outerTag() { + + System.out.println("Rahul Hello World"); + + String expectedStr = + " Ralls, Kim\n"+ + " Midnight Rain\n"+ + " Fantasy\n"+ + " 5.95\n"+ + " 2000-12-16\n"+ + " A former architect battles corporate zombies, " + + "an evil sorceress, and her own childhood to become queen " + + "of the world.\n" + + " bk102\n"; + + expectedStr = XML.toJSONObject(expectedStr).toString(); + //expectedStr = expectedStr.replaceAll("\\n", ""); + String actualStr = ""; + try { - FileReader filereader = new FileReader("src/test/resources/file.xml"); - JSONObject jo = XML.toJSONObject(filereader, new JSONPointer("/clinical_study/required_header/1")); + //FileReader filereader = new FileReader("src/test/resources/file.xml"); + //JSONObject jo = XML.toJSONObject(filereader, new JSONPointer("/clinical_study/sponsors/lead_sponsor/agency_class")); + FileReader filereader = new FileReader("src/test/resources/Catalog.xml"); + JSONObject jo = XML.toJSONObject(filereader, new JSONPointer("/catalog/book/1")); - System.out.println(jo); + actualStr = jo.toString(); + //actualStr = actualStr.replaceAll((\\r\\n|\\n|\\r), ""); + + System.out.println("Actual: " + actualStr); + System.out.println("Expected: " + expectedStr); + assertEquals(expectedStr, actualStr); } catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } - //String xmlStr = "{ \"this is\": \"not xml\"}"; - //JSONObject jsonObject = XML.toJSONObject(xmlStr); - //assertTrue("xml string should be empty", jsonObject.isEmpty()); } @Test - public void testMethodTwo() + public void testMethodTwo_replaceTag() { System.out.println("\nIn Test Method 2"); + String expectedStr = "{\"catalog\":{\"tname\":\"rahul jain\"}}"; try { FileReader filereader = new FileReader("src/test/resources/Catalog.xml"); JSONObject jo = XML.toJSONObject(filereader, new JSONPointer("/catalog/book"), XML.toJSONObject("rahul jain")); - System.out.println(jo); + String actualStr = jo.toString(); + assertEquals(expectedStr, actualStr); + + } catch (FileNotFoundException e) { + System.out.println("File not found"); + e.printStackTrace(); + } + } + + @Test + public void testMethodTwo_replaceAll() + { + System.out.println("\nIn Test Method 2"); + String expectedStr = "{\"tname\":\"rahul jain\"}"; - System.out.println("Testing out JSON to XML Conversion"); + try { + FileReader filereader = new FileReader("src/test/resources/Catalog.xml"); + JSONObject jo = XML.toJSONObject(filereader, new JSONPointer("/"), XML.toJSONObject("rahul jain")); - System.out.println(XML.toString(jo)); + String actualStr = jo.toString(); + assertEquals(expectedStr, actualStr); } catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } - } + } diff --git a/src/test/resources/Catalog.xml b/src/test/resources/Catalog.xml index 06889bd6c..96fb8546f 100644 --- a/src/test/resources/Catalog.xml +++ b/src/test/resources/Catalog.xml @@ -15,9 +15,7 @@ Fantasy 5.95 2000-12-16 - A former architect battles corporate zombies, - an evil sorceress, and her own childhood to become queen - of the world. + A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. Corets, Eva diff --git a/src/test/resources/file.xml b/src/test/resources/file.xml index bb550d162..b38836331 100644 --- a/src/test/resources/file.xml +++ b/src/test/resources/file.xml @@ -15,7 +15,7 @@ Link to the current ClinicalTrials.gov record. https://clinicaltrials.gov/show/NCT03874338 - ClinicalTrials.gov processed this data on July 19, 2020 + raji date caji Link to the current ClinicalTrials.gov record. https://clinicaltrials.gov/show/NCT03874338 From acce15c894534a0bbc73eb446cc3d15b021261d0 Mon Sep 17 00:00:00 2001 From: rajihul Date: Mon, 8 Feb 2021 23:49:51 -0800 Subject: [PATCH 05/11] Added overloaded method toJSONObject(Reader, Function) for Milestone 3 that transforms keys given by a transformation given by user.. Added a TestCase to XMLTest_SWE262 called testMethodThree_replaceKay --- pom.xml | 4 +- src/main/java/org/json/XML.java | 76 ++++++++++ .../java/org/json/junit/XMLTest_SWE262.java | 141 ++++++++++++++++++ src/test/resources/TransformerTest.xml | 0 4 files changed, 219 insertions(+), 2 deletions(-) create mode 100644 src/test/resources/TransformerTest.xml diff --git a/pom.xml b/pom.xml index e5449ba8c..e161b2d46 100644 --- a/pom.xml +++ b/pom.xml @@ -118,8 +118,8 @@ maven-compiler-plugin 2.3.2 - 1.6 - 1.6 + 8 + 8 diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 21a85938e..28ee080c5 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -30,6 +30,7 @@ of this software and associated documentation files (the "Software"), to deal import java.math.BigDecimal; import java.math.BigInteger; import java.util.Iterator; +import java.util.function.Function; /** @@ -967,6 +968,81 @@ public static JSONObject toJSONObject(Reader reader, JSONPointer path, JSONObjec return query; } + //[RJ_ADDED] This overloaded static method replces all keys with output + //of keyTransformer output. + public static JSONObject toJSONObject(Reader reader, Function keyTransformer) + { + + JSONObject jo = new JSONObject(); + XMLParserConfiguration config = new XMLParserConfiguration(); + XMLTokener x = new XMLTokener(reader); + + + //rebuild the sub xml + String rebuildXML = ""; + boolean cycle = false; + + boolean exitLoop = false; + + String currTag =""; + + //String startString = "<" + parseTag; + //String exitString = " with possible info afterwards. + //1. Extract the first word after opening tag openTag = ",0); + //Get the first word after < in the tag + tag = tag[0].split(" ",0); + + //Handle close \n" + + "\n" + + " \n" + + " Gambardella, Matthew\n" + + " XML Developer's Guide\n" + + " Computer\n" + + " 44.95\n" + + " 2000-10-01\n" + + " An in-depth look at creating applications\n" + + " with XML.\n" + + " \n" + + " \n" + + " Ralls, Kim\n" + + " Midnight Rain\n" + + " Fantasy\n" + + " 5.95\n" + + " 2000-12-16\n" + + " A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.\n" + + " \n" + + " \n" + + " Corets, Eva\n" + + " Maeve Ascendant\n" + + " Fantasy\n" + + " 5.95\n" + + " 2000-11-17\n" + + " After the collapse of a nanotechnology\n" + + " society in England, the young survivors lay the\n" + + " foundation for a new society.\n" + + " \n" + + " \n" + + " Corets, Eva\n" + + " Oberon's Legacy\n" + + " Fantasy\n" + + " 5.95\n" + + " 2001-03-10\n" + + " In post-apocalypse England, the mysterious\n" + + " agent known only as Oberon helps to create a new life\n" + + " for the inhabitants of London. Sequel to Maeve\n" + + " Ascendant.\n" + + " \n" + + " \n" + + " Corets, Eva\n" + + " The Sundered Grail\n" + + " Fantasy\n" + + " 5.95\n" + + " 2001-09-10\n" + + " The two daughters of Maeve, half-sisters,\n" + + " battle one another for control of England. Sequel to\n" + + " Oberon's Legacy.\n" + + " \n" + + " \n" + + " Randall, Cynthia\n" + + " Lover Birds\n" + + " Romance\n" + + " 4.95\n" + + " 2000-09-02\n" + + " When Carla meets Paul at an ornithology\n" + + " conference, tempers fly as feathers get ruffled.\n" + + " \n" + + " \n" + + " Thurman, Paula\n" + + " Splish Splash\n" + + " Romance\n" + + " 4.95\n" + + " 2000-11-02\n" + + " A deep sea diver finds true love twenty\n" + + " thousand leagues beneath the sea.\n" + + " \n" + + " \n" + + " Knorr, Stefan\n" + + " Creepy Crawlies\n" + + " Horror\n" + + " 4.95\n" + + " 2000-12-06\n" + + " An anthology of horror stories about roaches,\n" + + " centipedes, scorpions and other insects.\n" + + " \n" + + " \n" + + " Kress, Peter\n" + + " Paradox Lost\n" + + " Science Fiction\n" + + " 6.95\n" + + " 2000-11-02\n" + + " After an inadvertant trip through a Heisenberg\n" + + " Uncertainty Device, James Salway discovers the problems\n" + + " of being quantum.\n" + + " \n" + + " \n" + + " O'Brien, Tim\n" + + " Microsoft .NET: The Programming Bible\n" + + " Computer\n" + + " 36.95\n" + + " 2000-12-09\n" + + " Microsoft's .NET initiative is explored in\n" + + " detail in this deep programmer's reference.\n" + + " \n" + + " \n" + + " O'Brien, Tim\n" + + " MSXML3: A Comprehensive Guide\n" + + " Computer\n" + + " 36.95\n" + + " 2000-12-01\n" + + " The Microsoft MSXML3 parser is covered in\n" + + " detail, with attention to XML DOM interfaces, XSLT processing,\n" + + " SAX and more.\n" + + " \n" + + " \n" + + " Galos, Mike\n" + + " Visual Studio 7: A Comprehensive Guide\n" + + " Computer\n" + + " 49.95\n" + + " 2001-04-16\n" + + " Microsoft Visual Studio 7 is explored in depth,\n" + + " looking at how Visual Basic, Visual C++, C#, and ASP+ are\n" + + " integrated into a comprehensive development\n" + + " environment.\n" + + " \n" + + ""; + + expectedStr = XML.toJSONObject(expectedStr).toString(); + try { + //Define the function + Function keyTransformer= (x) -> ("RJ_"+x); + FileReader filereader = new FileReader("src/test/resources/Catalog.xml"); + JSONObject jo = XML.toJSONObject(filereader, keyTransformer); + + String actualStr = jo.toString(); + //System.out.println(actualStr); + assertEquals(expectedStr, actualStr); + + } catch (FileNotFoundException e) { + System.out.println("File not found"); + e.printStackTrace(); + } + } + } diff --git a/src/test/resources/TransformerTest.xml b/src/test/resources/TransformerTest.xml new file mode 100644 index 000000000..e69de29bb From edabcdcc42245420ef7bc9447ee2142fff36f7db Mon Sep 17 00:00:00 2001 From: rajihul Date: Mon, 8 Feb 2021 23:55:03 -0800 Subject: [PATCH 06/11] Added another test case testReplaceKey2 to XMLTest_SWE262. --- .../java/org/json/junit/XMLTest_SWE262.java | 26 +++++++++++++++++++ src/test/resources/TransformerTest.xml | 4 +++ 2 files changed, 30 insertions(+) diff --git a/src/test/java/org/json/junit/XMLTest_SWE262.java b/src/test/java/org/json/junit/XMLTest_SWE262.java index e5ae3f8c1..42eaf1e96 100644 --- a/src/test/java/org/json/junit/XMLTest_SWE262.java +++ b/src/test/java/org/json/junit/XMLTest_SWE262.java @@ -273,4 +273,30 @@ public void testMethodThree_replaceKey() } } + @Test + public void testReplaceKey2() + { + String expectedStr = "\n" + + "\n" + + " rajihul@gmail.com\n" + + ""; + expectedStr = XML.toJSONObject(expectedStr).toString(); + + try { + //Define the function + Function keyTransformer= (x) -> ("SWE262_"+x); + FileReader filereader = new FileReader("src/test/resources/TransformerTest.xml"); + JSONObject jo = XML.toJSONObject(filereader, keyTransformer); + + String actualStr = jo.toString(); + //System.out.println(actualStr); + assertEquals(expectedStr, actualStr); + + } catch (FileNotFoundException e) { + System.out.println("File not found"); + e.printStackTrace(); + } + + } + } diff --git a/src/test/resources/TransformerTest.xml b/src/test/resources/TransformerTest.xml index e69de29bb..cef50a89c 100644 --- a/src/test/resources/TransformerTest.xml +++ b/src/test/resources/TransformerTest.xml @@ -0,0 +1,4 @@ + + + rajihul@gmail.com + \ No newline at end of file From 5289d97eb4122a62a64fee5f92fc295ce09f4707 Mon Sep 17 00:00:00 2001 From: rajihul Date: Mon, 8 Feb 2021 23:59:07 -0800 Subject: [PATCH 07/11] Cleaned up some comments and unused code. --- src/main/java/org/json/XML.java | 22 +--------------------- 1 file changed, 1 insertion(+), 21 deletions(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 28ee080c5..c01eb5799 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -972,30 +972,16 @@ public static JSONObject toJSONObject(Reader reader, JSONPointer path, JSONObjec //of keyTransformer output. public static JSONObject toJSONObject(Reader reader, Function keyTransformer) { - - JSONObject jo = new JSONObject(); - XMLParserConfiguration config = new XMLParserConfiguration(); XMLTokener x = new XMLTokener(reader); - //rebuild the sub xml String rebuildXML = ""; - boolean cycle = false; - - boolean exitLoop = false; String currTag =""; - //String startString = "<" + parseTag; - //String exitString = " with possible info afterwards. //1. Extract the first word after opening tag openTag = ke //This should contain what's in the current line tag String oldTag = tag[0].substring(tag[0].indexOf("<") + +1); - //2. Feed the openTag to keyTransformer function. Set it to new variable newTag. String newTag = keyTransformer.apply(oldTag); @@ -1028,21 +1013,16 @@ public static JSONObject toJSONObject(Reader reader, Function ke currTag = currTag.replaceAll(oldTag,newTag);; //+ something } - rebuildXML += currTag; //System.out.println("Pre If: " + currTag); } //System.out.println(rebuildXML); JSONObject query = XML.toJSONObject(rebuildXML); - //System.out.println(query.toString()); - - - //System.out.println("PrintingJSON"); return query; - //return null; } + /** * Convert a JSONObject into a well-formed, element-normal XML string. * From fef9e7134ea24219b6e26ff5b747381711504504 Mon Sep 17 00:00:00 2001 From: rajihul Date: Tue, 9 Feb 2021 22:39:11 -0800 Subject: [PATCH 08/11] Added another README for Milestone3 commenting on performance implications. --- MILESTONE3-README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 MILESTONE3-README.md diff --git a/MILESTONE3-README.md b/MILESTONE3-README.md new file mode 100644 index 000000000..2f3c499b5 --- /dev/null +++ b/MILESTONE3-README.md @@ -0,0 +1,12 @@ +**Performance Implications of doing this inside the +library vs. doing it in client code:** + +Performing a transformation on all the keys of the resulting JSON object is +much more efficient when done inside the library for two reasons: +1. You can modify the key as you're reading the XML file and generating the +JSON object versus generating the entire JSON Object first and then going back +to parse the entire structure again and updating the keys. + +2. You can provide your own custom transformations which can be +handled dynamically thanks to the functional interface built into +Java 8. \ No newline at end of file From a1a3fcccefa4ca3330e4dd01fc8c005863b9c65e Mon Sep 17 00:00:00 2001 From: rajihul Date: Tue, 23 Feb 2021 21:32:17 -0800 Subject: [PATCH 09/11] Added toStream method to XML class. Added two testStream methods to XMLTest_SWE262. --- src/main/java/org/json/XML.java | 53 ++++++++++++- .../java/org/json/junit/XMLTest_SWE262.java | 79 +++++++++++++++++++ 2 files changed, 130 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index c01eb5799..e01f6f5d1 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -29,8 +29,9 @@ of this software and associated documentation files (the "Software"), to deal import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.Iterator; +import java.util.*; import java.util.function.Function; +import java.util.stream.Stream; /** @@ -1007,7 +1008,7 @@ public static JSONObject toJSONObject(Reader reader, Function ke String oldTag = tag[0].substring(tag[0].indexOf("<") + +1); //2. Feed the openTag to keyTransformer function. Set it to new variable newTag. - String newTag = keyTransformer.apply(oldTag); + String newTag = keyTransformer.apply(oldTag ); //3. Replace openTag with newTag in currTag. currTag = currTag.replaceAll(oldTag,newTag);; //+ something @@ -1023,6 +1024,54 @@ public static JSONObject toJSONObject(Reader reader, Function ke return query; } + /** + * MILESTONE 4 METHOD: Implementing Streams + * Feb 21, 2021 + */ + + public static Stream toStream(JSONObject obj) + { + /***Takes an already established JSON Object and converts it into + an XML object: **/ + String jsonXML = XML.toString(obj); + + //Now we can play with our XML + // a type of collections so that the Streams can act upon it. + /*************************************************************/ + XMLTokener x = new XMLTokener(jsonXML); + + //rebuild the sub xml + String rebuildXML = ""; + + String currTag =""; + + ArrayList listOfTags = new ArrayList<>(); + + while (x.more()) { + x.skipPast("<"); + currTag = "<" + x.nextContent(); + //System.out.println(currTag); + //Current tag holds the tag <> with possible info afterwards. + //1. Extract the first word after opening tag openTag = \n" + + "\n" + + " rajihul@gmail.com\n" + + ""; + + //expectedStr = XML.toJSONObject(expectedStr).toString(); + String actualStr = ""; + + try { + //Define the function + //Function keyTransformer= (x) -> ("SWE262_"+x); + FileReader filereader = new FileReader("src/test/resources/TransformerTest.xml"); + JSONObject jo = XML.toJSONObject(Str); + + List trstr = XML.toStream(jo) + // .forEach(x -> x.replace("SWE262","RJ")) + .filter(x->x.contains("SWE262_email")) + .collect(Collectors.toList()); + + for(String i:trstr) + actualStr += i; + + //System.out.println(actualStr); + //System.out.println(actualStr); + assertEquals(expectedStr, actualStr); + + } catch (FileNotFoundException e) { + System.out.println("File not found"); + e.printStackTrace(); + } + } + @Test + public void testStream2() + { + String expectedStr = ""; + + String Str = "\n" + + "\n" + + " rajihul@gmail.com\n" + + ""; + + //expectedStr = XML.toJSONObject(expectedStr).toString(); + String actualStr = ""; + + try { + //Define the function + //Function keyTransformer= (x) -> ("SWE262_"+x); + FileReader filereader = new FileReader("src/test/resources/TransformerTest.xml"); + JSONObject jo = XML.toJSONObject(Str); + + List trstr = XML.toStream(jo) + // .forEach(x -> x.replace("SWE262","RJ")) + .filter(x->!x.contains("SWE262_email")) + .collect(Collectors.toList()); + + for(String i:trstr) + actualStr += i; + + System.out.println(actualStr); + //System.out.println(actualStr); + assertEquals(expectedStr, actualStr); + + } catch (FileNotFoundException e) { + System.out.println("File not found"); + e.printStackTrace(); + } + } + } From 99dea4113d5d7d92530b7234556ce612ec2aab53 Mon Sep 17 00:00:00 2001 From: rajihul Date: Tue, 9 Mar 2021 11:42:15 -0800 Subject: [PATCH 10/11] Added Async toJSONObject method and one test case. --- src/main/java/org/json/XML.java | 46 ++++++++++++++++++- .../java/org/json/junit/XMLTest_SWE262.java | 45 ++++++++++++++++++ 2 files changed, 90 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index e01f6f5d1..9eb934005 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -42,7 +42,7 @@ of this software and associated documentation files (the "Software"), to deal * @version 2016-08-10 */ @SuppressWarnings("boxing") -public class XML { +public class XML{ /** The Character '&'. */ public static final Character AMP = '&'; @@ -78,6 +78,11 @@ public class XML { public static final String TYPE_ATTR = "xsi:type"; + /** [Milestone 5] + * Need to define some global function variables that can be accessed by run function. + */ + //public static Function command, errorHandle; + /** * Creates an iterator for navigating Code Points in a string instead of * characters. Once Java7 support is dropped, this can be replaced with @@ -1072,6 +1077,45 @@ public static Stream toStream(JSONObject obj) return (listOfTags).stream(); } + public static void toJSONObject(Reader r, Function command, boolean diff) + { + //Reader r, Function commander, Function errorHandler + //Take the inputs and store them in global variables for later use in run function + //command = commander; + //errorHandle = errorHandler; + String outstr = "outside the thread rj"; + JSONObject myJSON = toJSONObject(r); + + Runnable runnable = () -> { + System.out.println("Inside : " + outstr); + System.out.println(myJSON.toString()); + command.apply(myJSON); + }; + + System.out.println("Creating Thread..."); + Thread thread = new Thread(runnable); + + System.out.println("Starting Thread..."); + thread.start(); + + + //(new Thread(new XML())).start(); + } + + /*public void run() { + System.out.println("Hello from a thread!"); + try + { + //Convert reader to JSON Object and send off.i + command.apply(); + + } catch (Exception e) + { + System.out.println(); + } + }*/ + + /** * Convert a JSONObject into a well-formed, element-normal XML string. * diff --git a/src/test/java/org/json/junit/XMLTest_SWE262.java b/src/test/java/org/json/junit/XMLTest_SWE262.java index 1b1e868bb..e2eb59f51 100644 --- a/src/test/java/org/json/junit/XMLTest_SWE262.java +++ b/src/test/java/org/json/junit/XMLTest_SWE262.java @@ -378,4 +378,49 @@ public void testStream2() } } + @Test + public void async() + { + String expectedStr = ""; + //Generate output.txt + try + { + FileReader filereader = new FileReader("src/test/resources/Catalog.xml"); + FileWriter filewriter = new FileWriter("output.json"); + XML.toJSONObject(filereader, (JSONObject joo) -> joo.write(filewriter), true); + //XML.toJSONObject(); + expectedStr = XML.toJSONObject(filereader).toString(); + + + //Give thread adequate time to finish + try{ + Thread.sleep(1000); + + }catch(InterruptedException e) + { + e.printStackTrace(); + } + + //filewriter.flush(); + filewriter.close(); + }catch(IOException e) + { + e.printStackTrace(); + } + + //Compare the output.txt to the Catalog.xml JSON + try + { + FileReader filereader = new FileReader("output.json"); + JSONObject actualJSON = XML.toJSONObject(filereader); + assertEquals(expectedStr, actualJSON.toString()); + + }catch(IOException e) + { + e.printStackTrace(); + } + + + } + } From b14fdca49e078a94b2b6c6e22296e81d9ab70a88 Mon Sep 17 00:00:00 2001 From: rajihul Date: Tue, 9 Mar 2021 12:48:27 -0800 Subject: [PATCH 11/11] Added Exception handling paramater to Async toJSONObject method in XML class. Added another test case. --- src/main/java/org/json/XML.java | 54 +++++++------------ .../java/org/json/junit/XMLTest_SWE262.java | 48 ++++++++++++++++- src/test/resources/baddata.xml | 11 ++++ 3 files changed, 78 insertions(+), 35 deletions(-) create mode 100644 src/test/resources/baddata.xml diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 9eb934005..cc52dd50e 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -30,6 +30,7 @@ of this software and associated documentation files (the "Software"), to deal import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; +import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Stream; @@ -78,11 +79,6 @@ public class XML{ public static final String TYPE_ATTR = "xsi:type"; - /** [Milestone 5] - * Need to define some global function variables that can be accessed by run function. - */ - //public static Function command, errorHandle; - /** * Creates an iterator for navigating Code Points in a string instead of * characters. Once Java7 support is dropped, this can be replaced with @@ -1077,45 +1073,35 @@ public static Stream toStream(JSONObject obj) return (listOfTags).stream(); } - public static void toJSONObject(Reader r, Function command, boolean diff) + /** + * ASYNCHRONOUS toJSONObject method for [MILESTONE 5], 3/9/2021 + * @param r + * @param command + * @param diff + */ + public static void toJSONObject(Reader r, Function command, Consumer errorHandler) { - //Reader r, Function commander, Function errorHandler - //Take the inputs and store them in global variables for later use in run function - //command = commander; - //errorHandle = errorHandler; - String outstr = "outside the thread rj"; - JSONObject myJSON = toJSONObject(r); + //"Thread run method" - Apply the User-Given function. Runnable runnable = () -> { - System.out.println("Inside : " + outstr); - System.out.println(myJSON.toString()); - command.apply(myJSON); + try{ + JSONObject myJSON = toJSONObject(r); + command.apply(myJSON); + } + catch(Exception e) + { + errorHandler.accept(e); + } + }; - System.out.println("Creating Thread..."); + //"Creating Thread" Thread thread = new Thread(runnable); - System.out.println("Starting Thread..."); + //"Starting Thread" thread.start(); - - - //(new Thread(new XML())).start(); } - /*public void run() { - System.out.println("Hello from a thread!"); - try - { - //Convert reader to JSON Object and send off.i - command.apply(); - - } catch (Exception e) - { - System.out.println(); - } - }*/ - - /** * Convert a JSONObject into a well-formed, element-normal XML string. * diff --git a/src/test/java/org/json/junit/XMLTest_SWE262.java b/src/test/java/org/json/junit/XMLTest_SWE262.java index e2eb59f51..3c1c34d83 100644 --- a/src/test/java/org/json/junit/XMLTest_SWE262.java +++ b/src/test/java/org/json/junit/XMLTest_SWE262.java @@ -378,6 +378,7 @@ public void testStream2() } } + /** For Milestone 5 **/ @Test public void async() { @@ -387,7 +388,7 @@ public void async() { FileReader filereader = new FileReader("src/test/resources/Catalog.xml"); FileWriter filewriter = new FileWriter("output.json"); - XML.toJSONObject(filereader, (JSONObject joo) -> joo.write(filewriter), true); + XML.toJSONObject(filereader, (JSONObject joo) -> joo.write(filewriter), (Exception e)-> e.printStackTrace()); //XML.toJSONObject(); expectedStr = XML.toJSONObject(filereader).toString(); @@ -420,6 +421,51 @@ public void async() e.printStackTrace(); } + } + + /** For Milestone 5 **/ + @Test + public void async_exception() + { + String expectedStr = ""; + //Generate output.txt + try + { + //The baddata file doens't have closing tag so should throw exception + FileReader filereader = new FileReader("src/test/resources/baddata.xml"); + FileWriter filewriter = new FileWriter("output.json"); + XML.toJSONObject(filereader, (JSONObject joo) -> joo.write(filewriter), (Exception e)-> System.out.println("Something went wrong!")); + //XML.toJSONObject(); + expectedStr = XML.toJSONObject(filereader).toString(); + + + //Give thread adequate time to finish + try{ + Thread.sleep(1000); + + }catch(InterruptedException e) + { + e.printStackTrace(); + } + + //filewriter.flush(); + filewriter.close(); + }catch(IOException e) + { + e.printStackTrace(); + } + + //Compare the output.txt to the Catalog.xml JSON + try + { + FileReader filereader = new FileReader("output.json"); + JSONObject actualJSON = XML.toJSONObject(filereader); + assertEquals(expectedStr, actualJSON.toString()); + + }catch(IOException e) + { + e.printStackTrace(); + } } diff --git a/src/test/resources/baddata.xml b/src/test/resources/baddata.xml new file mode 100644 index 000000000..4c684918e --- /dev/null +++ b/src/test/resources/baddata.xml @@ -0,0 +1,11 @@ + + + + Gambardella, Matthew + XML Developer's Guide + Computer + 44.95 + 2000-10-01 + An in-depth look at creating applications + with XML. + \ No newline at end of file