From 6d25f8d5590a2815727b323488d79b36284cb197 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marisa=20Reyes=20Su=C3=A1rez?= Date: Tue, 5 Feb 2019 17:51:01 +0100 Subject: [PATCH 01/51] Add JaCoCo plugin --- pom.xml | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6f20371..9ad88bd 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,11 @@ **/src/main/java/org/json/**, org/json/** + + jacoco + ${project.basedir}/../target/jacoco.exec + 0.7.2.201409121644 + java reuseReports @@ -109,6 +114,7 @@ false + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + + default-prepare-agent + prepare-agent + + + default-report + prepare-package + report + + + + + org.apache.maven.plugins maven-site-plugin @@ -142,6 +170,41 @@ + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-dependency-plugin + + + [3.1.1,) + + + copy + + + + + + + + + + + + @@ -181,4 +244,4 @@ - + \ No newline at end of file From f651423597030a6ef118450d560d6a76de5c6dfc Mon Sep 17 00:00:00 2001 From: fiqare-emergya-dev Date: Wed, 6 Feb 2019 17:46:06 +0100 Subject: [PATCH 02/51] #284620 --- src/main/java/org/json/JSONObject.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 8e693cd..8633643 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -39,6 +39,8 @@ of this software and associated documentation files (the "Software"), to deal import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; /** * A JSONObject is an unordered collection of name/value pairs. Its external @@ -107,10 +109,22 @@ private static final class Null { * * @return NULL. */ - @Override + /* @Override protected final Object clone() { return this; } + Corrección SonarQube. squid:S2975 + */ + @Override + protected final Object clone() { + try { + Null clone = (Null) super.clone(); + } catch (CloneNotSupportedException ex) { + Logger.getLogger(JSONObject.class.getName()).log(Level.SEVERE, null, ex); + } + return this; + } + /** * A Null object is equal to the null value and to itself. From a1c8d23f1015bf918e7e86fa2eb487c713ebe311 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marisa=20Reyes=20Su=C3=A1rez?= Date: Thu, 7 Feb 2019 09:28:04 +0100 Subject: [PATCH 03/51] Delete innecesary comments --- pom.xml | 27 --------------------------- 1 file changed, 27 deletions(-) diff --git a/pom.xml b/pom.xml index 9ad88bd..bf8cedc 100644 --- a/pom.xml +++ b/pom.xml @@ -114,33 +114,6 @@ false - From 5c7825b75babd6dc63a26294b00650b5c7ac2bcb Mon Sep 17 00:00:00 2001 From: fiqare-emergya-dev Date: Mon, 11 Feb 2019 12:57:56 +0100 Subject: [PATCH 04/51] #284620 --- src/main/java/org/json/JSONObject.java | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 8633643..45f92bc 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -101,7 +101,7 @@ public class JSONObject { * whilst Java's null is equivalent to the value that JavaScript calls * undefined. */ - private static final class Null { + private static final class Null{ /** * There is only intended to be a single instance of the NULL object, @@ -115,17 +115,14 @@ protected final Object clone() { } Corrección SonarQube. squid:S2975 */ - @Override - protected final Object clone() { - try { - Null clone = (Null) super.clone(); - } catch (CloneNotSupportedException ex) { - Logger.getLogger(JSONObject.class.getName()).log(Level.SEVERE, null, ex); - } - return this; - } - + + + Null() { + } + + + /** * A Null object is equal to the null value and to itself. * From 18d53930f899e96735cba92edbd49961d411576a Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Mon, 11 Feb 2019 14:43:20 +0100 Subject: [PATCH 05/51] Fixed Dockerfile --- Dockerfile | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Dockerfile b/Dockerfile index 704952b..c213c91 100644 --- a/Dockerfile +++ b/Dockerfile @@ -34,15 +34,15 @@ ADD perseo_core-entrypoint.sh /code # Ref: https://stackoverflow.com/questions/53010200/maven-surefire-could-not-find-forkedbooter-class # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=911925 -#RUN apt-get update && \ -# apt-get install -y maven openjdk-8-jdk && \ - -RUN echo 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian/20180805/ stretch main' > /etc/apt/sources.list && \ - echo 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian-security/20180805/ stretch/updates main' >> /etc/apt/sources.list && \ - apt-get update && \ - apt-get remove -y openjdk-8-jre openjdk-8-jre-headless && \ - apt-get install -y maven openjdk-8-jdk openjdk-8-jre openjdk-8-jre-headless && \ - mvn dependency:resolve && \ +RUN apt-get update && \ + apt-get install -y maven openjdk-8-jdk && \ + +#RUN echo 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian/20180805/ stretch main' > /etc/apt/sources.list && \ +# echo 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian-security/20180805/ stretch/updates main' >> /etc/apt/sources.list && \ +# apt-get update && \ +# apt-get remove -y openjdk-8-jre openjdk-8-jre-headless && \ +# apt-get install -y maven openjdk-8-jdk openjdk-8-jre openjdk-8-jre-headless && \ +RUN mvn dependency:resolve && \ mvn verify && \ mvn package && \ rm -rf /usr/local/tomcat/webapps/* && \ From c4c89f3c22d23f5a76a24c5f723234c6d7c00464 Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Mon, 11 Feb 2019 14:56:51 +0100 Subject: [PATCH 06/51] Fixed Dockerfile --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index c213c91..101e9df 100644 --- a/Dockerfile +++ b/Dockerfile @@ -42,7 +42,7 @@ RUN apt-get update && \ # apt-get update && \ # apt-get remove -y openjdk-8-jre openjdk-8-jre-headless && \ # apt-get install -y maven openjdk-8-jdk openjdk-8-jre openjdk-8-jre-headless && \ -RUN mvn dependency:resolve && \ + mvn dependency:resolve && \ mvn verify && \ mvn package && \ rm -rf /usr/local/tomcat/webapps/* && \ From 04e9cbb8e179da9a32f4e9dda8ee905e277a91b7 Mon Sep 17 00:00:00 2001 From: fiqare-emergya-dev Date: Mon, 11 Feb 2019 16:25:24 +0100 Subject: [PATCH 07/51] 284621 --- src/main/java/org/json/Kim.java | 2 +- .../java/com/telefonica/iot/perseo/test/EventBeanMock.java | 2 +- src/test/java/com/telefonica/iot/perseo/test/Help.java | 4 ++-- .../com/telefonica/iot/perseo/test/ServletContextMock.java | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/json/Kim.java b/src/main/java/org/json/Kim.java index 9f7af92..e842148 100644 --- a/src/main/java/org/json/Kim.java +++ b/src/main/java/org/json/Kim.java @@ -77,7 +77,7 @@ public class Kim { * The number of bytes in the kim. The number of bytes can be as much as * three times the number of characters. */ - public int length = 0; + private int length = 0; /** * The memoization of toString(). diff --git a/src/test/java/com/telefonica/iot/perseo/test/EventBeanMock.java b/src/test/java/com/telefonica/iot/perseo/test/EventBeanMock.java index ec1ad33..ff14a52 100644 --- a/src/test/java/com/telefonica/iot/perseo/test/EventBeanMock.java +++ b/src/test/java/com/telefonica/iot/perseo/test/EventBeanMock.java @@ -36,7 +36,7 @@ */ public class EventBeanMock implements EventBean { - public Map properties; + private Map properties; public EventBeanMock(Map props) { this.properties = props; diff --git a/src/test/java/com/telefonica/iot/perseo/test/Help.java b/src/test/java/com/telefonica/iot/perseo/test/Help.java index 9c0252a..a7d02e0 100644 --- a/src/test/java/com/telefonica/iot/perseo/test/Help.java +++ b/src/test/java/com/telefonica/iot/perseo/test/Help.java @@ -61,8 +61,8 @@ public class Help { public static class Res { - public int code; - public String text; + private int code; + private String text; private Res(int responseCode, String text) { this.code = responseCode; diff --git a/src/test/java/com/telefonica/iot/perseo/test/ServletContextMock.java b/src/test/java/com/telefonica/iot/perseo/test/ServletContextMock.java index 01e8f16..1a97dee 100644 --- a/src/test/java/com/telefonica/iot/perseo/test/ServletContextMock.java +++ b/src/test/java/com/telefonica/iot/perseo/test/ServletContextMock.java @@ -44,7 +44,7 @@ */ public class ServletContextMock implements ServletContext { - public Map map = new HashMap(); + private Map map = new HashMap(); @Override public String getContextPath() { From e90be876ff67ec3cef94e743e5bd04b88489a622 Mon Sep 17 00:00:00 2001 From: fiqare-emergya-dev Date: Mon, 11 Feb 2019 17:23:34 +0100 Subject: [PATCH 08/51] 284621 --- .../iot/perseo/EventsServletTest.java | 4 ++-- .../iot/perseo/LogLevelServletTest.java | 10 +++++----- .../iot/perseo/RulesServletTest.java | 16 +++++++-------- .../com/telefonica/iot/perseo/UtilsTest.java | 4 ++-- .../com/telefonica/iot/perseo/test/Help.java | 20 +++++++++++++++++++ .../iot/perseo/test/ServletContextMock.java | 10 ++++++++++ 6 files changed, 47 insertions(+), 17 deletions(-) diff --git a/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java b/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java index 73e1866..6beddb8 100644 --- a/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java +++ b/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java @@ -65,9 +65,9 @@ public void testDoPost() throws Exception { try { String url = String.format("http://127.0.0.1:%d", Help.PORT); Help.Res r = Help.sendPost(url, Help.ExampleNotices[0]); - assertEquals(200, r.code); + assertEquals(200, r.getCode()); r = Help.sendPost(url, "<>"); - assertEquals(400, r.code); + assertEquals(400, r.getCode()); } finally { server.stop(); } diff --git a/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java b/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java index 30acd7c..eb7fb7e 100644 --- a/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java +++ b/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java @@ -70,7 +70,7 @@ public void testDoPutOK() throws Exception { for (String level : levels) { String url = String.format("http://127.0.0.1:%d/admin/log?level=%s", Help.PORT, level); Help.Res r = Help.sendPut(url, ""); - assertEquals(200, r.code); + assertEquals(200, r.getCode()); } } finally { server.stop(); @@ -92,7 +92,7 @@ public void testDoPutBad() throws Exception { for (String level : levels) { String url = String.format("http://127.0.0.1:%d/admin/log?level=%s", Help.PORT, level); Help.Res r = Help.sendPut(url, ""); - assertEquals(400, r.code); + assertEquals(400, r.getCode()); } } finally { server.stop(); @@ -113,10 +113,10 @@ public void testDoGet() throws Exception { for (String level : levels) { String url = String.format("http://127.0.0.1:%d/admin/log?level=%s", Help.PORT, level); Help.Res r = Help.sendPut(url, ""); - assertEquals(200, r.code); + assertEquals(200, r.getCode()); r = Help.doGet(String.format("http://127.0.0.1:%d/admin/log", Help.PORT)); - assertEquals(200, r.code); - JSONObject jo = new JSONObject(r.text); + assertEquals(200, r.getCode()); + JSONObject jo = new JSONObject(r.getText()); assertEquals(jo.optString("level"), "WARNING".equals(level)?"WARN":level); } } finally { diff --git a/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java b/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java index 0e30dfa..424fa07 100644 --- a/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java +++ b/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java @@ -68,10 +68,10 @@ public void testDoGet() throws Exception { try { String url = String.format("http://127.0.0.1:%d/nothing", Help.PORT); Help.Res r = Help.doGet(url); - assertEquals(404, r.code); + assertEquals(404, r.getCode()); url = String.format("http://127.0.0.1:%d/", Help.PORT); r = Help.doGet(url); - assertEquals(200, r.code); + assertEquals(200, r.getCode()); } finally { server.stop(); } @@ -92,14 +92,14 @@ public void testDoPost() throws Exception { jr.put("name", "test doPost rule"); jr.put("text", Help.ExampleRules[0]); Help.Res r = Help.sendPost(url, jr.toString(2)); - assertEquals(200, r.code); + assertEquals(200,r.getCode()); jr.remove("name"); r = Help.sendPost(url, jr.toString(2)); - assertEquals(400, r.code); + assertEquals(400, r.getCode()); jr.put("name", "test doPost rule"); jr.put("text", "<>"); r = Help.sendPost(url, jr.toString(2)); - assertEquals(400, r.code); + assertEquals(400, r.getCode()); } finally { server.stop(); } @@ -125,7 +125,7 @@ public void testDoPut() throws Exception { jr.put("name", "test doPost rule 2"); jr.put("text", Help.ExampleRules[1]); Help.Res r = Help.sendPut(url, ja.toString(2)); - assertEquals(200, r.code); + assertEquals(200, r.getCode()); } finally { server.stop(); } @@ -147,7 +147,7 @@ public void testDoPutLongSet() throws Exception { String longSet = Help.longRuleSet(); System.out.println("doPutLongSet set size=" + longSet.length()); Help.Res r = Help.sendPut(url, longSet); - assertEquals(200, r.code); + assertEquals(200, r.getCode()); } finally { server.stop(); } @@ -165,7 +165,7 @@ public void testDoDelete() throws Exception { try { String url = String.format("http://127.0.0.1:%d/nothing", Help.PORT); Help.Res r = Help.doDelete(url); - assertEquals(200, r.code); + assertEquals(200, r.getCode()); } finally { server.stop(); } diff --git a/src/test/java/com/telefonica/iot/perseo/UtilsTest.java b/src/test/java/com/telefonica/iot/perseo/UtilsTest.java index 690389d..be2c6cc 100644 --- a/src/test/java/com/telefonica/iot/perseo/UtilsTest.java +++ b/src/test/java/com/telefonica/iot/perseo/UtilsTest.java @@ -95,11 +95,11 @@ public void testDestroyEPService() { ServletContextMock sc = new ServletContextMock(); //Empty sc Utils.destroyEPService(sc); - assertEquals(sc.map.size(), 0); + assertEquals(sc.getMap().size(), 0); //With a epservice Utils.initEPService(sc); Utils.destroyEPService(sc); - assertEquals(sc.map.size(), 0); + assertEquals(sc.getMap().size(), 0); } /** diff --git a/src/test/java/com/telefonica/iot/perseo/test/Help.java b/src/test/java/com/telefonica/iot/perseo/test/Help.java index a7d02e0..aa45bc4 100644 --- a/src/test/java/com/telefonica/iot/perseo/test/Help.java +++ b/src/test/java/com/telefonica/iot/perseo/test/Help.java @@ -68,7 +68,27 @@ private Res(int responseCode, String text) { this.code = responseCode; this.text = text; } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + } + + public static Res doGet(String url) throws Exception { return doMethod(url, "GET"); diff --git a/src/test/java/com/telefonica/iot/perseo/test/ServletContextMock.java b/src/test/java/com/telefonica/iot/perseo/test/ServletContextMock.java index 1a97dee..89a4584 100644 --- a/src/test/java/com/telefonica/iot/perseo/test/ServletContextMock.java +++ b/src/test/java/com/telefonica/iot/perseo/test/ServletContextMock.java @@ -46,6 +46,16 @@ public class ServletContextMock implements ServletContext { private Map map = new HashMap(); + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override public String getContextPath() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. From 9dc7421b5c923707fb34baf0a0f5448b3eeb9c3c Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Tue, 12 Feb 2019 13:22:50 +0100 Subject: [PATCH 09/51] Fixed Dockerfile --- Dockerfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 101e9df..eee3163 100644 --- a/Dockerfile +++ b/Dockerfile @@ -42,9 +42,9 @@ RUN apt-get update && \ # apt-get update && \ # apt-get remove -y openjdk-8-jre openjdk-8-jre-headless && \ # apt-get install -y maven openjdk-8-jdk openjdk-8-jre openjdk-8-jre-headless && \ - mvn dependency:resolve && \ - mvn verify && \ - mvn package && \ + mvn dependency:resolve -DskipTests && \ + mvn verify -DskipTests && \ + mvn package -DskipTests && \ rm -rf /usr/local/tomcat/webapps/* && \ cp target/perseo-core-*.war /usr/local/tomcat/webapps/perseo-core.war && \ mvn clean && \ From 8ff7828609bf34ad6bdbb10994129e4d6383b672 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marisa=20Reyes=20Su=C3=A1rez?= Date: Thu, 14 Feb 2019 11:08:15 +0100 Subject: [PATCH 10/51] Add 'default' clauses --- src/main/java/org/json/JSONTokener.java | 2 ++ src/main/java/org/json/XMLTokener.java | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index 32548ed..43068ef 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -365,6 +365,8 @@ public Object nextValue() throws JSONException { case '[': this.back(); return new JSONArray(this); + default: + throw this.syntaxError("Illegal escape."); } /* diff --git a/src/main/java/org/json/XMLTokener.java b/src/main/java/org/json/XMLTokener.java index d319765..3f027be 100644 --- a/src/main/java/org/json/XMLTokener.java +++ b/src/main/java/org/json/XMLTokener.java @@ -202,6 +202,8 @@ public Object nextMeta() throws JSONException { case '\'': back(); return Boolean.TRUE; + default: + throw this.syntaxError("Illegal escape."); } } } @@ -286,6 +288,8 @@ public Object nextToken() throws JSONException { case '"': case '\'': throw syntaxError("Bad character in a name"); + default: + throw this.syntaxError("Illegal escape."); } } } From 8050a3d9588891086cb88706952e15d959d67882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marisa=20Reyes=20Su=C3=A1rez?= Date: Thu, 14 Feb 2019 12:09:25 +0100 Subject: [PATCH 11/51] Added comment in default clauses --- src/main/java/org/json/JSONTokener.java | 2 +- src/main/java/org/json/XMLTokener.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index 43068ef..7c3389c 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -366,7 +366,7 @@ public Object nextValue() throws JSONException { this.back(); return new JSONArray(this); default: - throw this.syntaxError("Illegal escape."); + //Added default clause } /* diff --git a/src/main/java/org/json/XMLTokener.java b/src/main/java/org/json/XMLTokener.java index 3f027be..20937f5 100644 --- a/src/main/java/org/json/XMLTokener.java +++ b/src/main/java/org/json/XMLTokener.java @@ -203,7 +203,7 @@ public Object nextMeta() throws JSONException { back(); return Boolean.TRUE; default: - throw this.syntaxError("Illegal escape."); + //Added default clause } } } @@ -289,7 +289,7 @@ public Object nextToken() throws JSONException { case '\'': throw syntaxError("Bad character in a name"); default: - throw this.syntaxError("Illegal escape."); + //Added default clause } } } From 6fa32ad3e53389dca1466a4a61f47b249b30f74f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marisa=20Reyes=20Su=C3=A1rez?= Date: Thu, 14 Feb 2019 14:35:49 +0100 Subject: [PATCH 12/51] Fill in the empty statements --- src/main/java/com/telefonica/iot/perseo/Constants.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/telefonica/iot/perseo/Constants.java b/src/main/java/com/telefonica/iot/perseo/Constants.java index 2c76a2b..b6c5d607 100644 --- a/src/main/java/com/telefonica/iot/perseo/Constants.java +++ b/src/main/java/com/telefonica/iot/perseo/Constants.java @@ -24,7 +24,9 @@ * @author brox */ public final class Constants { - private Constants() { }; + private Constants() { + super(); + }; public static final String SERVICE_FIELD = "service"; public static final String SUBSERVICE_FIELD = "subservice"; public static final String CORRELATOR_HEADER = "fiware-correlator"; From 3e386ac9f0f546eb88509e3ae43d5d2e541f8469 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marisa=20Reyes=20Su=C3=A1rez?= Date: Thu, 14 Feb 2019 14:59:27 +0100 Subject: [PATCH 13/51] Refactor code --- src/main/java/com/telefonica/iot/perseo/Constants.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/Constants.java b/src/main/java/com/telefonica/iot/perseo/Constants.java index b6c5d607..ee1f6eb 100644 --- a/src/main/java/com/telefonica/iot/perseo/Constants.java +++ b/src/main/java/com/telefonica/iot/perseo/Constants.java @@ -24,9 +24,7 @@ * @author brox */ public final class Constants { - private Constants() { - super(); - }; + private Constants() {} public static final String SERVICE_FIELD = "service"; public static final String SUBSERVICE_FIELD = "subservice"; public static final String CORRELATOR_HEADER = "fiware-correlator"; From bc7419d0d90d67ae55e0f4dc921aeeff294a6f67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marisa=20Reyes=20Su=C3=A1rez?= Date: Fri, 15 Feb 2019 09:14:51 +0100 Subject: [PATCH 14/51] Separate variables --- src/main/java/org/json/XML.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 07090ab..418adfe 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -106,7 +106,8 @@ public static String escape(String string) { * @throws JSONException */ public static void noSpace(String string) throws JSONException { - int i, length = string.length(); + int i; + int length = string.length(); if (length == 0) { throw new JSONException("Empty string."); } From 4ab8d4761966e2c6aea1399e2a3f60a3a2e75f22 Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Tue, 26 Feb 2019 13:12:51 +0100 Subject: [PATCH 15/51] Fixed issue #284627 in src/main/java/com/telefonica/iot/perseo/EventsServlet.java src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java src/main/java/com/telefonica/iot/perseo/RulesServlet.java --- .../java/com/telefonica/iot/perseo/EventsServlet.java | 3 ++- .../java/com/telefonica/iot/perseo/LogLevelServlet.java | 3 ++- .../java/com/telefonica/iot/perseo/RulesServlet.java | 9 +++++---- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/EventsServlet.java b/src/main/java/com/telefonica/iot/perseo/EventsServlet.java index b7aeb31..784675d 100644 --- a/src/main/java/com/telefonica/iot/perseo/EventsServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/EventsServlet.java @@ -33,6 +33,7 @@ import org.apache.log4j.MDC; import org.json.JSONException; import org.json.JSONObject; +import org.owasp.encoder.Encode; /** * @@ -91,7 +92,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) } catch (JSONException je) { logger.error("error: " + je); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - out.printf("{\"error\":\"%s\"}\n", je.getMessage()); + out.printf("{\"error\":\"%s\"}\n", Encode.forHtmlContent(je.getMessage())); } finally { out.close(); diff --git a/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java b/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java index dec916e..bf8c7b7 100644 --- a/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java @@ -30,6 +30,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Level; import org.apache.log4j.LogManager; +import org.owasp.encoder.Encode; /** @@ -99,7 +100,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); - response.getOutputStream().print("{\"level\":\""+ currentLevel +"\"}"); + response.getOutputStream().print("{\"level\":\""+ Encode.forHtmlContent(currentLevel) +"\"}"); } } /** diff --git a/src/main/java/com/telefonica/iot/perseo/RulesServlet.java b/src/main/java/com/telefonica/iot/perseo/RulesServlet.java index 90bdc9c..2fc5372 100644 --- a/src/main/java/com/telefonica/iot/perseo/RulesServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/RulesServlet.java @@ -31,6 +31,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.MDC; +import org.owasp.encoder.Encode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -90,7 +91,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) ruleName = ruleName == null ? "/" : ruleName; Result r = RulesManager.get(epService, ruleName.substring(1)); response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); + out.println(Encode.forHtmlContent(r.getMessage())); out.close(); } @@ -116,7 +117,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.make(epService, body); response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); + out.println(Encode.forHtmlContent(r.getMessage())); out.close(); } @@ -142,7 +143,7 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.updateAll(epService, body); response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); + out.println(Encode.forHtmlContent(r.getMessage())); out.close(); } @@ -178,7 +179,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response TimeRulesStore.getInstance().removeTimeRule(ruleName.substring(1)); response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); + out.println(Encode.forHtmlContent(r.getMessage())); out.close(); } From 149d591f8fc33d394dce58870a455ca15d1c022b Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Tue, 26 Feb 2019 13:18:48 +0100 Subject: [PATCH 16/51] Fixed issue #284627 in pom.xml --- pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pom.xml b/pom.xml index bf8cedc..a67672d 100644 --- a/pom.xml +++ b/pom.xml @@ -67,6 +67,11 @@ commons-logging 1.2 + + org.owasp.encoder + encoder + 1.2.2 + From 5e43ec8bd84b1615ecc86b1dc6febca21e200d0b Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Wed, 27 Feb 2019 11:30:34 +0100 Subject: [PATCH 17/51] Fixed issue #284639 in src/main/java/com/telefonica/iot/perseo/Configuration.java src/main/resources/perseo-core.properties --- src/main/java/com/telefonica/iot/perseo/Configuration.java | 6 ++++-- src/main/resources/perseo-core.properties | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/Configuration.java b/src/main/java/com/telefonica/iot/perseo/Configuration.java index 90ba385..062cb81 100644 --- a/src/main/java/com/telefonica/iot/perseo/Configuration.java +++ b/src/main/java/com/telefonica/iot/perseo/Configuration.java @@ -24,6 +24,8 @@ import java.io.IOException; import java.io.InputStream; import java.util.Properties; +import java.util.ResourceBundle; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +47,7 @@ private Configuration() { private static final String PERSEO_MAX_AGE_ENV = "MAX_AGE"; private static final Properties PROPERTIES = new Properties(); - private static final String PATH = "/etc/perseo-core.properties"; + private static final String PATH = ResourceBundle.getBundle("perseo-core").getString("properties.path"); private static final String ACTION_URL_PROP = "action.url"; private static final String MAX_AGE_PROP = "rule.max_age"; @@ -67,7 +69,7 @@ public static synchronized boolean reload() { InputStream stream; String defaultMaxAge; String defaultURL; - String actionPath = "/actions/do"; + String actionPath = ResourceBundle.getBundle("perseo-core").getString("action.path"); // Check configuration file. If exist, set as default configuration for perseo-core try { diff --git a/src/main/resources/perseo-core.properties b/src/main/resources/perseo-core.properties index e424043..e577ac1 100644 --- a/src/main/resources/perseo-core.properties +++ b/src/main/resources/perseo-core.properties @@ -25,4 +25,5 @@ action.url = http://127.0.0.1:9090/actions/do # Time in milliseconds (long) to "expire" a "dangling" rule rule.max_age= 60000 - +properties.path = /etc/perseo-core.properties +action.path = /actions/do From dd1ad0ef1e5759dedf564cbc99f7adbe3c9ae7aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Tue, 19 Mar 2019 08:51:31 +0100 Subject: [PATCH 18/51] fixed issues EventsServlet.java #~290936 --- .../telefonica/iot/perseo/EventsServlet.java | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/EventsServlet.java b/src/main/java/com/telefonica/iot/perseo/EventsServlet.java index b7aeb31..281d49b 100644 --- a/src/main/java/com/telefonica/iot/perseo/EventsServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/EventsServlet.java @@ -42,7 +42,7 @@ public class EventsServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(EventsServlet.class); - EPServiceProvider epService; + private static EPServiceProvider epService; @Override public void init() { @@ -76,25 +76,27 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Utils.putCorrelatorAndTrans(request); logger.debug("events doPost"); response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json;charset=UTF-8"); - PrintWriter out = response.getWriter(); - try { - StringBuilder sb = new StringBuilder(); + response.setContentType("application/json;charset=UTF-8"); + try { String eventText = Utils.getBodyAsString(request); - logger.info("incoming event:" + eventText); + logger.info(String.format("incoming event: %s", eventText)); org.json.JSONObject jo = new JSONObject(eventText); - logger.debug("event as JSONObject: " + jo); + logger.debug(String.format("event as JSONObject: %s", jo)); Map eventMap = Utils.JSONObject2Map(jo); - logger.debug("event as map: " + eventMap); + logger.debug(String.format("event as map: %s" , eventMap)); epService.getEPRuntime().sendEvent(eventMap, Constants.IOT_EVENT); - logger.debug("event was sent: " + eventMap); - } catch (JSONException je) { - logger.error("error: " + je); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - out.printf("{\"error\":\"%s\"}\n", je.getMessage()); + logger.debug(String.format("event was sent: %s", eventMap)); + } catch (Exception je) { + try { + PrintWriter out = response.getWriter(); + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + out.printf("{\"error\":\"%s\"}%n", je.getMessage()); + out.close(); + }catch(IOException exception) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } - } finally { - out.close(); } } From 5852c9523367ed0bfc4b668853cc0c1cc98bcb44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Tue, 19 Mar 2019 08:55:12 +0100 Subject: [PATCH 19/51] fixed issues GenericListener #290956 --- .../com/telefonica/iot/perseo/GenericListener.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/GenericListener.java b/src/main/java/com/telefonica/iot/perseo/GenericListener.java index c9bf114..ba42a83 100644 --- a/src/main/java/com/telefonica/iot/perseo/GenericListener.java +++ b/src/main/java/com/telefonica/iot/perseo/GenericListener.java @@ -49,8 +49,7 @@ public class GenericListener implements UpdateListener { */ @Override public void update(EventBean[] newEvents, EventBean[] oldEvents) { - try { - HashMap rules = TimeRulesStore.getInstance().getAllRulesInfo(); + try { for (EventBean event : newEvents) { JSONObject jo = Utils.Event2JSONObject(event); @@ -64,15 +63,15 @@ public void update(EventBean[] newEvents, EventBean[] oldEvents) { // Is a timed Rule. Set special headers using rule saved information Utils.setTimerRuleHeaders(rule); - LOGGER.info("Firing temporal rule: " + event); + LOGGER.info(String.format("Firing temporal rule: %s",event)); } else { - LOGGER.info("Firing Rule: " + event); + LOGGER.info(String.format("Firing Rule: %s",event)); } - LOGGER.debug("result errors: " + jo.optJSONObject("errors")); - LOGGER.debug("result json: " + jo); + LOGGER.debug(String.format("result errors: %s",jo.optJSONObject("errors"))); + LOGGER.debug(String.format("result json: %s", jo)); boolean ok = Utils.DoHTTPPost(Configuration.getActionURL(), jo.toString()); if (!ok) { @@ -80,7 +79,7 @@ public void update(EventBean[] newEvents, EventBean[] oldEvents) { } } } catch (PropertyAccessException pae) { - LOGGER.error("doing action " + pae); + LOGGER.error(String.format("doing action %s",pae)); } } } From 0ac3d7e4b6e5e71530368821ea0fb3f5b5531adc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Tue, 19 Mar 2019 15:30:49 +0100 Subject: [PATCH 20/51] #291109 --- .../telefonica/iot/perseo/RulesServlet.java | 125 +++++++++++------- 1 file changed, 77 insertions(+), 48 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/RulesServlet.java b/src/main/java/com/telefonica/iot/perseo/RulesServlet.java index 90bdc9c..75eadf3 100644 --- a/src/main/java/com/telefonica/iot/perseo/RulesServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/RulesServlet.java @@ -42,7 +42,7 @@ public class RulesServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(RulesServlet.class); - EPServiceProvider epService; + private static EPServiceProvider epService; @Override public void init() throws ServletException { @@ -81,17 +81,23 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - PrintWriter out = response.getWriter(); - logger.info("get rule " + request.getPathInfo()); - String ruleName = request.getPathInfo(); - //request.getPathInfo() returns null or the extra path information - //that follows the servlet path but precedes the query string and will - //start with a "/" character. So, we remove it with .substring(1) - ruleName = ruleName == null ? "/" : ruleName; - Result r = RulesManager.get(epService, ruleName.substring(1)); - response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); - out.close(); + + try { + PrintWriter out = response.getWriter(); + logger.info(String.format("get rule %s", request.getPathInfo())); + String ruleName = request.getPathInfo(); + //request.getPathInfo() returns null or the extra path information + //that follows the servlet path but precedes the query string and will + //start with a "/" character. So, we remove it with .substring(1) + ruleName = ruleName == null ? "/" : ruleName; + Result r = RulesManager.get(epService, ruleName.substring(1)); + response.setStatus(r.getStatusCode()); + out.println(r.getMessage()); + out.close(); + }catch(Exception je) { + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } } @@ -108,16 +114,22 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - PrintWriter out = response.getWriter(); - String body = Utils.getBodyAsString(request); - - // Save temporary rules, not triggered by events external to the core - TimeRulesStore.getInstance().saveTimeRules(body); - - Result r = RulesManager.make(epService, body); - response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); - out.close(); + try { + PrintWriter out = response.getWriter(); + String body = Utils.getBodyAsString(request); + + // Save temporary rules, not triggered by events external to the core + TimeRulesStore.getInstance().saveTimeRules(body); + + Result r = RulesManager.make(epService, body); + response.setStatus(r.getStatusCode()); + out.println(r.getMessage()); + out.close(); + }catch(Exception je) { + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + } /** @@ -134,16 +146,26 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - PrintWriter out = response.getWriter(); - String body = Utils.getBodyAsString(request); + + try { + PrintWriter out = response.getWriter(); + String body = Utils.getBodyAsString(request); - // Save timed rules, which are not activated by events external to the core - TimeRulesStore.getInstance().saveTimeRules(body); + // Save timed rules, which are not activated by events external to the core + TimeRulesStore.getInstance().saveTimeRules(body); - Result r = RulesManager.updateAll(epService, body); - response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); - out.close(); + Result r = RulesManager.updateAll(epService, body); + response.setStatus(r.getStatusCode()); + out.println(r.getMessage()); + out.close(); + }catch(Exception je) { + PrintWriter outException = response.getWriter(); + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + outException.printf("{\"error\":\"%s\"}%n", je.getMessage()); + outException.close(); + + } } /** @@ -160,26 +182,33 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - PrintWriter out = response.getWriter(); - logger.info("delete rule " + request.getPathInfo()); - //request.getPathInfo() returns null or the extra path information - //that follows the servlet path but precedes the query string and will - //start with a "/" character. So, we remove it with .substring(1) - String ruleName = request.getPathInfo(); - if (ruleName == null) { - response.setStatus(400); - out.println("Deleting a rule require valid ruleName parameter"); + + try { + PrintWriter out = response.getWriter(); + logger.info(String.format("delete rule %s", request.getPathInfo())); + //request.getPathInfo() returns null or the extra path information + //that follows the servlet path but precedes the query string and will + //start with a "/" character. So, we remove it with .substring(1) + String ruleName = request.getPathInfo(); + if (ruleName == null) { + response.setStatus(400); + out.println("Deleting a rule require valid ruleName parameter"); + out.close(); + return; + } + Result r = RulesManager.delete(epService, ruleName.substring(1)); + + // Delete timed rule if necessary + TimeRulesStore.getInstance().removeTimeRule(ruleName.substring(1)); + + response.setStatus(r.getStatusCode()); + out.println(r.getMessage()); out.close(); - return; + }catch(Exception je) { + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } - Result r = RulesManager.delete(epService, ruleName.substring(1)); - - // Delete timed rule if necessary - TimeRulesStore.getInstance().removeTimeRule(ruleName.substring(1)); - - response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); - out.close(); } /** From e53c7ebd503f7c1dfd21b60659bc27b1b14ef97f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:32:33 +0100 Subject: [PATCH 21/51] fixed issues Configuration #291280 --- .../java/com/telefonica/iot/perseo/Configuration.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/Configuration.java b/src/main/java/com/telefonica/iot/perseo/Configuration.java index 90ba385..22aa87d 100644 --- a/src/main/java/com/telefonica/iot/perseo/Configuration.java +++ b/src/main/java/com/telefonica/iot/perseo/Configuration.java @@ -53,7 +53,7 @@ private Configuration() { private static long maxAge; static { - LOGGER.debug("Configuration init: " + reload()); + LOGGER.debug(String.format("Configuration init: %s",reload())); } /** @@ -95,10 +95,10 @@ public static synchronized boolean reload() { // Add actions/do path if perseoFeURLEnv not contains it yet actionRule = perseoFeURLEnv.contains(actionPath) ? perseoFeURLEnv : perseoFeURLEnv + actionPath; } else { - LOGGER.error("Invalid value for " + PERSEO_FE_URL_ENV + ": " + perseoFeURLEnv); + LOGGER.error(String.format("Invalid value for %s: %s",PERSEO_FE_URL_ENV, perseoFeURLEnv)); return false; } - LOGGER.info("actionRule configuration is: " + actionRule); + LOGGER.info(String.format("actionRule configuration is: %s",actionRule)); // Get MAX_AGE from env var if exist, else default String maxAgeEnv = System.getenv(PERSEO_MAX_AGE_ENV); @@ -106,10 +106,10 @@ public static synchronized boolean reload() { try { maxAge = maxAgeEnv != null ? Long.parseLong(maxAgeEnv) : Long.parseLong(defaultMaxAge); } catch (NumberFormatException nfe) { - LOGGER.error("Invalid value for " + PERSEO_MAX_AGE_ENV + ": " + nfe); + LOGGER.error(String.format("Invalid value for %s: %s",PERSEO_MAX_AGE_ENV,nfe)); return false; } - LOGGER.info("maxAge configuration is: " + maxAge); + LOGGER.info(String.format("maxAge configuration is: %s",maxAge)); return true; } From 4eb356cd7834b196637f37627ecd0b64300f1e28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:33:38 +0100 Subject: [PATCH 22/51] fixed issues EventsServlet #290936 --- src/main/java/com/telefonica/iot/perseo/EventsServlet.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/EventsServlet.java b/src/main/java/com/telefonica/iot/perseo/EventsServlet.java index 281d49b..62ced42 100644 --- a/src/main/java/com/telefonica/iot/perseo/EventsServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/EventsServlet.java @@ -87,12 +87,10 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) epService.getEPRuntime().sendEvent(eventMap, Constants.IOT_EVENT); logger.debug(String.format("event was sent: %s", eventMap)); } catch (Exception je) { - try { - PrintWriter out = response.getWriter(); + try { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - out.printf("{\"error\":\"%s\"}%n", je.getMessage()); - out.close(); + response.getOutputStream().print(String.format("{\"error\":\"%s\"}%n", je.getMessage())); }catch(IOException exception) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } From 78835073e30f8df7cf9f3a507127305e2e697646 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:34:18 +0100 Subject: [PATCH 23/51] fixed issues LogLevelServlet #291283 --- .../iot/perseo/LogLevelServlet.java | 51 ++++++++++++------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java b/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java index dec916e..9bc2022 100644 --- a/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java @@ -65,21 +65,28 @@ public class LogLevelServlet extends HttpServlet { @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - String levelName = request.getParameter("level"); - logger.info("changing log level to " + levelName); - Level level = levels.get(levelName); - if (level == null) { - logger.error("invalid log level: " + levelName); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.getOutputStream().print("{\"errorMessage\":\"invalid log level\"}"); - return; + try { + String levelName = request.getParameter("level"); + logger.info(String.format("changing log level to %s",levelName)); + Level level = levels.get(levelName); + if (level == null) { + logger.error(String.format("invalid log level: %s",levelName)); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.getOutputStream().print("{\"errorMessage\":\"invalid log level\"}"); + return; + } + synchronized (mutex) { + LogManager.getRootLogger().setLevel(level); + } + response.setStatus(HttpServletResponse.SC_OK); + }catch(IOException e) { + logger.error("IOException in log level"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; } - synchronized (mutex) { - LogManager.getRootLogger().setLevel(level); - } - response.setStatus(HttpServletResponse.SC_OK); + } /** @@ -95,11 +102,17 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("getting log level"); synchronized (mutex) { - String currentLevel = LogManager.getRootLogger().getLevel().toString(); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - response.getOutputStream().print("{\"level\":\""+ currentLevel +"\"}"); + try { + String currentLevel = LogManager.getRootLogger().getLevel().toString(); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + response.setStatus(HttpServletResponse.SC_OK); + response.getOutputStream().print("{\"level\":\""+ currentLevel +"\"}"); + }catch(IOException e) { + logger.error("IOException in log level"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } } } /** From 1395a506aba6a70bafcdf32949b7a184abbcb49e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:34:59 +0100 Subject: [PATCH 24/51] fixed issues RulesManager #290959 --- .../telefonica/iot/perseo/RulesManager.java | 90 +++++++++---------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/RulesManager.java b/src/main/java/com/telefonica/iot/perseo/RulesManager.java index df53475..8262c6d 100644 --- a/src/main/java/com/telefonica/iot/perseo/RulesManager.java +++ b/src/main/java/com/telefonica/iot/perseo/RulesManager.java @@ -41,7 +41,7 @@ */ public class RulesManager { - private static final Logger logger = LoggerFactory.getLogger(RulesServlet.class); + private static final Logger logger = LoggerFactory.getLogger(RulesManager.class); /** * Get a rule by name @@ -54,7 +54,7 @@ public class RulesManager { public static synchronized Result get(EPServiceProvider epService, String ruleName) { try { - logger.debug("rule asked for: " + ruleName); + logger.debug(String.format("rule asked for: %s", ruleName)); ruleName = ruleName == null ? "" : ruleName; EPAdministrator epa = epService.getEPAdministrator(); @@ -62,7 +62,7 @@ public static synchronized Result get(EPServiceProvider epService, String ruleNa EPStatement st = epa.getStatement(ruleName); if (st == null) { return new Result(HttpServletResponse.SC_NOT_FOUND, - String.format("{\"error\":\"%s not found\"}\n", + String.format("{\"error\":\"%s not found\"}%n", ruleName)); } else { return new Result(HttpServletResponse.SC_OK, @@ -72,7 +72,7 @@ public static synchronized Result get(EPServiceProvider epService, String ruleNa String[] sttmntNames = epa.getStatementNames(); JSONArray ja = new JSONArray(); for (String name : sttmntNames) { - logger.debug("getting rule " + name); + logger.debug(String.format("getting rule %s", name)); EPStatement st = epa.getStatement(name); ja.put(Utils.Statement2JSONObject(st)); } @@ -80,9 +80,9 @@ public static synchronized Result get(EPServiceProvider epService, String ruleNa } } catch (EPException epe) { - logger.error("getting statement" + epe); + logger.error(String.format("getting statement %s", epe)); return new Result(HttpServletResponse.SC_BAD_REQUEST, - String.format("{\"error\":%s}\n", + String.format("{\"error\":%s}%n", JSONObject.valueToString(epe.getMessage()))); } } @@ -99,12 +99,12 @@ public static synchronized Result get(EPServiceProvider epService, String ruleNa public static synchronized Result make(EPServiceProvider epService, String text) { try { - logger.debug("rule text: " + text); + logger.debug(String.format("rule text: %s", text)); org.json.JSONObject jo = new JSONObject(text); - logger.debug("rule as JSONObject: " + jo); + logger.debug(String.format("rule as JSONObject: %s", jo)); String name = jo.optString("name", ""); - logger.info("post rule: " + name); + logger.info(String.format("post rule: %s",name)); if ("".equals(name.trim())) { return new Result(HttpServletResponse.SC_BAD_REQUEST, "{\"error\":\"missing name\"}"); @@ -114,44 +114,44 @@ public static synchronized Result make(EPServiceProvider epService, String text) return new Result(HttpServletResponse.SC_BAD_REQUEST, "{\"error\":\"missing text\"}"); } - logger.debug("statement name: " + name); - logger.debug("statement text: " + newEpl); + logger.debug(String.format("statement name: %s",name)); + logger.debug(String.format("statement text: %s",newEpl)); EPStatement statement; EPStatement prevStmnt = epService.getEPAdministrator().getStatement(name); if (prevStmnt == null) { - logger.debug("found new statement: " + name); + logger.debug(String.format("found new statement: %s",name)); statement = epService.getEPAdministrator().createEPL(newEpl, name); - logger.debug("statement json: " + Utils.Statement2JSONObject(statement)); + logger.debug(String.format("statement json: %s", Utils.Statement2JSONObject(statement))); statement.addListener(new GenericListener()); } else { String oldEpl = prevStmnt.getText(); - logger.debug("old epl: " + oldEpl); + logger.debug(String.format("old epl: %s", oldEpl)); if (!newEpl.equals(oldEpl)) { - logger.debug("found changed statement: " + name); + logger.debug(String.format("found changed statement: %s",name)); prevStmnt.destroy(); - logger.debug("deleted statement: " + name); + logger.debug(String.format("deleted statement: %s",name)); statement = epService.getEPAdministrator().createEPL(newEpl, name); - logger.debug("re-created statement: " + name); - logger.debug("statement json: " + Utils.Statement2JSONObject(statement)); + logger.debug(String.format("re-created statement: %s", name)); + logger.debug(String.format("statement json: %s", Utils.Statement2JSONObject(statement))); statement.addListener(new GenericListener()); } else { - logger.debug("found repeated statement: " + name); + logger.debug(String.format("found repeated statement: %s", name)); statement = prevStmnt; } } return new Result(HttpServletResponse.SC_OK, Utils.Statement2JSONObject(statement).toString()); } catch (EPException epe) { - logger.error("creating statement " + epe); + logger.error(String.format("creating statement %s", epe)); return new Result(HttpServletResponse.SC_BAD_REQUEST, - String.format("{\"error\":%s}\n", + String.format("{\"error\":%s}%n", JSONObject.valueToString(epe.getMessage()))); } catch (JSONException je) { - logger.error("creating statement " + je); + logger.error(String.format("creating statement %s",je)); return new Result(HttpServletResponse.SC_BAD_REQUEST, - String.format("{\"error\":%s}\n", + String.format("{\"error\":%s}%n", JSONObject.valueToString(je.getMessage()))); } } @@ -170,10 +170,10 @@ public static synchronized Result make(EPServiceProvider epService, String text) public static synchronized Result updateAll(EPServiceProvider epService, String text) { try { long maxAge = Configuration.getMaxAge(); - logger.debug("rule block text: " + text); + logger.debug(String.format("rule block text: %s",text)); org.json.JSONArray ja = new JSONArray(text); - logger.debug("rules as JSONArray: " + ja); - logger.info("put rules+contexts: " + ja.length()); + logger.debug(String.format("rules as JSONArray: %s", ja)); + logger.info(String.format("put rules+contexts: %s", ja.length())); Map newOnes = new LinkedHashMap(); Set oldOnesNames = new HashSet(); @@ -198,23 +198,23 @@ public static synchronized Result updateAll(EPServiceProvider epService, String for (String n : newOnes.keySet()) { String newEpl = newOnes.get(n); if (!oldOnesNames.contains(n)) { - logger.debug("found new statement: " + n); + logger.debug(String.format("found new statement: %s", n)); EPStatement statement = epService.getEPAdministrator().createEPL(newEpl, n); - logger.debug("statement json: " + Utils.Statement2JSONObject(statement)); + logger.debug(String.format("statement json: %s", Utils.Statement2JSONObject(statement))); statement.addListener(new GenericListener()); } else { EPStatement prevStmnt = epService.getEPAdministrator().getStatement(n); String oldEPL = prevStmnt.getText(); if (!oldEPL.equals(newOnes.get(n))) { - logger.debug("found changed statement: " + n); + logger.debug(String.format("found changed statement: %s", n)); prevStmnt.destroy(); - logger.debug("deleted statement: " + n); + logger.debug(String.format("deleted statement: %s", n)); EPStatement statement = epService.getEPAdministrator().createEPL(newEpl, n); - logger.debug("re-created statement: " + n); - logger.debug("statement json: " + Utils.Statement2JSONObject(statement)); + logger.debug(String.format("re-created statement: %s" ,n)); + logger.debug(String.format("statement json: %s", Utils.Statement2JSONObject(statement))); statement.addListener(new GenericListener()); } else { - logger.debug("identical statement: " + n); + logger.debug(String.format("identical statement: %s", n)); } oldOnesNames.remove(n); } @@ -222,23 +222,23 @@ public static synchronized Result updateAll(EPServiceProvider epService, String //Delete oldOnes if they are old enough for (String o : oldOnesNames) { EPStatement prevStmnt = epService.getEPAdministrator().getStatement(o); - logger.debug("unexpected statement: " + o); + logger.debug(String.format("unexpected statement: %s" ,o)); if (prevStmnt.getTimeLastStateChange() < now - maxAge) { - logger.debug("unexpected statement, too old: " + o); + logger.debug(String.format("unexpected statement, too old: %s", o)); prevStmnt.destroy(); - logger.debug("deleted garbage statement: " + o); + logger.debug(String.format("deleted garbage statement: %s", o)); } } return new Result(HttpServletResponse.SC_OK, "{}"); } catch (EPException epe) { - logger.error("creating statement " + epe); + logger.error(String.format("creating statement %s", epe)); return new Result(HttpServletResponse.SC_BAD_REQUEST, - String.format("{\"error\":%s}\n", + String.format("{\"error\":%s}%n", JSONObject.valueToString(epe.getMessage()))); } catch (JSONException je) { - logger.error("creating statement " + je); + logger.error(String.format("creating statement %s", je)); return new Result(HttpServletResponse.SC_BAD_REQUEST, - String.format("{\"error\":%s}\n", + String.format("{\"error\":%s}%n", JSONObject.valueToString(je.getMessage()))); } } @@ -256,19 +256,19 @@ public static synchronized Result delete(EPServiceProvider epService, String rul try { ruleName = ruleName == null ? "" : ruleName; - logger.debug("delete rule: " + ruleName); + logger.debug(String.format("delete rule: %s" ,ruleName)); EPAdministrator epa = epService.getEPAdministrator(); if (ruleName.length() != 0) { EPStatement st = epa.getStatement(ruleName); //Allow to delete inexistent rule if (st != null) { - logger.debug("deleted statement: " + ruleName); + logger.debug(String.format("deleted statement: %s", ruleName)); st.destroy(); return new Result(HttpServletResponse.SC_OK, Utils.Statement2JSONObject(st).toString()); } else { - logger.debug("asked for deleting inexistent statement: " + ruleName); + logger.debug(String.format("asked for deleting inexistent statement: %s",ruleName)); return new Result(HttpServletResponse.SC_OK, "{}"); } @@ -277,9 +277,9 @@ public static synchronized Result delete(EPServiceProvider epService, String rul } } catch (EPException epe) { - logger.error("deleting statement " + epe); + logger.error(String.format("deleting statement %s", epe)); return new Result(HttpServletResponse.SC_BAD_REQUEST, - String.format("{\"error\":%s}\n", + String.format("{\"error\":%s}%n", JSONObject.valueToString(epe.getMessage()))); } } From b5103931e6ae22775788ff183985bc20ac1793be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:35:48 +0100 Subject: [PATCH 25/51] fixed issues RulesServlet #291109 --- .../telefonica/iot/perseo/RulesServlet.java | 33 +++++++------------ 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/RulesServlet.java b/src/main/java/com/telefonica/iot/perseo/RulesServlet.java index 75eadf3..c7d28fc 100644 --- a/src/main/java/com/telefonica/iot/perseo/RulesServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/RulesServlet.java @@ -82,8 +82,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - try { - PrintWriter out = response.getWriter(); + try { logger.info(String.format("get rule %s", request.getPathInfo())); String ruleName = request.getPathInfo(); //request.getPathInfo() returns null or the extra path information @@ -92,8 +91,8 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) ruleName = ruleName == null ? "/" : ruleName; Result r = RulesManager.get(epService, ruleName.substring(1)); response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); - out.close(); + response.getOutputStream().print(r.getMessage()); + }catch(Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); @@ -115,7 +114,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); try { - PrintWriter out = response.getWriter(); + String body = Utils.getBodyAsString(request); // Save temporary rules, not triggered by events external to the core @@ -123,8 +122,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.make(epService, body); response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); - out.close(); + response.getOutputStream().print(r.getMessage()); }catch(Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); @@ -148,7 +146,7 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) response.setContentType("application/json;charset=UTF-8"); try { - PrintWriter out = response.getWriter(); + String body = Utils.getBodyAsString(request); // Save timed rules, which are not activated by events external to the core @@ -156,15 +154,10 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.updateAll(epService, body); response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); - out.close(); - }catch(Exception je) { - PrintWriter outException = response.getWriter(); + response.getOutputStream().print(r.getMessage()); + }catch(Exception je) { logger.error(String.format("error: %s" ,je)); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - outException.printf("{\"error\":\"%s\"}%n", je.getMessage()); - outException.close(); - + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } @@ -184,7 +177,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response response.setContentType("application/json;charset=UTF-8"); try { - PrintWriter out = response.getWriter(); + logger.info(String.format("delete rule %s", request.getPathInfo())); //request.getPathInfo() returns null or the extra path information //that follows the servlet path but precedes the query string and will @@ -192,8 +185,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response String ruleName = request.getPathInfo(); if (ruleName == null) { response.setStatus(400); - out.println("Deleting a rule require valid ruleName parameter"); - out.close(); + response.getOutputStream().print("Deleting a rule require valid ruleName parameter"); return; } Result r = RulesManager.delete(epService, ruleName.substring(1)); @@ -202,8 +194,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response TimeRulesStore.getInstance().removeTimeRule(ruleName.substring(1)); response.setStatus(r.getStatusCode()); - out.println(r.getMessage()); - out.close(); + response.getOutputStream().print(r.getMessage()); }catch(Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); From 4ddbdb4b2ba10998f848ba00625452ff948dca3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:36:31 +0100 Subject: [PATCH 26/51] fixed issues TimeRulesStore #291284 --- .../java/com/telefonica/iot/perseo/TimeRulesStore.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/TimeRulesStore.java b/src/main/java/com/telefonica/iot/perseo/TimeRulesStore.java index a1e7e67..8f07f35 100644 --- a/src/main/java/com/telefonica/iot/perseo/TimeRulesStore.java +++ b/src/main/java/com/telefonica/iot/perseo/TimeRulesStore.java @@ -57,7 +57,7 @@ public static TimeRulesStore getInstance() { * @param body POST or PUT body with rules data */ public void saveTimeRules(String body) { - LOGGER.debug("Saving timerules from body: " + body); + LOGGER.debug(String.format("Saving timerules from body: %s", body)); if (body.equals("")) { return; } else { @@ -81,10 +81,10 @@ public void saveTimeRules(String body) { ruleText = (String) jo.getJSONObject(i).get("text"); } catch (JSONException e) { // Invalid Rule - LOGGER.error("invalid rule " + i + " by: " + e.getMessage()); + LOGGER.error(String.format("invalid rule %s by %s", i,e.getMessage())); continue; } - LOGGER.debug("Checking rule " + i + ": " + strName); + LOGGER.debug(String.format("Checking rule %s: %s",i, strName)); // Only "Timed Rules" if (!strName.startsWith("ctxt$") && isTimeRule(ruleText)) { @@ -95,7 +95,7 @@ public void saveTimeRules(String body) { context.remove(0); jo.getJSONObject(i).put("subservice", "/" + String.join("/", context)); rulesInfo.put(ruleName.get(0), jo.getJSONObject(i)); - LOGGER.info("Time rule " + i + " " + ruleName + " added"); + LOGGER.info(String.format("Time rule %s %s added",i, ruleName)); } } } @@ -146,7 +146,7 @@ public JSONObject getRuleInfo(String ruleName) { * @param ruleName The rule name. Can include optionally '@context...' in the name */ public void removeTimeRule(String ruleName) { - LOGGER.info("Removing timerule: " + ruleName); + LOGGER.info(String.format("Removing timerule: %s",ruleName)); if (ruleName != null) { rulesInfo.remove(ruleName.split("@")[0]); } From 6e26193f83f9346687f43904f4189b663f41f77f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:37:53 +0100 Subject: [PATCH 27/51] fixed issues Utils #~91285 --- src/main/java/com/telefonica/iot/perseo/Utils.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/telefonica/iot/perseo/Utils.java b/src/main/java/com/telefonica/iot/perseo/Utils.java index a1c8c05..0121e80 100644 --- a/src/main/java/com/telefonica/iot/perseo/Utils.java +++ b/src/main/java/com/telefonica/iot/perseo/Utils.java @@ -187,31 +187,31 @@ public static boolean DoHTTPPost(String urlStr, String content) { int code = urlConn.getResponseCode(); String message = urlConn.getResponseMessage(); - logger.debug("action http response " + code + " " + message); + logger.debug(String.format("action http response %s %s",code,message)); if (code / 100 == 2) { InputStream input = urlConn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); for (String line; (line = reader.readLine()) != null;) { - logger.info("action response body: " + line); + logger.info(String.format("action response body: %s", line)); } input.close(); return true; } else { - logger.error("action response is not OK: " + code + " " + message); + logger.error(String.format("action response is not OK: %s %s",code,message)); InputStream error = urlConn.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(error)); for (String line; (line = reader.readLine()) != null;) { - logger.error("action error response body: " + line); + logger.error(String.format("action error response body: %s", line)); } error.close(); return false; } } catch (MalformedURLException me) { - logger.error("exception MalformedURLException: " + me); + logger.error(String.format("exception MalformedURLException: %s",me)); return false; } catch (IOException ioe) { - logger.error("exception IOException: " + ioe); + logger.error(String.format("exception IOException: %s",ioe)); return false; } } @@ -260,7 +260,7 @@ public static void putCorrelatorAndTrans(HttpServletRequest req) { * */ public static String getBodyAsString(HttpServletRequest request) throws IOException { - logger.debug("request.getCharacterEncoding() " + request.getCharacterEncoding()); + logger.debug(String.format("request.getCharacterEncoding() %s", request.getCharacterEncoding())); if (request.getCharacterEncoding() == null) { request.setCharacterEncoding("UTF-8"); } From 5adca52c68a659ec157180bd36ab7c12ffd92592 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:38:50 +0100 Subject: [PATCH 28/51] fixed issues JSONArray #291298 --- src/main/java/org/json/JSONArray.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index 3f05548..04e2d34 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -889,7 +889,7 @@ public String toString() { try { return this.toString(0); } catch (Exception e) { - return null; + return ""; } } From f73d8f127a0dba9f552bd8468b0a61904dfca286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:39:21 +0100 Subject: [PATCH 29/51] fixed issues JSONObject #291299 --- src/main/java/org/json/JSONObject.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 45f92bc..483f514 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -135,6 +135,16 @@ protected final Object clone() { public boolean equals(Object object) { return object == null || object == this; } + + /** + * A Null object in Java always has hashCode 0. + * + * @return 0. + */ + @Override + public int hashCode() { + return 0; + } /** * Get the "null" string value. @@ -1330,7 +1340,7 @@ public boolean similar(Object other) { } } return true; - } catch (Throwable exception) { + } catch (JSONException exception) { return false; } } @@ -1450,7 +1460,7 @@ public String toString() { try { return this.toString(0); } catch (Exception e) { - return null; + return ""; } } @@ -1500,7 +1510,7 @@ public String toString(int indentFactor) throws JSONException { * If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { - if (value == null || value.equals(null)) { + if (value == null) { return "null"; } if (value instanceof JSONString) { @@ -1599,7 +1609,7 @@ public Writer write(Writer writer) throws JSONException { static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException { - if (value == null || value.equals(null)) { + if (value == null) { writer.write("null"); } else if (value instanceof JSONObject) { ((JSONObject) value).write(writer, indentFactor, indent); From d08fdcd46cd6273180fbb58b741f1fcc11664e2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:41:09 +0100 Subject: [PATCH 30/51] fixed issues Kim 291301 --- src/main/java/org/json/Kim.java | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/json/Kim.java b/src/main/java/org/json/Kim.java index e842148..5456112 100644 --- a/src/main/java/org/json/Kim.java +++ b/src/main/java/org/json/Kim.java @@ -159,7 +159,8 @@ public Kim(String string) throws JSONException { // to UTF-32 conversion, and then the UTF-32 to Kim conversion. if (stringLength > 0) { - for (int i = 0; i < stringLength; i += 1) { + int i = 0; + while (i < stringLength) { int c = string.charAt(i); if (c <= 0x7F) { this.length += 1; @@ -175,6 +176,7 @@ public Kim(String string) throws JSONException { } this.length += 3; } + i += 1; } // Second pass: Allocate a byte array and fill that array with the conversion @@ -184,8 +186,9 @@ public Kim(String string) throws JSONException { int at = 0; int b; int sum = 1; - for (int i = 0; i < stringLength; i += 1) { - int character = string.charAt(i); + int x = 0; + while (x < stringLength) { + int character = string.charAt(x); if (character <= 0x7F) { bytes[at] = (byte) character; sum += character; @@ -204,7 +207,7 @@ public Kim(String string) throws JSONException { at += 1; } else { if (character >= 0xD800 && character <= 0xDBFF) { - i += 1; + x += 1; character = (((character & 0x3FF) << 10) | (string .charAt(i) & 0x3FF)) + 65536; } @@ -224,6 +227,7 @@ public Kim(String string) throws JSONException { this.hashcode += sum; at += 1; } + x += 1; } this.hashcode += sum << 16; } @@ -351,21 +355,21 @@ public int hashCode() { public String toString() throws JSONException { if (this.string == null) { int c; - int length = 0; + int charLength = 0; char chars[] = new char[this.length]; for (int at = 0; at < this.length; at += characterSize(c)) { c = this.characterAt(at); if (c < 0x10000) { - chars[length] = (char) c; - length += 1; + chars[charLength] = (char) c; + charLength += 1; } else { - chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10)); - length += 1; - chars[length] = (char) (0xDC00 | (c & 0x03FF)); - length += 1; + chars[charLength] = (char) (0xD800 | ((c - 0x10000) >>> 10)); + charLength += 1; + chars[charLength] = (char) (0xDC00 | (c & 0x03FF)); + charLength += 1; } } - this.string = new String(chars, 0, length); + this.string = new String(chars, 0, charLength); } return this.string; } From b694d53c86caee64991b67039001f05b5d84f0e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:42:05 +0100 Subject: [PATCH 31/51] fixed issues EventsServletTest #291302 --- .../com/telefonica/iot/perseo/EventsServletTest.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java b/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java index 6beddb8..1792f52 100644 --- a/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java +++ b/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java @@ -26,6 +26,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import static org.junit.Assert.*; /** @@ -33,7 +36,7 @@ * @author brox */ public class EventsServletTest { - + private static final Logger logger = LoggerFactory.getLogger(EventsServletTest.class); public EventsServletTest() { } @@ -59,12 +62,12 @@ public void tearDown() { */ @Test public void testDoPost() throws Exception { - System.out.println("doPost"); + logger.info("doPost"); Server server = Help.getServer(EventsServlet.class); server.start(); try { String url = String.format("http://127.0.0.1:%d", Help.PORT); - Help.Res r = Help.sendPost(url, Help.ExampleNotices[0]); + Help.Res r = Help.sendPost(url, Help.ExampleNotices()[0]); assertEquals(200, r.getCode()); r = Help.sendPost(url, "<>"); assertEquals(400, r.getCode()); From ed78f2fa8ca769fda9abf9af98055e3e8b4ab1da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:43:16 +0100 Subject: [PATCH 32/51] fixed issues GenericListenerTest #291303 --- .../com/telefonica/iot/perseo/GenericListenerTest.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java b/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java index 793d54e..4e48668 100644 --- a/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java +++ b/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java @@ -31,6 +31,8 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -38,7 +40,7 @@ * @author brox */ public class GenericListenerTest { - + private static final Logger logger = LoggerFactory.getLogger(GenericListenerTest.class); public GenericListenerTest() { } @@ -63,7 +65,7 @@ public void tearDown() { */ @Test public void testUpdate() { - System.out.println("update"); + logger.info("update"); EventBean[] newEvents = new EventBean[0]; EventBean[] oldEvents = new EventBean[0]; GenericListener instance = new GenericListener(); @@ -81,7 +83,7 @@ public void testUpdate() { */ @Test public void testUpdateTimerRule() { - System.out.println("update with timed rule"); + logger.info("update with timed rule"); // Add RuleTest in TimeRulesStore Singleton TimeRulesStore tRInfoInstance = TimeRulesStore.getInstance(); tRInfoInstance.cleanAllRules(); From 8e42d0e29b86d640c6a12d09db5b6de0f3418e85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:43:47 +0100 Subject: [PATCH 33/51] fixed issues LogLevelServletTest #291304 --- .../com/telefonica/iot/perseo/LogLevelServletTest.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java b/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java index eb7fb7e..a3a3bd0 100644 --- a/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java +++ b/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java @@ -29,13 +29,16 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * * @author brox */ public class LogLevelServletTest { - + + private static final Logger logger = LoggerFactory.getLogger(LogLevelServletTest.class); public LogLevelServletTest() { } @@ -62,7 +65,7 @@ public void tearDown() { */ @Test public void testDoPutOK() throws Exception { - System.out.println("doPut log level valid"); + logger.info("doPut log level valid"); Server server = Help.getServer(LogLevelServlet.class); server.start(); try { @@ -84,7 +87,7 @@ public void testDoPutOK() throws Exception { */ @Test public void testDoPutBad() throws Exception { - System.out.println("doPut log level invalid"); + logger.info("doPut log level invalid"); Server server = Help.getServer(LogLevelServlet.class); server.start(); try { From f94f1bfee5438afb0bd752d85a1f62e30c670ca8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:44:23 +0100 Subject: [PATCH 34/51] fixed issues RulesManagerTest #291305 --- .../iot/perseo/RulesManagerTest.java | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java b/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java index db10b0a..ea9d9e1 100644 --- a/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java +++ b/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java @@ -31,6 +31,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import static org.junit.Assert.*; /** @@ -40,7 +43,7 @@ public class RulesManagerTest { EPServiceProvider epService; - + private static final Logger logger = LoggerFactory.getLogger(RulesManagerTest.class); public RulesManagerTest() { epService = EPServiceProviderManager.getDefaultProvider(); @@ -76,9 +79,9 @@ public void tearDown() { */ @Test public void testGet() { - System.out.println("get"); + logger.info("get"); String ruleName = "ccc"; - String epl = Help.ExampleRules[0]; + String epl = Help.ExampleRules()[0]; EPStatement st = epService.getEPAdministrator().createEPL(epl, ruleName); Result result = RulesManager.get(epService, ruleName); assertEquals(200, result.getStatusCode()); @@ -93,9 +96,9 @@ public void testGet() { */ @Test public void testMake() { - System.out.println("make"); + logger.info("make"); String ruleName = "ccc"; - String epl = Help.ExampleRules[0]; + String epl = Help.ExampleRules()[0]; String text = String.format("{\"name\":\"%s\",\"text\":\"%s\"}", ruleName, epl); Result result = RulesManager.make(epService, text); @@ -110,9 +113,9 @@ public void testMake() { */ @Test public void testUpdateAll() { - System.out.println("updateAll"); + logger.info("updateAll"); String ruleName = "ccc"; - String epl = Help.ExampleRules[0]; + String epl = Help.ExampleRules()[0]; String text = String.format("[{\"name\":\"%s\",\"text\":\"%s\"}]", ruleName, epl); Result result = RulesManager.updateAll(epService, text); @@ -130,9 +133,9 @@ public void testUpdateAll() { */ @Test public void testDelete() { - System.out.println("delete"); + logger.info("delete"); String ruleName = "ccc"; - String epl = Help.ExampleRules[0]; + String epl = Help.ExampleRules()[0]; EPStatement st = epService.getEPAdministrator().createEPL(epl, ruleName); assertNotNull(st); Result result = RulesManager.delete(epService, ruleName); From b38f18b3cc1f829319d7aeda2d58f551ce172fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:48:13 +0100 Subject: [PATCH 35/51] fixed issues TimeRulesStoreTest #291306 --- .../iot/perseo/RulesServletTest.java | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java b/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java index 424fa07..3354ff2 100644 --- a/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java +++ b/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java @@ -24,6 +24,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import static org.junit.Assert.*; import org.eclipse.jetty.server.Server; @@ -36,7 +39,7 @@ * @author brox */ public class RulesServletTest { - + private static final Logger logger = LoggerFactory.getLogger(RulesServletTest.class); public RulesServletTest() { } @@ -62,7 +65,7 @@ public void tearDown() { */ @Test public void testDoGet() throws Exception { - System.out.println("doGet"); + logger.info("doGet"); Server server = Help.getServer(RulesServlet.class); server.start(); try { @@ -83,14 +86,14 @@ public void testDoGet() throws Exception { */ @Test public void testDoPost() throws Exception { - System.out.println("doPost"); + logger.info("doPost"); Server server = Help.getServer(RulesServlet.class); server.start(); try { String url = String.format("http://127.0.0.1:%d", Help.PORT); JSONObject jr = new JSONObject(); jr.put("name", "test doPost rule"); - jr.put("text", Help.ExampleRules[0]); + jr.put("text", Help.ExampleRules()[0]); Help.Res r = Help.sendPost(url, jr.toString(2)); assertEquals(200,r.getCode()); jr.remove("name"); @@ -111,7 +114,7 @@ public void testDoPost() throws Exception { */ @Test public void testDoPut() throws Exception { - System.out.println("doPut"); + logger.info("doPut"); Server server = Help.getServer(RulesServlet.class); server.start(); try { @@ -119,11 +122,11 @@ public void testDoPut() throws Exception { JSONArray ja = new JSONArray(); JSONObject jr = new JSONObject(); jr.put("name", "test doPost rule 1"); - jr.put("text", Help.ExampleRules[0]); + jr.put("text", Help.ExampleRules()[0]); ja.put(jr); jr = new JSONObject(); jr.put("name", "test doPost rule 2"); - jr.put("text", Help.ExampleRules[1]); + jr.put("text", Help.ExampleRules()[1]); Help.Res r = Help.sendPut(url, ja.toString(2)); assertEquals(200, r.getCode()); } finally { @@ -139,13 +142,13 @@ public void testDoPut() throws Exception { */ @Test public void testDoPutLongSet() throws Exception { - System.out.println("doPutLongSet"); + logger.info("doPutLongSet"); Server server = Help.getServer(RulesServlet.class); server.start(); try { String url = String.format("http://127.0.0.1:%d", Help.PORT); String longSet = Help.longRuleSet(); - System.out.println("doPutLongSet set size=" + longSet.length()); + logger.info(String.format("doPutLongSet set size=%s", longSet.length())); Help.Res r = Help.sendPut(url, longSet); assertEquals(200, r.getCode()); } finally { @@ -159,7 +162,7 @@ public void testDoPutLongSet() throws Exception { */ @Test public void testDoDelete() throws Exception { - System.out.println("doDelete"); + logger.info("doDelete"); Server server = Help.getServer(RulesServlet.class); server.start(); try { From 5491d95da2da95afc69e71c12cab47806a77ecdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:49:03 +0100 Subject: [PATCH 36/51] fixed issues TimeRulesStoreTest #291306 --- .../com/telefonica/iot/perseo/TimeRulesStoreTest.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java b/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java index 001cc37..78edd85 100644 --- a/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java +++ b/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java @@ -29,6 +29,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import static org.junit.Assert.*; /** @@ -38,7 +41,8 @@ public class TimeRulesStoreTest { private TimeRulesStore instance = TimeRulesStore.getInstance(); - + private static final Logger LOGGER = LoggerFactory.getLogger(TimeRulesStoreTest.class); + public TimeRulesStoreTest() { } @@ -68,7 +72,7 @@ public void testGetEmptyRuleMap() { HashMap emptyHasmap = new HashMap(); HashMap result = instance.getAllRulesInfo(); - System.out.println("testing ------- " + result); + LOGGER.debug(String.format("testing ------- %s",result)); assertEquals(result, emptyHasmap); } From fb3005de43c882490b8aec81e73df57fc8f0755a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:50:57 +0100 Subject: [PATCH 37/51] fixed issues UtilsTest #291307 --- .../com/telefonica/iot/perseo/UtilsTest.java | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/test/java/com/telefonica/iot/perseo/UtilsTest.java b/src/test/java/com/telefonica/iot/perseo/UtilsTest.java index be2c6cc..ff9b9b5 100644 --- a/src/test/java/com/telefonica/iot/perseo/UtilsTest.java +++ b/src/test/java/com/telefonica/iot/perseo/UtilsTest.java @@ -36,7 +36,6 @@ import java.util.HashMap; import java.util.Map; import java.util.logging.Level; -import java.util.logging.Logger; import javax.servlet.ServletContext; import org.json.JSONObject; import org.junit.After; @@ -44,6 +43,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import static org.junit.Assert.*; /** @@ -51,7 +53,7 @@ * @author brox */ public class UtilsTest { - + private static final Logger logger = LoggerFactory.getLogger(UtilsTest.class); public UtilsTest() { } @@ -76,7 +78,7 @@ public void tearDown() { */ @Test public void testInitEPService() { - System.out.println("initEPService"); + logger.info("initEPService"); ServletContext sc = new ServletContextMock(); EPServiceProvider result = Utils.initEPService(sc); assertEquals(sc.getAttribute("epService"), result); @@ -91,7 +93,7 @@ public void testInitEPService() { */ @Test public void testDestroyEPService() { - System.out.println("destroyEPService"); + logger.info("destroyEPService"); ServletContextMock sc = new ServletContextMock(); //Empty sc Utils.destroyEPService(sc); @@ -107,7 +109,7 @@ public void testDestroyEPService() { */ @Test public void testJSONObject2Map() { - System.out.println("JSONObject2Map"); + logger.info("JSONObject2Map"); HashMap m = new HashMap(); m.put("one", "1"); m.put("two", 2); @@ -121,7 +123,7 @@ public void testJSONObject2Map() { */ @Test public void testEvent2JSONObject() { - System.out.println("Event2JSONObject"); + logger.info("Event2JSONObject"); HashMap m = new HashMap(); m.put("one", "1"); m.put("two", 2); @@ -136,9 +138,9 @@ public void testEvent2JSONObject() { */ @Test public void testStatement2JSONObject() { - final String epl = Help.ExampleRules[1]; + final String epl = Help.ExampleRules()[1]; final String name = "rule name"; - System.out.println("Statement2JSONObject"); + logger.info("Statement2JSONObject"); EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(); Map def = new HashMap(); def.put("id", String.class); @@ -161,7 +163,7 @@ public void testStatement2JSONObject() { */ @Test public void testDoHTTPPost() { - System.out.println("DoHTTPPost"); + logger.info("DoHTTPPost"); InetSocketAddress address = new InetSocketAddress(Help.PORT); HttpServer httpServer = null; try { @@ -188,7 +190,7 @@ public void handle(HttpExchange exchange) throws IOException { assertEquals(false, result); } catch (IOException ex) { - Logger.getLogger(UtilsTest.class.getName()).log(Level.SEVERE, null, ex); + logger.error(ex.toString()); fail(ex.toString()); } finally { if (httpServer != null) { From a17edf11dc65e55d693f0239ccdd24aff69d0ffc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 11:51:56 +0100 Subject: [PATCH 38/51] fixed issues Help.java #291308 --- .../com/telefonica/iot/perseo/test/Help.java | 67 +++++++++++-------- 1 file changed, 39 insertions(+), 28 deletions(-) diff --git a/src/test/java/com/telefonica/iot/perseo/test/Help.java b/src/test/java/com/telefonica/iot/perseo/test/Help.java index aa45bc4..11f00da 100644 --- a/src/test/java/com/telefonica/iot/perseo/test/Help.java +++ b/src/test/java/com/telefonica/iot/perseo/test/Help.java @@ -24,7 +24,10 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.lang.reflect.MalformedParametersException; import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; import java.net.URL; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; @@ -39,26 +42,34 @@ public class Help { public static final int PORT = 8129; - public static final String[] ExampleRules = new String[]{ - "select id, price? as Price from iotEvent.win:length(100) group by id", - "@Audit select *,\"blood_1_action\" as iotcepaction," - + "ev.BloodPressure? as Pression, ev.id? as Meter from pattern " - + "[every ev=iotEvent(cast(cast(BloodPressure?,String),float)>1.5" - + " and type=\"BloodMeter\")]"}; - public static final String[] ExampleNotices = new String[]{ - "{\n" - + "\"BloodPressure\": 2,\n" - + "\"id\":\"guay!\",\n" - + "\"otro\":\"mas\",\n" - + "\"numero\":4,\n" - + "\"sub\": {\n" - + " \"subnumero\":18,\n" - + " \"subcadena\":\"SUB2\",\n" - + " \"subflotante\": 12.3,\n" - + " \"sub2\": { \"valor\": 3}\n" - + " }\n" - + "}"}; - + + public static String[] ExampleRules() { + return new String[]{ + "select id, price? as Price from iotEvent.win:length(100) group by id", + "@Audit select *,\"blood_1_action\" as iotcepaction," + + "ev.BloodPressure? as Pression, ev.id? as Meter from pattern " + + "[every ev=iotEvent(cast(cast(BloodPressure?,String),float)>1.5" + + " and type=\"BloodMeter\")]"}; + + } + public static String[] ExampleNotices() { + return new String[]{ + "{\n" + + "\"BloodPressure\": 2,\n" + + "\"id\":\"guay!\",\n" + + "\"otro\":\"mas\",\n" + + "\"numero\":4,\n" + + "\"sub\": {\n" + + " \"subnumero\":18,\n" + + " \"subcadena\":\"SUB2\",\n" + + " \"subflotante\": 12.3,\n" + + " \"sub2\": { \"valor\": 3}\n" + + " }\n" + + "}"}; + + } + + public static class Res { private int code; @@ -90,15 +101,15 @@ public void setText(String text) { - public static Res doGet(String url) throws Exception { + public static Res doGet(String url) throws MalformedURLException, IOException, ProtocolException{ return doMethod(url, "GET"); } - public static Res doDelete(String url) throws Exception { + public static Res doDelete(String url) throws MalformedURLException, IOException, ProtocolException { return doMethod(url, "DELETE"); } - public static Res doMethod(String url, String method) throws Exception { + public static Res doMethod(String url, String method) throws MalformedURLException, IOException, ProtocolException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod(method); @@ -107,15 +118,15 @@ public static Res doMethod(String url, String method) throws Exception { return new Res(responseCode, body); } - public static Res sendPost(String url, String body) throws Exception { + public static Res sendPost(String url, String body) throws MalformedURLException, IOException, ProtocolException { return sendMethod(url, body, "POST"); } - public static Res sendPut(String url, String body) throws Exception { + public static Res sendPut(String url, String body) throws MalformedURLException, IOException, ProtocolException { return sendMethod(url, body, "PUT"); } - public static Res sendMethod(String url, String body, String method) throws Exception { + public static Res sendMethod(String url, String body, String method) throws MalformedURLException, IOException, ProtocolException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod(method); @@ -170,10 +181,10 @@ public static String longRuleSet() { JSONObject rule = new JSONObject(); for (int i = 0; i < ruleNumber; i++) { rule.put("name", "manyrules_a_" + i); - rule.put("text", ExampleRules[0]); + rule.put("text", ExampleRules()[0]); ja.put(rule); rule.put("name", "manyrules_b_" + i); - rule.put("text", ExampleRules[1]); + rule.put("text", ExampleRules()[1]); ja.put(rule); } return ja.toString(); From 9eb801a3a33b76e65ea0e0b02c93f7cb5296cd14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Fern=C3=A1ndez=20Bueno?= Date: Wed, 20 Mar 2019 12:26:10 +0100 Subject: [PATCH 39/51] merge with ci brunch --- pom.xml | 5 +++++ sonar-project.properties | 9 +++++++++ .../com/telefonica/iot/perseo/Configuration.java | 6 ++++-- .../java/com/telefonica/iot/perseo/Constants.java | 2 +- .../com/telefonica/iot/perseo/EventsServlet.java | 4 +++- .../com/telefonica/iot/perseo/LogLevelServlet.java | 2 ++ .../com/telefonica/iot/perseo/RulesServlet.java | 13 +++++++------ src/main/java/org/json/JSONTokener.java | 2 ++ src/main/java/org/json/XML.java | 3 ++- src/main/java/org/json/XMLTokener.java | 4 ++++ src/main/resources/perseo-core.properties | 3 ++- 11 files changed, 41 insertions(+), 12 deletions(-) create mode 100644 sonar-project.properties diff --git a/pom.xml b/pom.xml index a831034..db7bd3d 100644 --- a/pom.xml +++ b/pom.xml @@ -67,6 +67,11 @@ commons-logging 1.2 + + org.owasp.encoder + encoder + 1.2.2 + diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 0000000..36ea78c --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,9 @@ +sonar.projectKey=fiware-perseo-core-dev-jafernandez +sonar.projectName=Fiware Perseo Core Dev JaFernandez +sonar.projectVersion=1.0 +sonar.sources=. +sonar.java.binaries=. +sonar.exclusions=target/** +sonar.junit.reportPaths=target/surefire-reports +sonar.jacoco.reportPaths=target/jacoco.exec +sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml \ No newline at end of file diff --git a/src/main/java/com/telefonica/iot/perseo/Configuration.java b/src/main/java/com/telefonica/iot/perseo/Configuration.java index 22aa87d..d8363aa 100644 --- a/src/main/java/com/telefonica/iot/perseo/Configuration.java +++ b/src/main/java/com/telefonica/iot/perseo/Configuration.java @@ -24,6 +24,8 @@ import java.io.IOException; import java.io.InputStream; import java.util.Properties; +import java.util.ResourceBundle; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +47,7 @@ private Configuration() { private static final String PERSEO_MAX_AGE_ENV = "MAX_AGE"; private static final Properties PROPERTIES = new Properties(); - private static final String PATH = "/etc/perseo-core.properties"; + private static final String PATH = ResourceBundle.getBundle("perseo-core").getString("properties.path"); private static final String ACTION_URL_PROP = "action.url"; private static final String MAX_AGE_PROP = "rule.max_age"; @@ -67,7 +69,7 @@ public static synchronized boolean reload() { InputStream stream; String defaultMaxAge; String defaultURL; - String actionPath = "/actions/do"; + String actionPath = ResourceBundle.getBundle("perseo-core").getString("action.path"); // Check configuration file. If exist, set as default configuration for perseo-core try { diff --git a/src/main/java/com/telefonica/iot/perseo/Constants.java b/src/main/java/com/telefonica/iot/perseo/Constants.java index 2c76a2b..ee1f6eb 100644 --- a/src/main/java/com/telefonica/iot/perseo/Constants.java +++ b/src/main/java/com/telefonica/iot/perseo/Constants.java @@ -24,7 +24,7 @@ * @author brox */ public final class Constants { - private Constants() { }; + private Constants() {} public static final String SERVICE_FIELD = "service"; public static final String SUBSERVICE_FIELD = "subservice"; public static final String CORRELATOR_HEADER = "fiware-correlator"; diff --git a/src/main/java/com/telefonica/iot/perseo/EventsServlet.java b/src/main/java/com/telefonica/iot/perseo/EventsServlet.java index 62ced42..94261fb 100644 --- a/src/main/java/com/telefonica/iot/perseo/EventsServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/EventsServlet.java @@ -33,6 +33,7 @@ import org.apache.log4j.MDC; import org.json.JSONException; import org.json.JSONObject; +import org.owasp.encoder.Encode; /** * @@ -90,11 +91,12 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) try { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.getOutputStream().print(String.format("{\"error\":\"%s\"}%n", je.getMessage())); + response.getOutputStream().print(String.format("{\"error\":\"%s\"}%n", Encode.forHtmlContent(je.getMessage()))); }catch(IOException exception) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } + } } diff --git a/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java b/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java index 9bc2022..feec38c 100644 --- a/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java @@ -30,6 +30,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Level; import org.apache.log4j.LogManager; +import org.owasp.encoder.Encode; /** @@ -113,6 +114,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } + } } /** diff --git a/src/main/java/com/telefonica/iot/perseo/RulesServlet.java b/src/main/java/com/telefonica/iot/perseo/RulesServlet.java index c7d28fc..5a9ae29 100644 --- a/src/main/java/com/telefonica/iot/perseo/RulesServlet.java +++ b/src/main/java/com/telefonica/iot/perseo/RulesServlet.java @@ -31,6 +31,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.MDC; +import org.owasp.encoder.Encode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -81,7 +82,6 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - try { logger.info(String.format("get rule %s", request.getPathInfo())); String ruleName = request.getPathInfo(); @@ -91,12 +91,13 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) ruleName = ruleName == null ? "/" : ruleName; Result r = RulesManager.get(epService, ruleName.substring(1)); response.setStatus(r.getStatusCode()); - response.getOutputStream().print(r.getMessage()); + response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); }catch(Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } + } @@ -122,12 +123,11 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.make(epService, body); response.setStatus(r.getStatusCode()); - response.getOutputStream().print(r.getMessage()); + response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); }catch(Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } - } /** @@ -144,7 +144,6 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - try { String body = Utils.getBodyAsString(request); @@ -154,11 +153,12 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.updateAll(epService, body); response.setStatus(r.getStatusCode()); - response.getOutputStream().print(r.getMessage()); + response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); }catch(Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } + } /** @@ -200,6 +200,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } + } /** diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index 32548ed..7c3389c 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -365,6 +365,8 @@ public Object nextValue() throws JSONException { case '[': this.back(); return new JSONArray(this); + default: + //Added default clause } /* diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 07090ab..418adfe 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -106,7 +106,8 @@ public static String escape(String string) { * @throws JSONException */ public static void noSpace(String string) throws JSONException { - int i, length = string.length(); + int i; + int length = string.length(); if (length == 0) { throw new JSONException("Empty string."); } diff --git a/src/main/java/org/json/XMLTokener.java b/src/main/java/org/json/XMLTokener.java index d319765..20937f5 100644 --- a/src/main/java/org/json/XMLTokener.java +++ b/src/main/java/org/json/XMLTokener.java @@ -202,6 +202,8 @@ public Object nextMeta() throws JSONException { case '\'': back(); return Boolean.TRUE; + default: + //Added default clause } } } @@ -286,6 +288,8 @@ public Object nextToken() throws JSONException { case '"': case '\'': throw syntaxError("Bad character in a name"); + default: + //Added default clause } } } diff --git a/src/main/resources/perseo-core.properties b/src/main/resources/perseo-core.properties index e424043..e577ac1 100644 --- a/src/main/resources/perseo-core.properties +++ b/src/main/resources/perseo-core.properties @@ -25,4 +25,5 @@ action.url = http://127.0.0.1:9090/actions/do # Time in milliseconds (long) to "expire" a "dangling" rule rule.max_age= 60000 - +properties.path = /etc/perseo-core.properties +action.path = /actions/do From 90a8cba2995d4eaf8f030ae7403f59ed93632d11 Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Thu, 21 Nov 2019 12:00:45 +0100 Subject: [PATCH 40/51] Travis I --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 168e7d0..ca43c30 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,7 +30,7 @@ jdk: - openjdk11 branches: only: - - /.*/ + - fiqare-perseo-core-improvements install: - mvn test -B From 5c7b89142ec56ba98993ff65273945c58731b35a Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Thu, 21 Nov 2019 12:13:12 +0100 Subject: [PATCH 41/51] Travis CI --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ca43c30..91806fc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,7 +31,6 @@ jdk: branches: only: - fiqare-perseo-core-improvements - install: - mvn test -B From 64f471342d8d38cc48db19445e89aca035501313 Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Thu, 21 Nov 2019 12:23:52 +0100 Subject: [PATCH 42/51] Fixed Travis errors --- pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pom.xml b/pom.xml index 143e3ce..26daa40 100644 --- a/pom.xml +++ b/pom.xml @@ -80,6 +80,11 @@ 1.1.1 compile + + org.owasp.encoder + encoder + 1.2.2 + From a5ff18a8b93089e27c9d6508f0207544a72f0d7c Mon Sep 17 00:00:00 2001 From: Vladimir Rico Hebles Date: Thu, 21 Nov 2019 12:44:30 +0100 Subject: [PATCH 43/51] Fixed Travis errors(2) --- pom.xml | 61 --------------------------------------------------------- 1 file changed, 61 deletions(-) diff --git a/pom.xml b/pom.xml index 26daa40..cefcd0c 100644 --- a/pom.xml +++ b/pom.xml @@ -17,11 +17,6 @@ **/src/main/java/org/json/**, org/json/** - - jacoco - ${project.basedir}/../target/jacoco.exec - 0.7.2.201409121644 - java reuseReports @@ -132,27 +127,6 @@ false - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - default-prepare-agent - prepare-agent - - - default-report - prepare-package - report - - - - - org.apache.maven.plugins maven-site-plugin @@ -161,41 +135,6 @@ - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-dependency-plugin - - - [3.1.1,) - - - copy - - - - - - - - - - - - From 660056edcaa916a101a2422bcfaa058eeac26a85 Mon Sep 17 00:00:00 2001 From: Fiqare-Emergya Date: Tue, 17 Dec 2019 12:36:06 +0100 Subject: [PATCH 44/51] Fixed org.json dependency --- pom.xml | 19 +- src/main/java/org/json/CDL.java | 279 ---- src/main/java/org/json/Cookie.java | 169 -- src/main/java/org/json/CookieList.java | 89 -- src/main/java/org/json/HTTP.java | 163 -- src/main/java/org/json/HTTPTokener.java | 77 - src/main/java/org/json/JSONArray.java | 977 ------------ src/main/java/org/json/JSONException.java | 43 - src/main/java/org/json/JSONML.java | 467 ------ src/main/java/org/json/JSONObject.java | 1704 --------------------- src/main/java/org/json/JSONString.java | 18 - src/main/java/org/json/JSONStringer.java | 78 - src/main/java/org/json/JSONTokener.java | 448 ------ src/main/java/org/json/JSONWriter.java | 327 ---- src/main/java/org/json/Kim.java | 376 ----- src/main/java/org/json/Property.java | 72 - src/main/java/org/json/README | 68 - src/main/java/org/json/XML.java | 491 ------ src/main/java/org/json/XMLTokener.java | 369 ----- 19 files changed, 12 insertions(+), 6222 deletions(-) delete mode 100644 src/main/java/org/json/CDL.java delete mode 100644 src/main/java/org/json/Cookie.java delete mode 100644 src/main/java/org/json/CookieList.java delete mode 100644 src/main/java/org/json/HTTP.java delete mode 100644 src/main/java/org/json/HTTPTokener.java delete mode 100644 src/main/java/org/json/JSONArray.java delete mode 100644 src/main/java/org/json/JSONException.java delete mode 100644 src/main/java/org/json/JSONML.java delete mode 100644 src/main/java/org/json/JSONObject.java delete mode 100644 src/main/java/org/json/JSONString.java delete mode 100644 src/main/java/org/json/JSONStringer.java delete mode 100644 src/main/java/org/json/JSONTokener.java delete mode 100644 src/main/java/org/json/JSONWriter.java delete mode 100644 src/main/java/org/json/Kim.java delete mode 100644 src/main/java/org/json/Property.java delete mode 100644 src/main/java/org/json/README delete mode 100644 src/main/java/org/json/XML.java delete mode 100644 src/main/java/org/json/XMLTokener.java diff --git a/pom.xml b/pom.xml index cefcd0c..df34613 100644 --- a/pom.xml +++ b/pom.xml @@ -70,15 +70,20 @@ 1.2 - ca.rmen - lib-sunrise-sunset - 1.1.1 - compile + ca.rmen + lib-sunrise-sunset + 1.1.1 + compile - org.owasp.encoder - encoder - 1.2.2 + org.json + json + 20180813 + + + org.owasp.encoder + encoder + 1.2.2 diff --git a/src/main/java/org/json/CDL.java b/src/main/java/org/json/CDL.java deleted file mode 100644 index 995b1d4..0000000 --- a/src/main/java/org/json/CDL.java +++ /dev/null @@ -1,279 +0,0 @@ -package org.json; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/** - * This provides static methods to convert comma delimited text into a - * JSONArray, and to covert a JSONArray into comma delimited text. Comma - * delimited text is a very popular format for data interchange. It is - * understood by most database, spreadsheet, and organizer programs. - *

- * Each row of text represents a row in a table or a data record. Each row - * ends with a NEWLINE character. Each row contains one or more values. - * Values are separated by commas. A value can contain any character except - * for comma, unless is is wrapped in single quotes or double quotes. - *

- * The first row usually contains the names of the columns. - *

- * A comma delimited list can be converted into a JSONArray of JSONObjects. - * The names for the elements in the JSONObjects can be taken from the names - * in the first row. - * @author JSON.org - * @version 2014-05-03 - */ -public class CDL { - - /** - * Get the next value. The value can be wrapped in quotes. The value can - * be empty. - * @param x A JSONTokener of the source text. - * @return The value string, or null if empty. - * @throws JSONException if the quoted string is badly formed. - */ - private static String getValue(JSONTokener x) throws JSONException { - char c; - char q; - StringBuffer sb; - do { - c = x.next(); - } while (c == ' ' || c == '\t'); - switch (c) { - case 0: - return null; - case '"': - case '\'': - q = c; - sb = new StringBuffer(); - for (;;) { - c = x.next(); - if (c == q) { - break; - } - if (c == 0 || c == '\n' || c == '\r') { - throw x.syntaxError("Missing close quote '" + q + "'."); - } - sb.append(c); - } - return sb.toString(); - case ',': - x.back(); - return ""; - default: - x.back(); - return x.nextTo(','); - } - } - - /** - * Produce a JSONArray of strings from a row of comma delimited values. - * @param x A JSONTokener of the source text. - * @return A JSONArray of strings. - * @throws JSONException - */ - public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { - JSONArray ja = new JSONArray(); - for (;;) { - String value = getValue(x); - char c = x.next(); - if (value == null || - (ja.length() == 0 && value.length() == 0 && c != ',')) { - return null; - } - ja.put(value); - for (;;) { - if (c == ',') { - break; - } - if (c != ' ') { - if (c == '\n' || c == '\r' || c == 0) { - return ja; - } - throw x.syntaxError("Bad character '" + c + "' (" + - (int)c + ")."); - } - c = x.next(); - } - } - } - - /** - * Produce a JSONObject from a row of comma delimited text, using a - * parallel JSONArray of strings to provides the names of the elements. - * @param names A JSONArray of names. This is commonly obtained from the - * first row of a comma delimited text file using the rowToJSONArray - * method. - * @param x A JSONTokener of the source text. - * @return A JSONObject combining the names and values. - * @throws JSONException - */ - public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) - throws JSONException { - JSONArray ja = rowToJSONArray(x); - return ja != null ? ja.toJSONObject(names) : null; - } - - /** - * Produce a comma delimited text row from a JSONArray. Values containing - * the comma character will be quoted. Troublesome characters may be - * removed. - * @param ja A JSONArray of strings. - * @return A string ending in NEWLINE. - */ - public static String rowToString(JSONArray ja) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < ja.length(); i += 1) { - if (i > 0) { - sb.append(','); - } - Object object = ja.opt(i); - if (object != null) { - String string = object.toString(); - if (string.length() > 0 && (string.indexOf(',') >= 0 || - string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || - string.indexOf(0) >= 0 || string.charAt(0) == '"')) { - sb.append('"'); - int length = string.length(); - for (int j = 0; j < length; j += 1) { - char c = string.charAt(j); - if (c >= ' ' && c != '"') { - sb.append(c); - } - } - sb.append('"'); - } else { - sb.append(string); - } - } - } - sb.append('\n'); - return sb.toString(); - } - - /** - * Produce a JSONArray of JSONObjects from a comma delimited text string, - * using the first row as a source of names. - * @param string The comma delimited text. - * @return A JSONArray of JSONObjects. - * @throws JSONException - */ - public static JSONArray toJSONArray(String string) throws JSONException { - return toJSONArray(new JSONTokener(string)); - } - - /** - * Produce a JSONArray of JSONObjects from a comma delimited text string, - * using the first row as a source of names. - * @param x The JSONTokener containing the comma delimited text. - * @return A JSONArray of JSONObjects. - * @throws JSONException - */ - public static JSONArray toJSONArray(JSONTokener x) throws JSONException { - return toJSONArray(rowToJSONArray(x), x); - } - - /** - * Produce a JSONArray of JSONObjects from a comma delimited text string - * using a supplied JSONArray as the source of element names. - * @param names A JSONArray of strings. - * @param string The comma delimited text. - * @return A JSONArray of JSONObjects. - * @throws JSONException - */ - public static JSONArray toJSONArray(JSONArray names, String string) - throws JSONException { - return toJSONArray(names, new JSONTokener(string)); - } - - /** - * Produce a JSONArray of JSONObjects from a comma delimited text string - * using a supplied JSONArray as the source of element names. - * @param names A JSONArray of strings. - * @param x A JSONTokener of the source text. - * @return A JSONArray of JSONObjects. - * @throws JSONException - */ - public static JSONArray toJSONArray(JSONArray names, JSONTokener x) - throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - JSONArray ja = new JSONArray(); - for (;;) { - JSONObject jo = rowToJSONObject(names, x); - if (jo == null) { - break; - } - ja.put(jo); - } - if (ja.length() == 0) { - return null; - } - return ja; - } - - - /** - * Produce a comma delimited text from a JSONArray of JSONObjects. The - * first row will be a list of names obtained by inspecting the first - * JSONObject. - * @param ja A JSONArray of JSONObjects. - * @return A comma delimited text. - * @throws JSONException - */ - public static String toString(JSONArray ja) throws JSONException { - JSONObject jo = ja.optJSONObject(0); - if (jo != null) { - JSONArray names = jo.names(); - if (names != null) { - return rowToString(names) + toString(names, ja); - } - } - return null; - } - - /** - * Produce a comma delimited text from a JSONArray of JSONObjects using - * a provided list of names. The list of names is not included in the - * output. - * @param names A JSONArray of strings. - * @param ja A JSONArray of JSONObjects. - * @return A comma delimited text. - * @throws JSONException - */ - public static String toString(JSONArray names, JSONArray ja) - throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < ja.length(); i += 1) { - JSONObject jo = ja.optJSONObject(i); - if (jo != null) { - sb.append(rowToString(jo.toJSONArray(names))); - } - } - return sb.toString(); - } -} diff --git a/src/main/java/org/json/Cookie.java b/src/main/java/org/json/Cookie.java deleted file mode 100644 index 1867dbd..0000000 --- a/src/main/java/org/json/Cookie.java +++ /dev/null @@ -1,169 +0,0 @@ -package org.json; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/** - * Convert a web browser cookie specification to a JSONObject and back. - * JSON and Cookies are both notations for name/value pairs. - * @author JSON.org - * @version 2014-05-03 - */ -public class Cookie { - - /** - * Produce a copy of a string in which the characters '+', '%', '=', ';' - * and control characters are replaced with "%hh". This is a gentle form - * of URL encoding, attempting to cause as little distortion to the - * string as possible. The characters '=' and ';' are meta characters in - * cookies. By convention, they are escaped using the URL-encoding. This is - * only a convention, not a standard. Often, cookies are expected to have - * encoded values. We encode '=' and ';' because we must. We encode '%' and - * '+' because they are meta characters in URL encoding. - * @param string The source string. - * @return The escaped result. - */ - public static String escape(String string) { - char c; - String s = string.trim(); - int length = s.length(); - StringBuilder sb = new StringBuilder(length); - for (int i = 0; i < length; i += 1) { - c = s.charAt(i); - if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { - sb.append('%'); - sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); - sb.append(Character.forDigit((char)(c & 0x0f), 16)); - } else { - sb.append(c); - } - } - return sb.toString(); - } - - - /** - * Convert a cookie specification string into a JSONObject. The string - * will contain a name value pair separated by '='. The name and the value - * will be unescaped, possibly converting '+' and '%' sequences. The - * cookie properties may follow, separated by ';', also represented as - * name=value (except the secure property, which does not have a value). - * The name will be stored under the key "name", and the value will be - * stored under the key "value". This method does not do checking or - * validation of the parameters. It only converts the cookie string into - * a JSONObject. - * @param string The cookie specification string. - * @return A JSONObject containing "name", "value", and possibly other - * members. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - String name; - JSONObject jo = new JSONObject(); - Object value; - JSONTokener x = new JSONTokener(string); - jo.put("name", x.nextTo('=')); - x.next('='); - jo.put("value", x.nextTo(';')); - x.next(); - while (x.more()) { - name = unescape(x.nextTo("=;")); - if (x.next() != '=') { - if (name.equals("secure")) { - value = Boolean.TRUE; - } else { - throw x.syntaxError("Missing '=' in cookie parameter."); - } - } else { - value = unescape(x.nextTo(';')); - x.next(); - } - jo.put(name, value); - } - return jo; - } - - - /** - * Convert a JSONObject into a cookie specification string. The JSONObject - * must contain "name" and "value" members. - * If the JSONObject contains "expires", "domain", "path", or "secure" - * members, they will be appended to the cookie specification string. - * All other members are ignored. - * @param jo A JSONObject - * @return A cookie specification string - * @throws JSONException - */ - public static String toString(JSONObject jo) throws JSONException { - StringBuilder sb = new StringBuilder(); - - sb.append(escape(jo.getString("name"))); - sb.append("="); - sb.append(escape(jo.getString("value"))); - if (jo.has("expires")) { - sb.append(";expires="); - sb.append(jo.getString("expires")); - } - if (jo.has("domain")) { - sb.append(";domain="); - sb.append(escape(jo.getString("domain"))); - } - if (jo.has("path")) { - sb.append(";path="); - sb.append(escape(jo.getString("path"))); - } - if (jo.optBoolean("secure")) { - sb.append(";secure"); - } - return sb.toString(); - } - - /** - * Convert %hh sequences to single characters, and - * convert plus to space. - * @param string A string that may contain - * + (plus) and - * %hh sequences. - * @return The unescaped string. - */ - public static String unescape(String string) { - int length = string.length(); - StringBuilder sb = new StringBuilder(length); - for (int i = 0; i < length; ++i) { - char c = string.charAt(i); - if (c == '+') { - c = ' '; - } else if (c == '%' && i + 2 < length) { - int d = JSONTokener.dehexchar(string.charAt(i + 1)); - int e = JSONTokener.dehexchar(string.charAt(i + 2)); - if (d >= 0 && e >= 0) { - c = (char)(d * 16 + e); - i += 2; - } - } - sb.append(c); - } - return sb.toString(); - } -} diff --git a/src/main/java/org/json/CookieList.java b/src/main/java/org/json/CookieList.java deleted file mode 100644 index b716fd7..0000000 --- a/src/main/java/org/json/CookieList.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.json; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import java.util.Iterator; - -/** - * Convert a web browser cookie list string to a JSONObject and back. - * @author JSON.org - * @version 2014-05-03 - */ -public class CookieList { - - /** - * Convert a cookie list into a JSONObject. A cookie list is a sequence - * of name/value pairs. The names are separated from the values by '='. - * The pairs are separated by ';'. The names and the values - * will be unescaped, possibly converting '+' and '%' sequences. - * - * To add a cookie to a cooklist, - * cookielistJSONObject.put(cookieJSONObject.getString("name"), - * cookieJSONObject.getString("value")); - * @param string A cookie list string - * @return A JSONObject - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - JSONTokener x = new JSONTokener(string); - while (x.more()) { - String name = Cookie.unescape(x.nextTo('=')); - x.next('='); - jo.put(name, Cookie.unescape(x.nextTo(';'))); - x.next(); - } - return jo; - } - - /** - * Convert a JSONObject into a cookie list. A cookie list is a sequence - * of name/value pairs. The names are separated from the values by '='. - * The pairs are separated by ';'. The characters '%', '+', '=', and ';' - * in the names and values are replaced by "%hh". - * @param jo A JSONObject - * @return A cookie list string - * @throws JSONException - */ - public static String toString(JSONObject jo) throws JSONException { - boolean b = false; - Iterator keys = jo.keys(); - String string; - StringBuilder sb = new StringBuilder(); - while (keys.hasNext()) { - string = keys.next(); - if (!jo.isNull(string)) { - if (b) { - sb.append(';'); - } - sb.append(Cookie.escape(string)); - sb.append("="); - sb.append(Cookie.escape(jo.getString(string))); - b = true; - } - } - return sb.toString(); - } -} diff --git a/src/main/java/org/json/HTTP.java b/src/main/java/org/json/HTTP.java deleted file mode 100644 index 648f4da..0000000 --- a/src/main/java/org/json/HTTP.java +++ /dev/null @@ -1,163 +0,0 @@ -package org.json; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import java.util.Iterator; - -/** - * Convert an HTTP header to a JSONObject and back. - * @author JSON.org - * @version 2014-05-03 - */ -public class HTTP { - - /** Carriage return/line feed. */ - public static final String CRLF = "\r\n"; - - /** - * Convert an HTTP header string into a JSONObject. It can be a request - * header or a response header. A request header will contain - *

{
-     *    Method: "POST" (for example),
-     *    "Request-URI": "/" (for example),
-     *    "HTTP-Version": "HTTP/1.1" (for example)
-     * }
- * A response header will contain - *
{
-     *    "HTTP-Version": "HTTP/1.1" (for example),
-     *    "Status-Code": "200" (for example),
-     *    "Reason-Phrase": "OK" (for example)
-     * }
- * In addition, the other parameters in the header will be captured, using - * the HTTP field names as JSON names, so that
-     *    Date: Sun, 26 May 2002 18:06:04 GMT
-     *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
-     *    Cache-Control: no-cache
- * become - *
{...
-     *    Date: "Sun, 26 May 2002 18:06:04 GMT",
-     *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
-     *    "Cache-Control": "no-cache",
-     * ...}
- * It does no further checking or conversion. It does not parse dates. - * It does not do '%' transforms on URLs. - * @param string An HTTP header string. - * @return A JSONObject containing the elements and attributes - * of the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - HTTPTokener x = new HTTPTokener(string); - String token; - - token = x.nextToken(); - if (token.toUpperCase().startsWith("HTTP")) { - -// Response - - jo.put("HTTP-Version", token); - jo.put("Status-Code", x.nextToken()); - jo.put("Reason-Phrase", x.nextTo('\0')); - x.next(); - - } else { - -// Request - - jo.put("Method", token); - jo.put("Request-URI", x.nextToken()); - jo.put("HTTP-Version", x.nextToken()); - } - -// Fields - - while (x.more()) { - String name = x.nextTo(':'); - x.next(':'); - jo.put(name, x.nextTo('\0')); - x.next(); - } - return jo; - } - - - /** - * Convert a JSONObject into an HTTP header. A request header must contain - *
{
-     *    Method: "POST" (for example),
-     *    "Request-URI": "/" (for example),
-     *    "HTTP-Version": "HTTP/1.1" (for example)
-     * }
- * A response header must contain - *
{
-     *    "HTTP-Version": "HTTP/1.1" (for example),
-     *    "Status-Code": "200" (for example),
-     *    "Reason-Phrase": "OK" (for example)
-     * }
- * Any other members of the JSONObject will be output as HTTP fields. - * The result will end with two CRLF pairs. - * @param jo A JSONObject - * @return An HTTP header string. - * @throws JSONException if the object does not contain enough - * information. - */ - public static String toString(JSONObject jo) throws JSONException { - Iterator keys = jo.keys(); - String string; - StringBuilder sb = new StringBuilder(); - if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { - sb.append(jo.getString("HTTP-Version")); - sb.append(' '); - sb.append(jo.getString("Status-Code")); - sb.append(' '); - sb.append(jo.getString("Reason-Phrase")); - } else if (jo.has("Method") && jo.has("Request-URI")) { - sb.append(jo.getString("Method")); - sb.append(' '); - sb.append('"'); - sb.append(jo.getString("Request-URI")); - sb.append('"'); - sb.append(' '); - sb.append(jo.getString("HTTP-Version")); - } else { - throw new JSONException("Not enough material for an HTTP header."); - } - sb.append(CRLF); - while (keys.hasNext()) { - string = keys.next(); - if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && - !"Reason-Phrase".equals(string) && !"Method".equals(string) && - !"Request-URI".equals(string) && !jo.isNull(string)) { - sb.append(string); - sb.append(": "); - sb.append(jo.getString(string)); - sb.append(CRLF); - } - } - sb.append(CRLF); - return sb.toString(); - } -} diff --git a/src/main/java/org/json/HTTPTokener.java b/src/main/java/org/json/HTTPTokener.java deleted file mode 100644 index b2489b6..0000000 --- a/src/main/java/org/json/HTTPTokener.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.json; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/** - * The HTTPTokener extends the JSONTokener to provide additional methods - * for the parsing of HTTP headers. - * @author JSON.org - * @version 2014-05-03 - */ -public class HTTPTokener extends JSONTokener { - - /** - * Construct an HTTPTokener from a string. - * @param string A source string. - */ - public HTTPTokener(String string) { - super(string); - } - - - /** - * Get the next token or string. This is used in parsing HTTP headers. - * @throws JSONException - * @return A String. - */ - public String nextToken() throws JSONException { - char c; - char q; - StringBuilder sb = new StringBuilder(); - do { - c = next(); - } while (Character.isWhitespace(c)); - if (c == '"' || c == '\'') { - q = c; - for (;;) { - c = next(); - if (c < ' ') { - throw syntaxError("Unterminated string."); - } - if (c == q) { - return sb.toString(); - } - sb.append(c); - } - } - for (;;) { - if (c == 0 || Character.isWhitespace(c)) { - return sb.toString(); - } - sb.append(c); - c = next(); - } - } -} diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java deleted file mode 100644 index 04e2d34..0000000 --- a/src/main/java/org/json/JSONArray.java +++ /dev/null @@ -1,977 +0,0 @@ -package org.json; - -/* - Copyright (c) 2002 JSON.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - The Software shall be used for Good, not Evil. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - */ - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; - -/** - * A JSONArray is an ordered sequence of values. Its external text form is a - * string wrapped in square brackets with commas separating the values. The - * internal form is an object having get and opt - * methods for accessing the values by index, and put methods for - * adding or replacing values. The values can be any of these types: - * Boolean, JSONArray, JSONObject, - * Number, String, or the - * JSONObject.NULL object. - *

- * The constructor can convert a JSON text into a Java object. The - * toString method converts to JSON text. - *

- * A get method returns a value if one can be found, and throws an - * exception if one cannot be found. An opt method returns a - * default value instead of throwing an exception, and so is useful for - * obtaining optional values. - *

- * The generic get() and opt() methods return an - * object which you can cast or query for type. There are also typed - * get and opt methods that do type checking and type - * coercion for you. - *

- * The texts produced by the toString methods strictly conform to - * JSON syntax rules. The constructors are more forgiving in the texts they will - * accept: - *

    - *
  • An extra , (comma) may appear just - * before the closing bracket.
  • - *
  • The null value will be inserted when there is , - *  (comma) elision.
  • - *
  • Strings may be quoted with ' (single - * quote).
  • - *
  • Strings do not need to be quoted at all if they do not begin with a quote - * or single quote, and if they do not contain leading or trailing spaces, and - * if they do not contain any of these characters: - * { } [ ] / \ : , # and if they do not look like numbers and - * if they are not the reserved words true, false, or - * null.
  • - *
- * - * @author JSON.org - * @version 2014-05-03 - */ -public class JSONArray { - - /** - * The arrayList where the JSONArray's properties are kept. - */ - private final ArrayList myArrayList; - - /** - * Construct an empty JSONArray. - */ - public JSONArray() { - this.myArrayList = new ArrayList(); - } - - /** - * Construct a JSONArray from a JSONTokener. - * - * @param x - * A JSONTokener - * @throws JSONException - * If there is a syntax error. - */ - public JSONArray(JSONTokener x) throws JSONException { - this(); - if (x.nextClean() != '[') { - throw x.syntaxError("A JSONArray text must start with '['"); - } - if (x.nextClean() != ']') { - x.back(); - for (;;) { - if (x.nextClean() == ',') { - x.back(); - this.myArrayList.add(JSONObject.NULL); - } else { - x.back(); - this.myArrayList.add(x.nextValue()); - } - switch (x.nextClean()) { - case ',': - if (x.nextClean() == ']') { - return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); - } - } - } - } - - /** - * Construct a JSONArray from a source JSON text. - * - * @param source - * A string that begins with [ (left - * bracket) and ends with ] - *  (right bracket). - * @throws JSONException - * If there is a syntax error. - */ - public JSONArray(String source) throws JSONException { - this(new JSONTokener(source)); - } - - /** - * Construct a JSONArray from a Collection. - * - * @param collection - * A Collection. - */ - public JSONArray(Collection collection) { - this.myArrayList = new ArrayList(); - if (collection != null) { - Iterator iter = collection.iterator(); - while (iter.hasNext()) { - this.myArrayList.add(JSONObject.wrap(iter.next())); - } - } - } - - /** - * Construct a JSONArray from an array - * - * @throws JSONException - * If not an array. - */ - public JSONArray(Object array) throws JSONException { - this(); - if (array.getClass().isArray()) { - int length = Array.getLength(array); - for (int i = 0; i < length; i += 1) { - this.put(JSONObject.wrap(Array.get(array, i))); - } - } else { - throw new JSONException( - "JSONArray initial value should be a string or collection or array."); - } - } - - /** - * Get the object value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return An object value. - * @throws JSONException - * If there is no value for the index. - */ - public Object get(int index) throws JSONException { - Object object = this.opt(index); - if (object == null) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - return object; - } - - /** - * Get the boolean value associated with an index. The string values "true" - * and "false" are converted to boolean. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The truth. - * @throws JSONException - * If there is no value for the index or if the value is not - * convertible to boolean. - */ - public boolean getBoolean(int index) throws JSONException { - Object object = this.get(index); - if (object.equals(Boolean.FALSE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("false"))) { - return false; - } else if (object.equals(Boolean.TRUE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("true"))) { - return true; - } - throw new JSONException("JSONArray[" + index + "] is not a boolean."); - } - - /** - * Get the double value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. - */ - public double getDouble(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number ? ((Number) object).doubleValue() - : Double.parseDouble((String) object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + "] is not a number."); - } - } - - /** - * Get the int value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value is not a number. - */ - public int getInt(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number ? ((Number) object).intValue() - : Integer.parseInt((String) object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + "] is not a number."); - } - } - - /** - * Get the JSONArray associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A JSONArray value. - * @throws JSONException - * If there is no value for the index. or if the value is not a - * JSONArray - */ - public JSONArray getJSONArray(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONArray) { - return (JSONArray) object; - } - throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); - } - - /** - * Get the JSONObject associated with an index. - * - * @param index - * subscript - * @return A JSONObject value. - * @throws JSONException - * If there is no value for the index or if the value is not a - * JSONObject - */ - public JSONObject getJSONObject(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONObject) { - return (JSONObject) object; - } - throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); - } - - /** - * Get the long value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. - */ - public long getLong(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number ? ((Number) object).longValue() - : Long.parseLong((String) object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + "] is not a number."); - } - } - - /** - * Get the string associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A string value. - * @throws JSONException - * If there is no string value for the index. - */ - public String getString(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof String) { - return (String) object; - } - throw new JSONException("JSONArray[" + index + "] not a string."); - } - - /** - * Determine if the value is null. - * - * @param index - * The index must be between 0 and length() - 1. - * @return true if the value at the index is null, or if there is no value. - */ - public boolean isNull(int index) { - return JSONObject.NULL.equals(this.opt(index)); - } - - /** - * Make a string from the contents of this JSONArray. The - * separator string is inserted between each element. Warning: - * This method assumes that the data structure is acyclical. - * - * @param separator - * A string that will be inserted between the elements. - * @return a string. - * @throws JSONException - * If the array contains an invalid number. - */ - public String join(String separator) throws JSONException { - int len = this.length(); - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < len; i += 1) { - if (i > 0) { - sb.append(separator); - } - sb.append(JSONObject.valueToString(this.myArrayList.get(i))); - } - return sb.toString(); - } - - /** - * Get the number of elements in the JSONArray, included nulls. - * - * @return The length (or size). - */ - public int length() { - return this.myArrayList.size(); - } - - /** - * Get the optional object value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return An object value, or null if there is no object at that index. - */ - public Object opt(int index) { - return (index < 0 || index >= this.length()) ? null : this.myArrayList - .get(index); - } - - /** - * Get the optional boolean value associated with an index. It returns false - * if there is no value at that index, or if the value is not Boolean.TRUE - * or the String "true". - * - * @param index - * The index must be between 0 and length() - 1. - * @return The truth. - */ - public boolean optBoolean(int index) { - return this.optBoolean(index, false); - } - - /** - * Get the optional boolean value associated with an index. It returns the - * defaultValue if there is no value at that index or if it is not a Boolean - * or the String "true" or "false" (case insensitive). - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * A boolean default. - * @return The truth. - */ - public boolean optBoolean(int index, boolean defaultValue) { - try { - return this.getBoolean(index); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get the optional double value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public double optDouble(int index) { - return this.optDouble(index, Double.NaN); - } - - /** - * Get the optional double value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * subscript - * @param defaultValue - * The default value. - * @return The value. - */ - public double optDouble(int index, double defaultValue) { - try { - return this.getDouble(index); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get the optional int value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public int optInt(int index) { - return this.optInt(index, 0); - } - - /** - * Get the optional int value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public int optInt(int index, int defaultValue) { - try { - return this.getInt(index); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get the optional JSONArray associated with an index. - * - * @param index - * subscript - * @return A JSONArray value, or null if the index has no value, or if the - * value is not a JSONArray. - */ - public JSONArray optJSONArray(int index) { - Object o = this.opt(index); - return o instanceof JSONArray ? (JSONArray) o : null; - } - - /** - * Get the optional JSONObject associated with an index. Null is returned if - * the key is not found, or null if the index has no value, or if the value - * is not a JSONObject. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A JSONObject value. - */ - public JSONObject optJSONObject(int index) { - Object o = this.opt(index); - return o instanceof JSONObject ? (JSONObject) o : null; - } - - /** - * Get the optional long value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public long optLong(int index) { - return this.optLong(index, 0); - } - - /** - * Get the optional long value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public long optLong(int index, long defaultValue) { - try { - return this.getLong(index); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get the optional string value associated with an index. It returns an - * empty string if there is no value at that index. If the value is not a - * string and is not null, then it is coverted to a string. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A String value. - */ - public String optString(int index) { - return this.optString(index, ""); - } - - /** - * Get the optional string associated with an index. The defaultValue is - * returned if the key is not found. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return A String value. - */ - public String optString(int index, String defaultValue) { - Object object = this.opt(index); - return JSONObject.NULL.equals(object) ? defaultValue : object - .toString(); - } - - /** - * Append a boolean value. This increases the array's length by one. - * - * @param value - * A boolean value. - * @return this. - */ - public JSONArray put(boolean value) { - this.put(value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - /** - * Put a value in the JSONArray, where the value will be a JSONArray which - * is produced from a Collection. - * - * @param value - * A Collection value. - * @return this. - */ - public JSONArray put(Collection value) { - this.put(new JSONArray(value)); - return this; - } - - /** - * Append a double value. This increases the array's length by one. - * - * @param value - * A double value. - * @throws JSONException - * if the value is not finite. - * @return this. - */ - public JSONArray put(double value) throws JSONException { - Double d = new Double(value); - JSONObject.testValidity(d); - this.put(d); - return this; - } - - /** - * Append an int value. This increases the array's length by one. - * - * @param value - * An int value. - * @return this. - */ - public JSONArray put(int value) { - this.put(new Integer(value)); - return this; - } - - /** - * Append an long value. This increases the array's length by one. - * - * @param value - * A long value. - * @return this. - */ - public JSONArray put(long value) { - this.put(new Long(value)); - return this; - } - - /** - * Put a value in the JSONArray, where the value will be a JSONObject which - * is produced from a Map. - * - * @param value - * A Map value. - * @return this. - */ - public JSONArray put(Map value) { - this.put(new JSONObject(value)); - return this; - } - - /** - * Append an object value. This increases the array's length by one. - * - * @param value - * An object value. The value should be a Boolean, Double, - * Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. - * @return this. - */ - public JSONArray put(Object value) { - this.myArrayList.add(value); - return this; - } - - /** - * Put or replace a boolean value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @param index - * The subscript. - * @param value - * A boolean value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, boolean value) throws JSONException { - this.put(index, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - /** - * Put a value in the JSONArray, where the value will be a JSONArray which - * is produced from a Collection. - * - * @param index - * The subscript. - * @param value - * A Collection value. - * @return this. - * @throws JSONException - * If the index is negative or if the value is not finite. - */ - public JSONArray put(int index, Collection value) throws JSONException { - this.put(index, new JSONArray(value)); - return this; - } - - /** - * Put or replace a double value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * A double value. - * @return this. - * @throws JSONException - * If the index is negative or if the value is not finite. - */ - public JSONArray put(int index, double value) throws JSONException { - this.put(index, new Double(value)); - return this; - } - - /** - * Put or replace an int value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * An int value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, int value) throws JSONException { - this.put(index, new Integer(value)); - return this; - } - - /** - * Put or replace a long value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * A long value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, long value) throws JSONException { - this.put(index, new Long(value)); - return this; - } - - /** - * Put a value in the JSONArray, where the value will be a JSONObject that - * is produced from a Map. - * - * @param index - * The subscript. - * @param value - * The Map value. - * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. - */ - public JSONArray put(int index, Map value) throws JSONException { - this.put(index, new JSONObject(value)); - return this; - } - - /** - * Put or replace an object value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @param index - * The subscript. - * @param value - * The value to put into the array. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. - */ - public JSONArray put(int index, Object value) throws JSONException { - JSONObject.testValidity(value); - if (index < 0) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - if (index < this.length()) { - this.myArrayList.set(index, value); - } else { - while (index != this.length()) { - this.put(JSONObject.NULL); - } - this.put(value); - } - return this; - } - - /** - * Remove an index and close the hole. - * - * @param index - * The index of the element to be removed. - * @return The value that was associated with the index, or null if there - * was no value. - */ - public Object remove(int index) { - return index >= 0 && index < this.length() - ? this.myArrayList.remove(index) - : null; - } - - /** - * Determine if two JSONArrays are similar. - * They must contain similar sequences. - * - * @param other The other JSONArray - * @return true if they are equal - */ - public boolean similar(Object other) { - if (!(other instanceof JSONArray)) { - return false; - } - int len = this.length(); - if (len != ((JSONArray)other).length()) { - return false; - } - for (int i = 0; i < len; i += 1) { - Object valueThis = this.get(i); - Object valueOther = ((JSONArray)other).get(i); - if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { - return false; - } - } else if (!valueThis.equals(valueOther)) { - return false; - } - } - return true; - } - - /** - * Produce a JSONObject by combining a JSONArray of names with the values of - * this JSONArray. - * - * @param names - * A JSONArray containing a list of key strings. These will be - * paired with the values. - * @return A JSONObject, or null if there are no names or if this JSONArray - * has no values. - * @throws JSONException - * If any of the names are null. - */ - public JSONObject toJSONObject(JSONArray names) throws JSONException { - if (names == null || names.length() == 0 || this.length() == 0) { - return null; - } - JSONObject jo = new JSONObject(); - for (int i = 0; i < names.length(); i += 1) { - jo.put(names.getString(i), this.opt(i)); - } - return jo; - } - - /** - * Make a JSON text of this JSONArray. For compactness, no unnecessary - * whitespace is added. If it is not possible to produce a syntactically - * correct JSON text then null will be returned instead. This could occur if - * the array contains an invalid number. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, transmittable representation of the - * array. - */ - public String toString() { - try { - return this.toString(0); - } catch (Exception e) { - return ""; - } - } - - /** - * Make a prettyprinted JSON text of this JSONArray. Warning: This method - * assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @return a printable, displayable, transmittable representation of the - * object, beginning with [ (left - * bracket) and ending with ] - *  (right bracket). - * @throws JSONException - */ - public String toString(int indentFactor) throws JSONException { - StringWriter sw = new StringWriter(); - synchronized (sw.getBuffer()) { - return this.write(sw, indentFactor, 0).toString(); - } - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @param indent - * The indention of the top level. - * @return The writer. - * @throws JSONException - */ - Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean commanate = false; - int length = this.length(); - writer.write('['); - - if (length == 1) { - JSONObject.writeValue(writer, this.myArrayList.get(0), - indentFactor, indent); - } else if (length != 0) { - final int newindent = indent + indentFactor; - - for (int i = 0; i < length; i += 1) { - if (commanate) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, newindent); - JSONObject.writeValue(writer, this.myArrayList.get(i), - indentFactor, newindent); - commanate = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, indent); - } - writer.write(']'); - return writer; - } catch (IOException e) { - throw new JSONException(e); - } - } -} diff --git a/src/main/java/org/json/JSONException.java b/src/main/java/org/json/JSONException.java deleted file mode 100644 index 6fef519..0000000 --- a/src/main/java/org/json/JSONException.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.json; - -/** - * The JSONException is thrown by the JSON.org classes when things are amiss. - * - * @author JSON.org - * @version 2014-05-03 - */ -public class JSONException extends RuntimeException { - private static final long serialVersionUID = 0; - private Throwable cause; - - /** - * Constructs a JSONException with an explanatory message. - * - * @param message - * Detail about the reason for the exception. - */ - public JSONException(String message) { - super(message); - } - - /** - * Constructs a new JSONException with the specified cause. - * @param cause The cause. - */ - public JSONException(Throwable cause) { - super(cause.getMessage()); - this.cause = cause; - } - - /** - * Returns the cause of this exception or null if the cause is nonexistent - * or unknown. - * - * @return the cause of this exception or null if the cause is nonexistent - * or unknown. - */ - @Override - public Throwable getCause() { - return this.cause; - } -} diff --git a/src/main/java/org/json/JSONML.java b/src/main/java/org/json/JSONML.java deleted file mode 100644 index 20e0be5..0000000 --- a/src/main/java/org/json/JSONML.java +++ /dev/null @@ -1,467 +0,0 @@ -package org.json; - -/* -Copyright (c) 2008 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import java.util.Iterator; - - -/** - * This provides static methods to convert an XML text into a JSONArray or - * JSONObject, and to covert a JSONArray or JSONObject into an XML text using - * the JsonML transform. - * - * @author JSON.org - * @version 2014-05-03 - */ -public class JSONML { - - /** - * Parse XML values and store them in a JSONArray. - * @param x The XMLTokener containing the source string. - * @param arrayForm true if array form, false if object form. - * @param ja The JSONArray that is containing the current tag or null - * if we are at the outermost level. - * @return A JSONArray if the value is the outermost tag, otherwise null. - * @throws JSONException - */ - private static Object parse( - XMLTokener x, - boolean arrayForm, - JSONArray ja - ) throws JSONException { - String attribute; - char c; - String closeTag = null; - int i; - JSONArray newja = null; - JSONObject newjo = null; - Object token; - String tagName = null; - -// Test for and skip past these forms: -// -// -// -// - - while (true) { - if (!x.more()) { - throw x.syntaxError("Bad XML"); - } - token = x.nextContent(); - if (token == XML.LT) { - token = x.nextToken(); - if (token instanceof Character) { - if (token == XML.SLASH) { - -// Close tag "); - } else { - x.back(); - } - } else if (c == '[') { - token = x.nextToken(); - if (token.equals("CDATA") && x.next() == '[') { - if (ja != null) { - ja.put(x.nextCDATA()); - } - } else { - throw x.syntaxError("Expected 'CDATA['"); - } - } else { - i = 1; - do { - token = x.nextMeta(); - if (token == null) { - throw x.syntaxError("Missing '>' after ' 0); - } - } else if (token == XML.QUEST) { - -// "); - } else { - throw x.syntaxError("Misshaped tag"); - } - -// Open tag < - - } else { - if (!(token instanceof String)) { - throw x.syntaxError("Bad tagName '" + token + "'."); - } - tagName = (String)token; - newja = new JSONArray(); - newjo = new JSONObject(); - if (arrayForm) { - newja.put(tagName); - if (ja != null) { - ja.put(newja); - } - } else { - newjo.put("tagName", tagName); - if (ja != null) { - ja.put(newjo); - } - } - token = null; - for (;;) { - if (token == null) { - token = x.nextToken(); - } - if (token == null) { - throw x.syntaxError("Misshaped tag"); - } - if (!(token instanceof String)) { - break; - } - -// attribute = value - - attribute = (String)token; - if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { - throw x.syntaxError("Reserved attribute."); - } - token = x.nextToken(); - if (token == XML.EQ) { - token = x.nextToken(); - if (!(token instanceof String)) { - throw x.syntaxError("Missing value"); - } - newjo.accumulate(attribute, XML.stringToValue((String)token)); - token = null; - } else { - newjo.accumulate(attribute, ""); - } - } - if (arrayForm && newjo.length() > 0) { - newja.put(newjo); - } - -// Empty tag <.../> - - if (token == XML.SLASH) { - if (x.nextToken() != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } - if (ja == null) { - if (arrayForm) { - return newja; - } else { - return newjo; - } - } - -// Content, between <...> and - - } else { - if (token != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } - closeTag = (String)parse(x, arrayForm, newja); - if (closeTag != null) { - if (!closeTag.equals(tagName)) { - throw x.syntaxError("Mismatched '" + tagName + - "' and '" + closeTag + "'"); - } - tagName = null; - if (!arrayForm && newja.length() > 0) { - newjo.put("childNodes", newja); - } - if (ja == null) { - if (arrayForm) { - return newja; - } else { - return newjo; - } - } - } - } - } - } else { - if (ja != null) { - ja.put(token instanceof String - ? XML.stringToValue((String)token) - : token); - } - } - } - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONArray using the JsonML transform. Each XML tag is represented as - * a JSONArray in which the first element is the tag name. If the tag has - * attributes, then the second element will be JSONObject containing the - * name/value pairs. If the tag contains children, then strings and - * JSONArrays will represent the child tags. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param string The source string. - * @return A JSONArray containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONArray toJSONArray(String string) throws JSONException { - return toJSONArray(new XMLTokener(string)); - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONArray using the JsonML transform. Each XML tag is represented as - * a JSONArray in which the first element is the tag name. If the tag has - * attributes, then the second element will be JSONObject containing the - * name/value pairs. If the tag contains children, then strings and - * JSONArrays will represent the child content and tags. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param x An XMLTokener. - * @return A JSONArray containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONArray toJSONArray(XMLTokener x) throws JSONException { - return (JSONArray)parse(x, true, null); - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject using the JsonML transform. Each XML tag is represented as - * a JSONObject with a "tagName" property. If the tag has attributes, then - * the attributes will be in the JSONObject as properties. If the tag - * contains children, the object will have a "childNodes" property which - * will be an array of strings and JsonML JSONObjects. - - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param x An XMLTokener of the XML source text. - * @return A JSONObject containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(XMLTokener x) throws JSONException { - return (JSONObject)parse(x, false, null); - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject using the JsonML transform. Each XML tag is represented as - * a JSONObject with a "tagName" property. If the tag has attributes, then - * the attributes will be in the JSONObject as properties. If the tag - * contains children, the object will have a "childNodes" property which - * will be an array of strings and JsonML JSONObjects. - - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param string The XML source text. - * @return A JSONObject containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - return toJSONObject(new XMLTokener(string)); - } - - - /** - * Reverse the JSONML transformation, making an XML text from a JSONArray. - * @param ja A JSONArray. - * @return An XML string. - * @throws JSONException - */ - public static String toString(JSONArray ja) throws JSONException { - int i; - JSONObject jo; - String key; - Iterator keys; - int length; - Object object; - StringBuilder sb = new StringBuilder(); - String tagName; - String value; - -// Emit = length) { - sb.append('/'); - sb.append('>'); - } else { - sb.append('>'); - do { - object = ja.get(i); - i += 1; - if (object != null) { - if (object instanceof String) { - sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject)object)); - } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray)object)); - } - } - } while (i < length); - sb.append('<'); - sb.append('/'); - sb.append(tagName); - sb.append('>'); - } - return sb.toString(); - } - - /** - * Reverse the JSONML transformation, making an XML text from a JSONObject. - * The JSONObject must contain a "tagName" property. If it has children, - * then it must have a "childNodes" property containing an array of objects. - * The other properties are attributes with string values. - * @param jo A JSONObject. - * @return An XML string. - * @throws JSONException - */ - public static String toString(JSONObject jo) throws JSONException { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - String key; - Iterator keys; - int length; - Object object; - String tagName; - String value; - -//Emit '); - } else { - sb.append('>'); - length = ja.length(); - for (i = 0; i < length; i += 1) { - object = ja.get(i); - if (object != null) { - if (object instanceof String) { - sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject)object)); - } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray)object)); - } else { - sb.append(object.toString()); - } - } - } - sb.append('<'); - sb.append('/'); - sb.append(tagName); - sb.append('>'); - } - return sb.toString(); - } -} diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java deleted file mode 100644 index 483f514..0000000 --- a/src/main/java/org/json/JSONObject.java +++ /dev/null @@ -1,1704 +0,0 @@ -package org.json; - -/* - Copyright (c) 2002 JSON.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - The Software shall be used for Good, not Evil. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - */ - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.ResourceBundle; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A JSONObject is an unordered collection of name/value pairs. Its external - * form is a string wrapped in curly braces with colons between the names and - * values, and commas between the values and names. The internal form is an - * object having get and opt methods for accessing - * the values by name, and put methods for adding or replacing - * values by name. The values can be any of these types: Boolean, - * JSONArray, JSONObject, Number, - * String, or the JSONObject.NULL object. A - * JSONObject constructor can be used to convert an external form JSON text - * into an internal form whose values can be retrieved with the - * get and opt methods, or to convert values into a - * JSON text using the put and toString methods. A - * get method returns a value if one can be found, and throws an - * exception if one cannot be found. An opt method returns a - * default value instead of throwing an exception, and so is useful for - * obtaining optional values. - *

- * The generic get() and opt() methods return an - * object, which you can cast or query for type. There are also typed - * get and opt methods that do type checking and type - * coercion for you. The opt methods differ from the get methods in that they - * do not throw. Instead, they return a specified value, such as null. - *

- * The put methods add or replace values in an object. For - * example, - * - *

- * myString = new JSONObject()
- *         .put("JSON", "Hello, World!").toString();
- * 
- * - * produces the string {"JSON": "Hello, World"}. - *

- * The texts produced by the toString methods strictly conform to - * the JSON syntax rules. The constructors are more forgiving in the texts they - * will accept: - *

    - *
  • An extra , (comma) may appear just - * before the closing brace.
  • - *
  • Strings may be quoted with ' (single - * quote).
  • - *
  • Strings do not need to be quoted at all if they do not begin with a - * quote or single quote, and if they do not contain leading or trailing - * spaces, and if they do not contain any of these characters: - * { } [ ] / \ : , # and if they do not look like numbers and - * if they are not the reserved words true, false, - * or null.
  • - *
- * - * @author JSON.org - * @version 2014-05-03 - */ -public class JSONObject { - /** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined. - */ - private static final class Null{ - - /** - * There is only intended to be a single instance of the NULL object, - * so the clone method returns itself. - * - * @return NULL. - */ - /* @Override - protected final Object clone() { - return this; - } - Corrección SonarQube. squid:S2975 - */ - - - - Null() { - } - - - - /** - * A Null object is equal to the null value and to itself. - * - * @param object - * An object to test for nullness. - * @return true if the object parameter is the JSONObject.NULL object or - * null. - */ - @Override - public boolean equals(Object object) { - return object == null || object == this; - } - - /** - * A Null object in Java always has hashCode 0. - * - * @return 0. - */ - @Override - public int hashCode() { - return 0; - } - - /** - * Get the "null" string value. - * - * @return The string "null". - */ - public String toString() { - return "null"; - } - } - - /** - * The map where the JSONObject's properties are kept. - */ - private final Map map; - - /** - * It is sometimes more convenient and less ambiguous to have a - * NULL object than to use Java's null value. - * JSONObject.NULL.equals(null) returns true. - * JSONObject.NULL.toString() returns "null". - */ - public static final Object NULL = new Null(); - - /** - * Construct an empty JSONObject. - */ - public JSONObject() { - this.map = new HashMap(); - } - - /** - * Construct a JSONObject from a subset of another JSONObject. An array of - * strings is used to identify the keys that should be copied. Missing keys - * are ignored. - * - * @param jo - * A JSONObject. - * @param names - * An array of strings. - * @throws JSONException - * @exception JSONException - * If a value is a non-finite number or if a name is - * duplicated. - */ - public JSONObject(JSONObject jo, String[] names) { - this(); - for (int i = 0; i < names.length; i += 1) { - try { - this.putOnce(names[i], jo.opt(names[i])); - } catch (Exception ignore) { - } - } - } - - /** - * Construct a JSONObject from a JSONTokener. - * - * @param x - * A JSONTokener object containing the source string. - * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. - */ - public JSONObject(JSONTokener x) throws JSONException { - this(); - char c; - String key; - - if (x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for (;;) { - c = x.nextClean(); - switch (c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); - } - -// The key is followed by ':'. - - c = x.nextClean(); - if (c != ':') { - throw x.syntaxError("Expected a ':' after a key"); - } - this.putOnce(key, x.nextValue()); - -// Pairs are separated by ','. - - switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { - return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); - } - } - } - - /** - * Construct a JSONObject from a Map. - * - * @param map - * A map object that can be used to initialize the contents of - * the JSONObject. - * @throws JSONException - */ - public JSONObject(Map map) { - this.map = new HashMap(); - if (map != null) { - Iterator> i = map.entrySet().iterator(); - while (i.hasNext()) { - Entry entry = i.next(); - Object value = entry.getValue(); - if (value != null) { - this.map.put(entry.getKey(), wrap(value)); - } - } - } - } - - /** - * Construct a JSONObject from an Object using bean getters. It reflects on - * all of the public methods of the object. For each of the methods with no - * parameters and a name starting with "get" or - * "is" followed by an uppercase letter, the method is invoked, - * and a key and the value returned from the getter method are put into the - * new JSONObject. - * - * The key is formed by removing the "get" or "is" - * prefix. If the second remaining character is not upper case, then the - * first character is converted to lower case. - * - * For example, if an object has a method named "getName", and - * if the result of calling object.getName() is - * "Larry Fine", then the JSONObject will contain - * "name": "Larry Fine". - * - * @param bean - * An object that has getter methods that should be used to make - * a JSONObject. - */ - public JSONObject(Object bean) { - this(); - this.populateMap(bean); - } - - /** - * Construct a JSONObject from an Object, using reflection to find the - * public members. The resulting JSONObject's keys will be the strings from - * the names array, and the values will be the field values associated with - * those keys in the object. If a key is not found or not visible, then it - * will not be copied into the new JSONObject. - * - * @param object - * An object that has fields that should be used to make a - * JSONObject. - * @param names - * An array of strings, the names of the fields to be obtained - * from the object. - */ - public JSONObject(Object object, String names[]) { - this(); - Class c = object.getClass(); - for (int i = 0; i < names.length; i += 1) { - String name = names[i]; - try { - this.putOpt(name, c.getField(name).get(object)); - } catch (Exception ignore) { - } - } - } - - /** - * Construct a JSONObject from a source JSON text string. This is the most - * commonly used JSONObject constructor. - * - * @param source - * A string beginning with { (left - * brace) and ending with } - *  (right brace). - * @exception JSONException - * If there is a syntax error in the source string or a - * duplicated key. - */ - public JSONObject(String source) throws JSONException { - this(new JSONTokener(source)); - } - - /** - * Construct a JSONObject from a ResourceBundle. - * - * @param baseName - * The ResourceBundle base name. - * @param locale - * The Locale to load the ResourceBundle for. - * @throws JSONException - * If any JSONExceptions are detected. - */ - public JSONObject(String baseName, Locale locale) throws JSONException { - this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, - Thread.currentThread().getContextClassLoader()); - -// Iterate through the keys in the bundle. - - Enumeration keys = bundle.getKeys(); - while (keys.hasMoreElements()) { - Object key = keys.nextElement(); - if (key != null) { - -// Go through the path, ensuring that there is a nested JSONObject for each -// segment except the last. Add the value using the last segment's name into -// the deepest nested JSONObject. - - String[] path = ((String) key).split("\\."); - int last = path.length - 1; - JSONObject target = this; - for (int i = 0; i < last; i += 1) { - String segment = path[i]; - JSONObject nextTarget = target.optJSONObject(segment); - if (nextTarget == null) { - nextTarget = new JSONObject(); - target.put(segment, nextTarget); - } - target = nextTarget; - } - target.put(path[last], bundle.getString((String) key)); - } - } - } - - /** - * Accumulate values under a key. It is similar to the put method except - * that if there is already an object stored under the key then a JSONArray - * is stored under the key to hold all of the accumulated values. If there - * is already a JSONArray, then the new value is appended to it. In - * contrast, the put method replaces the previous value. - * - * If only one value is accumulated that is not a JSONArray, then the result - * will be the same as using put. But if multiple values are accumulated, - * then the result will be like append. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the value is an invalid number or if the key is null. - */ - public JSONObject accumulate(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, - value instanceof JSONArray ? new JSONArray().put(value) - : value); - } else if (object instanceof JSONArray) { - ((JSONArray) object).put(value); - } else { - this.put(key, new JSONArray().put(object).put(value)); - } - return this; - } - - /** - * Append values to the array under a key. If the key does not exist in the - * JSONObject, then the key is put in the JSONObject with its value being a - * JSONArray containing the value parameter. If the key was already - * associated with a JSONArray, then the value parameter is appended to it. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the key is null or if the current value associated with - * the key is not a JSONArray. - */ - public JSONObject append(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, new JSONArray().put(value)); - } else if (object instanceof JSONArray) { - this.put(key, ((JSONArray) object).put(value)); - } else { - throw new JSONException("JSONObject[" + key - + "] is not a JSONArray."); - } - return this; - } - - /** - * Produce a string from a double. The string "null" will be returned if the - * number is not finite. - * - * @param d - * A double. - * @return A String. - */ - public static String doubleToString(double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } - -// Shave off trailing zeros and decimal point, if possible. - - String string = Double.toString(d); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 - && string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - /** - * Get the value object associated with a key. - * - * @param key - * A key string. - * @return The object associated with the key. - * @throws JSONException - * if the key is not found. - */ - public Object get(String key) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - Object object = this.opt(key); - if (object == null) { - throw new JSONException("JSONObject[" + quote(key) + "] not found."); - } - return object; - } - - /** - * Get the boolean value associated with a key. - * - * @param key - * A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or - * "false". - */ - public boolean getBoolean(String key) throws JSONException { - Object object = this.get(key); - if (object.equals(Boolean.FALSE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("false"))) { - return false; - } else if (object.equals(Boolean.TRUE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("true"))) { - return true; - } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a Boolean."); - } - - /** - * Get the double value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public double getDouble(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number ? ((Number) object).doubleValue() - : Double.parseDouble((String) object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] is not a number."); - } - } - - /** - * Get the int value associated with a key. - * - * @param key - * A key string. - * @return The integer value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an integer. - */ - public int getInt(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number ? ((Number) object).intValue() - : Integer.parseInt((String) object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] is not an int."); - } - } - - /** - * Get the JSONArray value associated with a key. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONArray. - */ - public JSONArray getJSONArray(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONArray) { - return (JSONArray) object; - } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a JSONArray."); - } - - /** - * Get the JSONObject value associated with a key. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONObject. - */ - public JSONObject getJSONObject(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONObject) { - return (JSONObject) object; - } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a JSONObject."); - } - - /** - * Get the long value associated with a key. - * - * @param key - * A key string. - * @return The long value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to a long. - */ - public long getLong(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number ? ((Number) object).longValue() - : Long.parseLong((String) object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] is not a long."); - } - } - - /** - * Get an array of field names from a JSONObject. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(JSONObject jo) { - int length = jo.length(); - if (length == 0) { - return null; - } - Iterator iterator = jo.keys(); - String[] names = new String[length]; - int i = 0; - while (iterator.hasNext()) { - names[i] = iterator.next(); - i += 1; - } - return names; - } - - /** - * Get an array of field names from an Object. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(Object object) { - if (object == null) { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if (length == 0) { - return null; - } - String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; - } - - /** - * Get the string associated with a key. - * - * @param key - * A key string. - * @return A string which is the value. - * @throws JSONException - * if there is no string value for the key. - */ - public String getString(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof String) { - return (String) object; - } - throw new JSONException("JSONObject[" + quote(key) + "] not a string."); - } - - /** - * Determine if the JSONObject contains a specific key. - * - * @param key - * A key string. - * @return true if the key exists in the JSONObject. - */ - public boolean has(String key) { - return this.map.containsKey(key); - } - - /** - * Increment a property of a JSONObject. If there is no such property, - * create one with a value of 1. If there is such a property, and if it is - * an Integer, Long, Double, or Float, then add one to it. - * - * @param key - * A key string. - * @return this. - * @throws JSONException - * If there is already a property with this name that is not an - * Integer, Long, Double, or Float. - */ - public JSONObject increment(String key) throws JSONException { - Object value = this.opt(key); - if (value == null) { - this.put(key, 1); - } else if (value instanceof Integer) { - this.put(key, (Integer) value + 1); - } else if (value instanceof Long) { - this.put(key, (Long) value + 1); - } else if (value instanceof Double) { - this.put(key, (Double) value + 1); - } else if (value instanceof Float) { - this.put(key, (Float) value + 1); - } else { - throw new JSONException("Unable to increment [" + quote(key) + "]."); - } - return this; - } - - /** - * Determine if the value associated with the key is null or if there is no - * value. - * - * @param key - * A key string. - * @return true if there is no value associated with the key or if the value - * is the JSONObject.NULL object. - */ - public boolean isNull(String key) { - return JSONObject.NULL.equals(this.opt(key)); - } - - /** - * Get an enumeration of the keys of the JSONObject. - * - * @return An iterator of the keys. - */ - public Iterator keys() { - return this.keySet().iterator(); - } - - /** - * Get a set of keys of the JSONObject. - * - * @return A keySet. - */ - public Set keySet() { - return this.map.keySet(); - } - - /** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - public int length() { - return this.map.size(); - } - - /** - * Produce a JSONArray containing the names of the elements of this - * JSONObject. - * - * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. - */ - public JSONArray names() { - JSONArray ja = new JSONArray(); - Iterator keys = this.keys(); - while (keys.hasNext()) { - ja.put(keys.next()); - } - return ja.length() == 0 ? null : ja; - } - - /** - * Produce a string from a Number. - * - * @param number - * A Number - * @return A String. - * @throws JSONException - * If n is a non-finite number. - */ - public static String numberToString(Number number) throws JSONException { - if (number == null) { - throw new JSONException("Null pointer"); - } - testValidity(number); - -// Shave off trailing zeros and decimal point, if possible. - - String string = number.toString(); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 - && string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - /** - * Get an optional value associated with a key. - * - * @param key - * A key string. - * @return An object which is the value, or null if there is no value. - */ - public Object opt(String key) { - return key == null ? null : this.map.get(key); - } - - /** - * Get an optional boolean associated with a key. It returns false if there - * is no such key, or if the value is not Boolean.TRUE or the String "true". - * - * @param key - * A key string. - * @return The truth. - */ - public boolean optBoolean(String key) { - return this.optBoolean(key, false); - } - - /** - * Get an optional boolean associated with a key. It returns the - * defaultValue if there is no such key, or if it is not a Boolean or the - * String "true" or "false" (case insensitive). - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return The truth. - */ - public boolean optBoolean(String key, boolean defaultValue) { - try { - return this.getBoolean(key); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional double associated with a key, or NaN if there is no such - * key or if its value is not a number. If the value is a string, an attempt - * will be made to evaluate it as a number. - * - * @param key - * A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) { - return this.optDouble(key, Double.NaN); - } - - /** - * Get an optional double associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public double optDouble(String key, double defaultValue) { - try { - return this.getDouble(key); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional int value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public int optInt(String key) { - return this.optInt(key, 0); - } - - /** - * Get an optional int value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public int optInt(String key, int defaultValue) { - try { - return this.getInt(key); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional JSONArray associated with a key. It returns null if there - * is no such key, or if its value is not a JSONArray. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key) { - Object o = this.opt(key); - return o instanceof JSONArray ? (JSONArray) o : null; - } - - /** - * Get an optional JSONObject associated with a key. It returns null if - * there is no such key, or if its value is not a JSONObject. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - */ - public JSONObject optJSONObject(String key) { - Object object = this.opt(key); - return object instanceof JSONObject ? (JSONObject) object : null; - } - - /** - * Get an optional long value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public long optLong(String key) { - return this.optLong(key, 0); - } - - /** - * Get an optional long value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public long optLong(String key, long defaultValue) { - try { - return this.getLong(key); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional string associated with a key. It returns an empty string - * if there is no such key. If the value is not a string and is not null, - * then it is converted to a string. - * - * @param key - * A key string. - * @return A string which is the value. - */ - public String optString(String key) { - return this.optString(key, ""); - } - - /** - * Get an optional string associated with a key. It returns the defaultValue - * if there is no such key. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return A string which is the value. - */ - public String optString(String key, String defaultValue) { - Object object = this.opt(key); - return NULL.equals(object) ? defaultValue : object.toString(); - } - - private void populateMap(Object bean) { - Class klass = bean.getClass(); - -// If klass is a System class then set includeSuperClass to false. - - boolean includeSuperClass = klass.getClassLoader() != null; - - Method[] methods = includeSuperClass ? klass.getMethods() : klass - .getDeclaredMethods(); - for (int i = 0; i < methods.length; i += 1) { - try { - Method method = methods[i]; - if (Modifier.isPublic(method.getModifiers())) { - String name = method.getName(); - String key = ""; - if (name.startsWith("get")) { - if ("getClass".equals(name) - || "getDeclaringClass".equals(name)) { - key = ""; - } else { - key = name.substring(3); - } - } else if (name.startsWith("is")) { - key = name.substring(2); - } - if (key.length() > 0 - && Character.isUpperCase(key.charAt(0)) - && method.getParameterTypes().length == 0) { - if (key.length() == 1) { - key = key.toLowerCase(); - } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() - + key.substring(1); - } - - Object result = method.invoke(bean, (Object[]) null); - if (result != null) { - this.map.put(key, wrap(result)); - } - } - } - } catch (Exception ignore) { - } - } - } - - /** - * Put a key/boolean pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A boolean which is the value. - * @return this. - * @throws JSONException - * If the key is null. - */ - public JSONObject put(String key, boolean value) throws JSONException { - this.put(key, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONArray which is produced from a Collection. - * - * @param key - * A key string. - * @param value - * A Collection value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Collection value) throws JSONException { - this.put(key, new JSONArray(value)); - return this; - } - - /** - * Put a key/double pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A double which is the value. - * @return this. - * @throws JSONException - * If the key is null or if the number is invalid. - */ - public JSONObject put(String key, double value) throws JSONException { - this.put(key, new Double(value)); - return this; - } - - /** - * Put a key/int pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * An int which is the value. - * @return this. - * @throws JSONException - * If the key is null. - */ - public JSONObject put(String key, int value) throws JSONException { - this.put(key, new Integer(value)); - return this; - } - - /** - * Put a key/long pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A long which is the value. - * @return this. - * @throws JSONException - * If the key is null. - */ - public JSONObject put(String key, long value) throws JSONException { - this.put(key, new Long(value)); - return this; - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONObject which is produced from a Map. - * - * @param key - * A key string. - * @param value - * A Map value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Map value) throws JSONException { - this.put(key, new JSONObject(value)); - return this; - } - - /** - * Put a key/value pair in the JSONObject. If the value is null, then the - * key will be removed from the JSONObject if it is present. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is non-finite number or if the key is null. - */ - public JSONObject put(String key, Object value) throws JSONException { - if (key == null) { - throw new NullPointerException("Null key."); - } - if (value != null) { - testValidity(value); - this.map.put(key, value); - } else { - this.remove(key); - } - return this; - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null, and only if there is not already a member with that - * name. - * - * @param key string - * @param value object - * @return this. - * @throws JSONException - * if the key is a duplicate - */ - public JSONObject putOnce(String key, Object value) throws JSONException { - if (key != null && value != null) { - if (this.opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - this.put(key, value); - } - return this; - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is a non-finite number. - */ - public JSONObject putOpt(String key, Object value) throws JSONException { - if (key != null && value != null) { - this.put(key, value); - } - return this; - } - - /** - * Produce a string in double quotes with backslash sequences in all the - * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') - || (c >= '\u2000' && c < '\u2100')) { - w.write("\\u"); - hhhh = Integer.toHexString(c); - w.write("0000", 0, 4 - hhhh.length()); - w.write(hhhh); - } else { - w.write(c); - } - } - } - w.write('"'); - return w; - } - - /** - * Remove a name and its value, if present. - * - * @param key - * The name to be removed. - * @return The value that was associated with the name, or null if there was - * no value. - */ - public Object remove(String key) { - return this.map.remove(key); - } - - /** - * Determine if two JSONObjects are similar. - * They must contain the same set of names which must be associated with - * similar values. - * - * @param other The other JSONObject - * @return true if they are equal - */ - public boolean similar(Object other) { - try { - if (!(other instanceof JSONObject)) { - return false; - } - Set set = this.keySet(); - if (!set.equals(((JSONObject)other).keySet())) { - return false; - } - Iterator iterator = set.iterator(); - while (iterator.hasNext()) { - String name = iterator.next(); - Object valueThis = this.get(name); - Object valueOther = ((JSONObject)other).get(name); - if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { - return false; - } - } else if (!valueThis.equals(valueOther)) { - return false; - } - } - return true; - } catch (JSONException exception) { - return false; - } - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * - * @param string - * A String. - * @return A simple JSON value. - */ - public static Object stringToValue(String string) { - Double d; - if (string.equals("")) { - return string; - } - if (string.equalsIgnoreCase("true")) { - return Boolean.TRUE; - } - if (string.equalsIgnoreCase("false")) { - return Boolean.FALSE; - } - if (string.equalsIgnoreCase("null")) { - return JSONObject.NULL; - } - - /* - * If it might be a number, try converting it. If a number cannot be - * produced, then the value will just be a string. - */ - - char b = string.charAt(0); - if ((b >= '0' && b <= '9') || b == '-') { - try { - if (string.indexOf('.') > -1 || string.indexOf('e') > -1 - || string.indexOf('E') > -1) { - d = Double.valueOf(string); - if (!d.isInfinite() && !d.isNaN()) { - return d; - } - } else { - Long myLong = new Long(string); - if (string.equals(myLong.toString())) { - if (myLong == myLong.intValue()) { - return myLong.intValue(); - } else { - return myLong; - } - } - } - } catch (Exception ignore) { - } - } - return string; - } - - /** - * Throw an exception if the object is a NaN or infinite number. - * - * @param o - * The object to test. - * @throws JSONException - * If o is a non-finite number. - */ - public static void testValidity(Object o) throws JSONException { - if (o != null) { - if (o instanceof Double) { - if (((Double) o).isInfinite() || ((Double) o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } else if (o instanceof Float) { - if (((Float) o).isInfinite() || ((Float) o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } - } - } - - /** - * Produce a JSONArray containing the values of the members of this - * JSONObject. - * - * @param names - * A JSONArray containing a list of key strings. This determines - * the sequence of the values in the result. - * @return A JSONArray of values. - * @throws JSONException - * If any of the values are non-finite numbers. - */ - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - - /** - * Make a JSON text of this JSONObject. For compactness, no whitespace is - * added. If this would not result in a syntactically correct JSON text, - * then null will be returned instead. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - */ - public String toString() { - try { - return this.toString(0); - } catch (Exception e) { - return ""; - } - } - - /** - * Make a prettyprinted JSON text of this JSONObject. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the object contains an invalid number. - */ - public String toString(int indentFactor) throws JSONException { - StringWriter w = new StringWriter(); - synchronized (w.getBuffer()) { - return this.write(w, indentFactor, 0).toString(); - } - } - - /** - * Make a JSON text of an Object value. If the object has an - * value.toJSONString() method, then that method will be used to produce the - * JSON text. The method is required to produce a strictly conforming text. - * If the object does not contain a toJSONString method (which is the most - * common case), then a text will be produced by other means. If the value - * is an array or Collection, then a JSONArray will be made from it and its - * toJSONString method will be called. If the value is a MAP, then a - * JSONObject will be made from it and its toJSONString method will be - * called. Otherwise, the value's toString method will be called, and the - * result will be quoted. - * - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param value - * The value to be serialized. - * @return a printable, displayable, transmittable representation of the - * object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. - */ - public static String valueToString(Object value) throws JSONException { - if (value == null) { - return "null"; - } - if (value instanceof JSONString) { - Object object; - try { - object = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - if (object instanceof String) { - return (String) object; - } - throw new JSONException("Bad value from toJSONString: " + object); - } - if (value instanceof Number) { - return numberToString((Number) value); - } - if (value instanceof Boolean || value instanceof JSONObject - || value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - return new JSONObject((Map)value).toString(); - } - if (value instanceof Collection) { - return new JSONArray((Collection) value).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - return quote(value.toString()); - } - - /** - * Wrap an object, if necessary. If the object is null, return the NULL - * object. If it is an array or collection, wrap it in a JSONArray. If it is - * a map, wrap it in a JSONObject. If it is a standard property (Double, - * String, et al) then it is already wrapped. Otherwise, if it comes from - * one of the java packages, turn it into a string. And if it doesn't, try - * to wrap it in a JSONObject. If the wrapping fails, then null is returned. - * - * @param object - * The object to wrap - * @return The wrapped value - */ - public static Object wrap(Object object) { - try { - if (object == null) { - return NULL; - } - if (object instanceof JSONObject || object instanceof JSONArray - || NULL.equals(object) || object instanceof JSONString - || object instanceof Byte || object instanceof Character - || object instanceof Short || object instanceof Integer - || object instanceof Long || object instanceof Boolean - || object instanceof Float || object instanceof Double - || object instanceof String) { - return object; - } - - if (object instanceof Collection) { - return new JSONArray((Collection) object); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map) { - return new JSONObject((Map) object); - } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = objectPackage != null ? objectPackage - .getName() : ""; - if (objectPackageName.startsWith("java.") - || objectPackageName.startsWith("javax.") - || object.getClass().getClassLoader() == null) { - return object.toString(); - } - return new JSONObject(object); - } catch (Exception exception) { - return null; - } - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - static final Writer writeValue(Writer writer, Object value, - int indentFactor, int indent) throws JSONException, IOException { - if (value == null) { - writer.write("null"); - } else if (value instanceof JSONObject) { - ((JSONObject) value).write(writer, indentFactor, indent); - } else if (value instanceof JSONArray) { - ((JSONArray) value).write(writer, indentFactor, indent); - } else if (value instanceof Map) { - new JSONObject((Map) value).write(writer, indentFactor, indent); - } else if (value instanceof Collection) { - new JSONArray((Collection) value).write(writer, indentFactor, - indent); - } else if (value.getClass().isArray()) { - new JSONArray(value).write(writer, indentFactor, indent); - } else if (value instanceof Number) { - writer.write(numberToString((Number) value)); - } else if (value instanceof Boolean) { - writer.write(value.toString()); - } else if (value instanceof JSONString) { - Object o; - try { - o = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - writer.write(o != null ? o.toString() : quote(value.toString())); - } else { - quote(value.toString(), writer); - } - return writer; - } - - static final void indent(Writer writer, int indent) throws IOException { - for (int i = 0; i < indent; i += 1) { - writer.write(' '); - } - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean commanate = false; - final int length = this.length(); - Iterator keys = this.keys(); - writer.write('{'); - - if (length == 1) { - Object key = keys.next(); - writer.write(quote(key.toString())); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, indent); - } else if (length != 0) { - final int newindent = indent + indentFactor; - while (keys.hasNext()) { - Object key = keys.next(); - if (commanate) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, newindent); - writer.write(quote(key.toString())); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, newindent); - commanate = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, indent); - } - writer.write('}'); - return writer; - } catch (IOException exception) { - throw new JSONException(exception); - } - } -} diff --git a/src/main/java/org/json/JSONString.java b/src/main/java/org/json/JSONString.java deleted file mode 100644 index 1f2d77d..0000000 --- a/src/main/java/org/json/JSONString.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.json; -/** - * The JSONString interface allows a toJSONString() - * method so that a class can change the behavior of - * JSONObject.toString(), JSONArray.toString(), - * and JSONWriter.value(Object). The - * toJSONString method will be used instead of the default behavior - * of using the Object's toString() method and quoting the result. - */ -public interface JSONString { - /** - * The toJSONString method allows a class to produce its own JSON - * serialization. - * - * @return A strictly syntactically correct JSON text. - */ - public String toJSONString(); -} diff --git a/src/main/java/org/json/JSONStringer.java b/src/main/java/org/json/JSONStringer.java deleted file mode 100644 index 25c2e5d..0000000 --- a/src/main/java/org/json/JSONStringer.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.json; - -/* -Copyright (c) 2006 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import java.io.StringWriter; - -/** - * JSONStringer provides a quick and convenient way of producing JSON text. - * The texts produced strictly conform to JSON syntax rules. No whitespace is - * added, so the results are ready for transmission or storage. Each instance of - * JSONStringer can produce one JSON text. - *

- * A JSONStringer instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting cascade style. For example,

- * myString = new JSONStringer()
- *     .object()
- *         .key("JSON")
- *         .value("Hello, World!")
- *     .endObject()
- *     .toString();
which produces the string
- * {"JSON":"Hello, World!"}
- *

- * The first method called must be array or object. - * There are no methods for adding commas or colons. JSONStringer adds them for - * you. Objects and arrays can be nested up to 20 levels deep. - *

- * This can sometimes be easier than using a JSONObject to build a string. - * @author JSON.org - * @version 2008-09-18 - */ -public class JSONStringer extends JSONWriter { - /** - * Make a fresh JSONStringer. It can be used to build one JSON text. - */ - public JSONStringer() { - super(new StringWriter()); - } - - /** - * Return the JSON text. This method is used to obtain the product of the - * JSONStringer instance. It will return null if there was a - * problem in the construction of the JSON text (such as the calls to - * array were not properly balanced with calls to - * endArray). - * @return The JSON text. - */ - public String toString() { - return this.mode == 'd' ? this.writer.toString() : null; - } -} diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java deleted file mode 100644 index 7c3389c..0000000 --- a/src/main/java/org/json/JSONTokener.java +++ /dev/null @@ -1,448 +0,0 @@ -package org.json; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/** - * A JSONTokener takes a source string and extracts characters and tokens from - * it. It is used by the JSONObject and JSONArray constructors to parse - * JSON source strings. - * @author JSON.org - * @version 2014-05-03 - */ -public class JSONTokener { - - private long character; - private boolean eof; - private long index; - private long line; - private char previous; - private Reader reader; - private boolean usePrevious; - - - /** - * Construct a JSONTokener from a Reader. - * - * @param reader A reader. - */ - public JSONTokener(Reader reader) { - this.reader = reader.markSupported() - ? reader - : new BufferedReader(reader); - this.eof = false; - this.usePrevious = false; - this.previous = 0; - this.index = 0; - this.character = 1; - this.line = 1; - } - - - /** - * Construct a JSONTokener from an InputStream. - * @param inputStream The source. - */ - public JSONTokener(InputStream inputStream) throws JSONException { - this(new InputStreamReader(inputStream)); - } - - - /** - * Construct a JSONTokener from a string. - * - * @param s A source string. - */ - public JSONTokener(String s) { - this(new StringReader(s)); - } - - - /** - * Back up one character. This provides a sort of lookahead capability, - * so that you can test for a digit or letter before attempting to parse - * the next number or identifier. - */ - public void back() throws JSONException { - if (this.usePrevious || this.index <= 0) { - throw new JSONException("Stepping back two steps is not supported"); - } - this.index -= 1; - this.character -= 1; - this.usePrevious = true; - this.eof = false; - } - - - /** - * Get the hex value of a character (base16). - * @param c A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. - */ - public static int dehexchar(char c) { - if (c >= '0' && c <= '9') { - return c - '0'; - } - if (c >= 'A' && c <= 'F') { - return c - ('A' - 10); - } - if (c >= 'a' && c <= 'f') { - return c - ('a' - 10); - } - return -1; - } - - public boolean end() { - return this.eof && !this.usePrevious; - } - - - /** - * Determine if the source string still contains characters that next() - * can consume. - * @return true if not yet at the end of the source. - */ - public boolean more() throws JSONException { - this.next(); - if (this.end()) { - return false; - } - this.back(); - return true; - } - - - /** - * Get the next character in the source string. - * - * @return The next character, or 0 if past the end of the source string. - */ - public char next() throws JSONException { - int c; - if (this.usePrevious) { - this.usePrevious = false; - c = this.previous; - } else { - try { - c = this.reader.read(); - } catch (IOException exception) { - throw new JSONException(exception); - } - - if (c <= 0) { // End of stream - this.eof = true; - c = 0; - } - } - this.index += 1; - if (this.previous == '\r') { - this.line += 1; - this.character = c == '\n' ? 0 : 1; - } else if (c == '\n') { - this.line += 1; - this.character = 0; - } else { - this.character += 1; - } - this.previous = (char) c; - return this.previous; - } - - - /** - * Consume the next character, and check that it matches a specified - * character. - * @param c The character to match. - * @return The character. - * @throws JSONException if the character does not match. - */ - public char next(char c) throws JSONException { - char n = this.next(); - if (n != c) { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + - n + "'"); - } - return n; - } - - - /** - * Get the next n characters. - * - * @param n The number of characters to take. - * @return A string of n characters. - * @throws JSONException - * Substring bounds error if there are not - * n characters remaining in the source string. - */ - public String next(int n) throws JSONException { - if (n == 0) { - return ""; - } - - char[] chars = new char[n]; - int pos = 0; - - while (pos < n) { - chars[pos] = this.next(); - if (this.end()) { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } - - - /** - * Get the next char in the string, skipping whitespace. - * @throws JSONException - * @return A character, or 0 if there are no more characters. - */ - public char nextClean() throws JSONException { - for (;;) { - char c = this.next(); - if (c == 0 || c > ' ') { - return c; - } - } - } - - - /** - * Return the characters up to the next close quote character. - * Backslash processing is done. The formal JSON format does not - * allow strings in single quotes, but an implementation is allowed to - * accept them. - * @param quote The quoting character, either - * " (double quote) or - * ' (single quote). - * @return A String. - * @throws JSONException Unterminated string. - */ - public String nextString(char quote) throws JSONException { - char c; - StringBuilder sb = new StringBuilder(); - for (;;) { - c = this.next(); - switch (c) { - case 0: - case '\n': - case '\r': - throw this.syntaxError("Unterminated string"); - case '\\': - c = this.next(); - switch (c) { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - sb.append((char)Integer.parseInt(this.next(4), 16)); - break; - case '"': - case '\'': - case '\\': - case '/': - sb.append(c); - break; - default: - throw this.syntaxError("Illegal escape."); - } - break; - default: - if (c == quote) { - return sb.toString(); - } - sb.append(c); - } - } - } - - - /** - * Get the text up but not including the specified character or the - * end of line, whichever comes first. - * @param delimiter A delimiter character. - * @return A string. - */ - public String nextTo(char delimiter) throws JSONException { - StringBuilder sb = new StringBuilder(); - for (;;) { - char c = this.next(); - if (c == delimiter || c == 0 || c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - - /** - * Get the text up but not including one of the specified delimiter - * characters or the end of line, whichever comes first. - * @param delimiters A set of delimiter characters. - * @return A string, trimmed. - */ - public String nextTo(String delimiters) throws JSONException { - char c; - StringBuilder sb = new StringBuilder(); - for (;;) { - c = this.next(); - if (delimiters.indexOf(c) >= 0 || c == 0 || - c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - - /** - * Get the next value. The value can be a Boolean, Double, Integer, - * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * @throws JSONException If syntax error. - * - * @return An object. - */ - public Object nextValue() throws JSONException { - char c = this.nextClean(); - String string; - - switch (c) { - case '"': - case '\'': - return this.nextString(c); - case '{': - this.back(); - return new JSONObject(this); - case '[': - this.back(); - return new JSONArray(this); - default: - //Added default clause - } - - /* - * Handle unquoted text. This could be the values true, false, or - * null, or it can be a number. An implementation (such as this one) - * is allowed to also accept non-standard forms. - * - * Accumulate characters until we reach the end of the text or a - * formatting character. - */ - - StringBuilder sb = new StringBuilder(); - while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { - sb.append(c); - c = this.next(); - } - this.back(); - - string = sb.toString().trim(); - if ("".equals(string)) { - throw this.syntaxError("Missing value"); - } - return JSONObject.stringToValue(string); - } - - - /** - * Skip characters until the next character is the requested character. - * If the requested character is not found, no characters are skipped. - * @param to A character to skip to. - * @return The requested character, or zero if the requested character - * is not found. - */ - public char skipTo(char to) throws JSONException { - char c; - try { - long startIndex = this.index; - long startCharacter = this.character; - long startLine = this.line; - this.reader.mark(1000000); - do { - c = this.next(); - if (c == 0) { - this.reader.reset(); - this.index = startIndex; - this.character = startCharacter; - this.line = startLine; - return c; - } - } while (c != to); - } catch (IOException exception) { - throw new JSONException(exception); - } - this.back(); - return c; - } - - - /** - * Make a JSONException to signal a syntax error. - * - * @param message The error message. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(String message) { - return new JSONException(message + this.toString()); - } - - - /** - * Make a printable string of this JSONTokener. - * - * @return " at {index} [character {character} line {line}]" - */ - public String toString() { - return " at " + this.index + " [character " + this.character + " line " + - this.line + "]"; - } -} diff --git a/src/main/java/org/json/JSONWriter.java b/src/main/java/org/json/JSONWriter.java deleted file mode 100644 index 07bbc8c..0000000 --- a/src/main/java/org/json/JSONWriter.java +++ /dev/null @@ -1,327 +0,0 @@ -package org.json; - -import java.io.IOException; -import java.io.Writer; - -/* -Copyright (c) 2006 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/** - * JSONWriter provides a quick and convenient way of producing JSON text. - * The texts produced strictly conform to JSON syntax rules. No whitespace is - * added, so the results are ready for transmission or storage. Each instance of - * JSONWriter can produce one JSON text. - *

- * A JSONWriter instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting a cascade style. For example,

- * new JSONWriter(myWriter)
- *     .object()
- *         .key("JSON")
- *         .value("Hello, World!")
- *     .endObject();
which writes
- * {"JSON":"Hello, World!"}
- *

- * The first method called must be array or object. - * There are no methods for adding commas or colons. JSONWriter adds them for - * you. Objects and arrays can be nested up to 20 levels deep. - *

- * This can sometimes be easier than using a JSONObject to build a string. - * @author JSON.org - * @version 2011-11-24 - */ -public class JSONWriter { - private static final int maxdepth = 200; - - /** - * The comma flag determines if a comma should be output before the next - * value. - */ - private boolean comma; - - /** - * The current mode. Values: - * 'a' (array), - * 'd' (done), - * 'i' (initial), - * 'k' (key), - * 'o' (object). - */ - protected char mode; - - /** - * The object/array stack. - */ - private final JSONObject stack[]; - - /** - * The stack top index. A value of 0 indicates that the stack is empty. - */ - private int top; - - /** - * The writer that will receive the output. - */ - protected Writer writer; - - /** - * Make a fresh JSONWriter. It can be used to build one JSON text. - */ - public JSONWriter(Writer w) { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; - } - - /** - * Append a value. - * @param string A string value. - * @return this - * @throws JSONException If the value is out of sequence. - */ - private JSONWriter append(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null pointer"); - } - if (this.mode == 'o' || this.mode == 'a') { - try { - if (this.comma && this.mode == 'a') { - this.writer.write(','); - } - this.writer.write(string); - } catch (IOException e) { - throw new JSONException(e); - } - if (this.mode == 'o') { - this.mode = 'k'; - } - this.comma = true; - return this; - } - throw new JSONException("Value out of sequence."); - } - - /** - * Begin appending a new array. All values until the balancing - * endArray will be appended to this array. The - * endArray method must be called to mark the array's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter array() throws JSONException { - if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } - - /** - * End something. - * @param mode Mode - * @param c Closing character - * @return this - * @throws JSONException If unbalanced. - */ - private JSONWriter end(char mode, char c) throws JSONException { - if (this.mode != mode) { - throw new JSONException(mode == 'a' - ? "Misplaced endArray." - : "Misplaced endObject."); - } - this.pop(mode); - try { - this.writer.write(c); - } catch (IOException e) { - throw new JSONException(e); - } - this.comma = true; - return this; - } - - /** - * End an array. This method most be called to balance calls to - * array. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); - } - - /** - * End an object. This method most be called to balance calls to - * object. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endObject() throws JSONException { - return this.end('k', '}'); - } - - /** - * Append a key. The key will be associated with the next value. In an - * object, every value must be preceded by a key. - * @param string A key string. - * @return this - * @throws JSONException If the key is out of place. For example, keys - * do not belong in arrays or if the key is null. - */ - public JSONWriter key(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - this.stack[this.top - 1].putOnce(string, Boolean.TRUE); - if (this.comma) { - this.writer.write(','); - } - this.writer.write(JSONObject.quote(string)); - this.writer.write(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch (IOException e) { - throw new JSONException(e); - } - } - throw new JSONException("Misplaced key."); - } - - - /** - * Begin appending a new object. All keys and values until the balancing - * endObject will be appended to this object. The - * endObject method must be called to mark the object's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter object() throws JSONException { - if (this.mode == 'i') { - this.mode = 'o'; - } - if (this.mode == 'o' || this.mode == 'a') { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); - - } - - - /** - * Pop an array or object scope. - * @param c The scope to close. - * @throws JSONException If nesting is wrong. - */ - private void pop(char c) throws JSONException { - if (this.top <= 0) { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if (m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 - ? 'd' - : this.stack[this.top - 1] == null - ? 'a' - : 'k'; - } - - /** - * Push an array or object scope. - * @param jo The scope to open. - * @throws JSONException If nesting is too deep. - */ - private void push(JSONObject jo) throws JSONException { - if (this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } - - - /** - * Append either the value true or the value - * false. - * @param b A boolean. - * @return this - * @throws JSONException - */ - public JSONWriter value(boolean b) throws JSONException { - return this.append(b ? "true" : "false"); - } - - /** - * Append a double value. - * @param d A double. - * @return this - * @throws JSONException If the number is not finite. - */ - public JSONWriter value(double d) throws JSONException { - return this.value(new Double(d)); - } - - /** - * Append a long value. - * @param l A long. - * @return this - * @throws JSONException - */ - public JSONWriter value(long l) throws JSONException { - return this.append(Long.toString(l)); - } - - - /** - * Append an object value. - * @param object The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements JSONString. - * @return this - * @throws JSONException If the value is out of sequence. - */ - public JSONWriter value(Object object) throws JSONException { - return this.append(JSONObject.valueToString(object)); - } -} diff --git a/src/main/java/org/json/Kim.java b/src/main/java/org/json/Kim.java deleted file mode 100644 index 5456112..0000000 --- a/src/main/java/org/json/Kim.java +++ /dev/null @@ -1,376 +0,0 @@ -package org.json; - - -/* - Copyright (c) 2013 JSON.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - The Software shall be used for Good, not Evil. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - */ - -/** - * Kim makes immutable eight bit Unicode strings. If the MSB of a byte is set, - * then the next byte is a continuation byte. The last byte of a character - * never has the MSB reset. Every byte that is not the last byte has the MSB - * set. Kim stands for "Keep it minimal". A Unicode character is never longer - * than 3 bytes. Every byte contributes 7 bits to the character. ASCII is - * unmodified. - * - * Kim UTF-8 - * one byte U+007F U+007F - * two bytes U+3FFF U+07FF - * three bytes U+10FFF U+FFFF - * four bytes U+10FFFF - * - * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one - * byte smaller when encoded in Kim compared to UTF-8. - * - * Kim is beneficial when using scripts such as Old South Arabian, Aramaic, - * Avestan, Balinese, Batak, Bopomofo, Buginese, Buhid, Carian, Cherokee, - * Coptic, Cyrillic, Deseret, Egyptian Hieroglyphs, Ethiopic, Georgian, - * Glagolitic, Gothic, Hangul Jamo, Hanunoo, Hiragana, Kanbun, Kaithi, - * Kannada, Katakana, Kharoshthi, Khmer, Lao, Lepcha, Limbu, Lycian, Lydian, - * Malayalam, Mandaic, Meroitic, Miao, Mongolian, Myanmar, New Tai Lue, - * Ol Chiki, Old Turkic, Oriya, Osmanya, Pahlavi, Parthian, Phags-Pa, - * Phoenician, Samaritan, Sharada, Sinhala, Sora Sompeng, Tagalog, Tagbanwa, - * Takri, Tai Le, Tai Tham, Tamil, Telugu, Thai, Tibetan, Tifinagh, UCAS. - * - * A kim object can be constructed from an ordinary UTF-16 string, or from a - * byte array. A kim object can produce a UTF-16 string. - * - * As with UTF-8, it is possible to detect character boundaries within a byte - * sequence. UTF-8 is one of the world's great inventions. While Kim is more - * efficient, it is not clear that it is worth the expense of transition. - * - * @version 2013-04-18 - */ -public class Kim { - - /** - * The byte array containing the kim's content. - */ - private byte[] bytes = null; - - /** - * The kim's hashcode, conforming to Java's hashcode conventions. - */ - private int hashcode = 0; - - /** - * The number of bytes in the kim. The number of bytes can be as much as - * three times the number of characters. - */ - private int length = 0; - - /** - * The memoization of toString(). - */ - private String string = null; - - /** - * Make a kim from a portion of a byte array. - * - * @param bytes - * A byte array. - * @param from - * The index of the first byte. - * @param thru - * The index of the last byte plus one. - */ - public Kim(byte[] bytes, int from, int thru) { - -// As the bytes are copied into the new kim, a hashcode is computed using a -// modified Fletcher code. - - int sum = 1; - int value; - this.hashcode = 0; - this.length = thru - from; - if (this.length > 0) { - this.bytes = new byte[this.length]; - for (int at = 0; at < this.length; at += 1) { - value = (int) bytes[at + from] & 0xFF; - sum += value; - this.hashcode += sum; - this.bytes[at] = (byte) value; - } - this.hashcode += sum << 16; - } - } - - /** - * Make a kim from a byte array. - * - * @param bytes - * The byte array. - * @param length - * The number of bytes. - */ - public Kim(byte[] bytes, int length) { - this(bytes, 0, length); - } - - /** - * Make a new kim from a substring of an existing kim. The coordinates are - * in byte units, not character units. - * - * @param kim - * The source of bytes. - * @param from - * The point at which to take bytes. - * @param thru - * The point at which to stop taking bytes. - */ - public Kim(Kim kim, int from, int thru) { - this(kim.bytes, from, thru); - } - - /** - * Make a kim from a string. - * - * @param string - * The string. - * @throws JSONException - * if surrogate pair mismatch. - */ - public Kim(String string) throws JSONException { - int stringLength = string.length(); - this.hashcode = 0; - this.length = 0; - -// First pass: Determine the length of the kim, allowing for the UTF-16 -// to UTF-32 conversion, and then the UTF-32 to Kim conversion. - - if (stringLength > 0) { - int i = 0; - while (i < stringLength) { - int c = string.charAt(i); - if (c <= 0x7F) { - this.length += 1; - } else if (c <= 0x3FFF) { - this.length += 2; - } else { - if (c >= 0xD800 && c <= 0xDFFF) { - i += 1; - int d = string.charAt(i); - if (c > 0xDBFF || d < 0xDC00 || d > 0xDFFF) { - throw new JSONException("Bad UTF16"); - } - } - this.length += 3; - } - i += 1; - } - -// Second pass: Allocate a byte array and fill that array with the conversion -// while computing the hashcode. - - this.bytes = new byte[length]; - int at = 0; - int b; - int sum = 1; - int x = 0; - while (x < stringLength) { - int character = string.charAt(x); - if (character <= 0x7F) { - bytes[at] = (byte) character; - sum += character; - this.hashcode += sum; - at += 1; - } else if (character <= 0x3FFF) { - b = 0x80 | (character >>> 7); - bytes[at] = (byte) b; - sum += b; - this.hashcode += sum; - at += 1; - b = character & 0x7F; - bytes[at] = (byte) b; - sum += b; - this.hashcode += sum; - at += 1; - } else { - if (character >= 0xD800 && character <= 0xDBFF) { - x += 1; - character = (((character & 0x3FF) << 10) | (string - .charAt(i) & 0x3FF)) + 65536; - } - b = 0x80 | (character >>> 14); - bytes[at] = (byte) b; - sum += b; - this.hashcode += sum; - at += 1; - b = 0x80 | ((character >>> 7) & 0xFF); - bytes[at] = (byte) b; - sum += b; - this.hashcode += sum; - at += 1; - b = character & 0x7F; - bytes[at] = (byte) b; - sum += b; - this.hashcode += sum; - at += 1; - } - x += 1; - } - this.hashcode += sum << 16; - } - } - - /** - * Returns the character at the specified index. The index refers to byte - * values and ranges from 0 to length - 1. The index of the next character - * is at index + Kim.characterSize(kim.characterAt(index)). - * - * @param at - * the index of the char value. The first character is at 0. - * @returns a Unicode character between 0 and 0x10FFFF. - * @throws JSONException - * if at does not point to a valid character. - */ - public int characterAt(int at) throws JSONException { - int c = get(at); - if ((c & 0x80) == 0) { - return c; - } - int character; - int c1 = get(at + 1); - if ((c1 & 0x80) == 0) { - character = ((c & 0x7F) << 7) | c1; - if (character > 0x7F) { - return character; - } - } else { - int c2 = get(at + 2); - character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; - if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF - && (character < 0xD800 || character > 0xDFFF)) { - return character; - } - } - throw new JSONException("Bad character at " + at); - } - - /** - * Returns the number of bytes needed to contain the character in Kim - * format. - * - * @param character - * a Unicode character between 0 and 0x10FFFF. - * @return 1, 2, or 3 - * @throws JSONException - * if the character is not representable in a kim. - */ - public static int characterSize(int character) throws JSONException { - if (character < 0 || character > 0x10FFFF) { - throw new JSONException("Bad character " + character); - } - return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3; - } - - /** - * Copy the contents of this kim to a byte array. - * - * @param bytes - * A byte array of sufficient size. - * @param at - * The position within the byte array to take the byes. - * @return The position immediately after the copy. - */ - public int copy(byte[] bytes, int at) { - System.arraycopy(this.bytes, 0, bytes, at, this.length); - return at + this.length; - } - - /** - * Two kim objects containing exactly the same bytes in the same order are - * equal to each other. - * - * @param obj - * the other kim with which to compare. - * @returns true if this and obj are both kim objects containing identical - * byte sequences. - */ - public boolean equals(Object obj) { - if (!(obj instanceof Kim)) { - return false; - } - Kim that = (Kim) obj; - if (this == that) { - return true; - } - if (this.hashcode != that.hashcode) { - return false; - } - return java.util.Arrays.equals(this.bytes, that.bytes); - } - - /** - * Get a byte from a kim. - * @param at - * The position of the byte. The first byte is at 0. - * @return The byte. - * @throws JSONException - * if there is no byte at that position. - */ - public int get(int at) throws JSONException { - if (at < 0 || at > this.length) { - throw new JSONException("Bad character at " + at); - } - return ((int) this.bytes[at]) & 0xFF; - } - - /** - * Returns a hash code value for the kim. - */ - public int hashCode() { - return this.hashcode; - } - - /** - * Produce a UTF-16 String from this kim. The number of codepoints in the - * string will not be greater than the number of bytes in the kim, although - * it could be less. - * - * @return The string. A kim memoizes its string representation. - * @throws JSONException - * if the kim is not valid. - */ - public String toString() throws JSONException { - if (this.string == null) { - int c; - int charLength = 0; - char chars[] = new char[this.length]; - for (int at = 0; at < this.length; at += characterSize(c)) { - c = this.characterAt(at); - if (c < 0x10000) { - chars[charLength] = (char) c; - charLength += 1; - } else { - chars[charLength] = (char) (0xD800 | ((c - 0x10000) >>> 10)); - charLength += 1; - chars[charLength] = (char) (0xDC00 | (c & 0x03FF)); - charLength += 1; - } - } - this.string = new String(chars, 0, charLength); - } - return this.string; - } -} diff --git a/src/main/java/org/json/Property.java b/src/main/java/org/json/Property.java deleted file mode 100644 index 8122241..0000000 --- a/src/main/java/org/json/Property.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.json; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import java.util.Enumeration; -import java.util.Iterator; -import java.util.Properties; - -/** - * Converts a Property file data into JSONObject and back. - * @author JSON.org - * @version 2014-05-03 - */ -public class Property { - /** - * Converts a property file object into a JSONObject. The property file object is a table of name value pairs. - * @param properties java.util.Properties - * @return JSONObject - * @throws JSONException - */ - public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException { - JSONObject jo = new JSONObject(); - if (properties != null && !properties.isEmpty()) { - Enumeration enumProperties = properties.propertyNames(); - while(enumProperties.hasMoreElements()) { - String name = (String)enumProperties.nextElement(); - jo.put(name, properties.getProperty(name)); - } - } - return jo; - } - - /** - * Converts the JSONObject into a property file object. - * @param jo JSONObject - * @return java.util.Properties - * @throws JSONException - */ - public static Properties toProperties(JSONObject jo) throws JSONException { - Properties properties = new Properties(); - if (jo != null) { - Iterator keys = jo.keys(); - while (keys.hasNext()) { - String name = keys.next(); - properties.put(name, jo.getString(name)); - } - } - return properties; - } -} diff --git a/src/main/java/org/json/README b/src/main/java/org/json/README deleted file mode 100644 index 6afe0c6..0000000 --- a/src/main/java/org/json/README +++ /dev/null @@ -1,68 +0,0 @@ -JSON in Java [package org.json] - -Douglas Crockford -douglas@crockford.com - -2011-02-02 - - -JSON is a light-weight, language independent, data interchange format. -See http://www.JSON.org/ - -The files in this package implement JSON encoders/decoders in Java. -It also includes the capability to convert between JSON and XML, HTTP -headers, Cookies, and CDL. - -This is a reference implementation. There is a large number of JSON packages -in Java. Perhaps someday the Java community will standardize on one. Until -then, choose carefully. - -The license includes this restriction: "The software shall be used for good, -not evil." If your conscience cannot live with that, then choose a different -package. - -The package compiles on Java 1.8. - - -JSONObject.java: The JSONObject can parse text from a String or a JSONTokener -to produce a map-like object. The object provides methods for manipulating its -contents, and for producing a JSON compliant object serialization. - -JSONArray.java: The JSONObject can parse text from a String or a JSONTokener -to produce a vector-like object. The object provides methods for manipulating -its contents, and for producing a JSON compliant array serialization. - -JSONTokener.java: The JSONTokener breaks a text into a sequence of individual -tokens. It can be constructed from a String, Reader, or InputStream. - -JSONException.java: The JSONException is the standard exception type thrown -by this package. - - -JSONString.java: The JSONString interface requires a toJSONString method, -allowing an object to provide its own serialization. - -JSONStringer.java: The JSONStringer provides a convenient facility for -building JSON strings. - -JSONWriter.java: The JSONWriter provides a convenient facility for building -JSON text through a writer. - - -CDL.java: CDL provides support for converting between JSON and comma -delimited lists. - -Cookie.java: Cookie provides support for converting between JSON and cookies. - -CookieList.java: CookieList provides support for converting between JSON and -cookie lists. - -HTTP.java: HTTP provides support for converting between JSON and HTTP headers. - -HTTPTokener.java: HTTPTokener extends JSONTokener for parsing HTTP headers. - -XML.java: XML provides support for converting between JSON and XML. - -JSONML.java: JSONML provides support for converting between JSONML and XML. - -XMLTokener.java: XMLTokener extends JSONTokener for parsing XML text. diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java deleted file mode 100644 index 418adfe..0000000 --- a/src/main/java/org/json/XML.java +++ /dev/null @@ -1,491 +0,0 @@ -package org.json; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import java.util.Iterator; - -/** - * This provides static methods to convert an XML text into a JSONObject, - * and to covert a JSONObject into an XML text. - * @author JSON.org - * @version 2014-05-03 - */ -public class XML { - - /** The Character '&'. */ - public static final Character AMP = '&'; - - /** The Character '''. */ - public static final Character APOS = '\''; - - /** The Character '!'. */ - public static final Character BANG = '!'; - - /** The Character '='. */ - public static final Character EQ = '='; - - /** The Character '>'. */ - public static final Character GT = '>'; - - /** The Character '<'. */ - public static final Character LT = '<'; - - /** The Character '?'. */ - public static final Character QUEST = '?'; - - /** The Character '"'. */ - public static final Character QUOT = '"'; - - /** The Character '/'. */ - public static final Character SLASH = '/'; - - /** - * Replace special characters with XML escapes: - *

-     * & (ampersand) is replaced by &amp;
-     * < (less than) is replaced by &lt;
-     * > (greater than) is replaced by &gt;
-     * " (double quote) is replaced by &quot;
-     * 
- * @param string The string to be escaped. - * @return The escaped string. - */ - public static String escape(String string) { - StringBuilder sb = new StringBuilder(string.length()); - for (int i = 0, length = string.length(); i < length; i++) { - char c = string.charAt(i); - switch (c) { - case '&': - sb.append("&"); - break; - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - case '"': - sb.append("""); - break; - case '\'': - sb.append("'"); - break; - default: - sb.append(c); - } - } - return sb.toString(); - } - - /** - * Throw an exception if the string contains whitespace. - * Whitespace is not allowed in tagNames and attributes. - * @param string A string. - * @throws JSONException - */ - public static void noSpace(String string) throws JSONException { - int i; - int length = string.length(); - if (length == 0) { - throw new JSONException("Empty string."); - } - for (i = 0; i < length; i += 1) { - if (Character.isWhitespace(string.charAt(i))) { - throw new JSONException("'" + string + - "' contains a space character."); - } - } - } - - /** - * Scan the content following the named tag, attaching it to the context. - * @param x The XMLTokener containing the source string. - * @param context The JSONObject that will include the new material. - * @param name The tag name. - * @return true if the close tag is processed. - * @throws JSONException - */ - private static boolean parse(XMLTokener x, JSONObject context, - String name) throws JSONException { - char c; - int i; - JSONObject jsonobject = null; - String string; - String tagName; - Object token; - -// Test for and skip past these forms: -// -// -// -// -// Report errors for these forms: -// <> -// <= -// << - - token = x.nextToken(); - -// "); - return false; - } - x.back(); - } else if (c == '[') { - token = x.nextToken(); - if ("CDATA".equals(token)) { - if (x.next() == '[') { - string = x.nextCDATA(); - if (string.length() > 0) { - context.accumulate("content", string); - } - return false; - } - } - throw x.syntaxError("Expected 'CDATA['"); - } - i = 1; - do { - token = x.nextMeta(); - if (token == null) { - throw x.syntaxError("Missing '>' after ' 0); - return false; - } else if (token == QUEST) { - -// "); - return false; - } else if (token == SLASH) { - -// Close tag - - } else if (token == SLASH) { - if (x.nextToken() != GT) { - throw x.syntaxError("Misshaped tag"); - } - if (jsonobject.length() > 0) { - context.accumulate(tagName, jsonobject); - } else { - context.accumulate(tagName, ""); - } - return false; - -// Content, between <...> and - - } else if (token == GT) { - for (;;) { - token = x.nextContent(); - if (token == null) { - if (tagName != null) { - throw x.syntaxError("Unclosed tag " + tagName); - } - return false; - } else if (token instanceof String) { - string = (String)token; - if (string.length() > 0) { - jsonobject.accumulate("content", - XML.stringToValue(string)); - } - -// Nested element - - } else if (token == LT) { - if (parse(x, jsonobject, tagName)) { - if (jsonobject.length() == 0) { - context.accumulate(tagName, ""); - } else if (jsonobject.length() == 1 && - jsonobject.opt("content") != null) { - context.accumulate(tagName, - jsonobject.opt("content")); - } else { - context.accumulate(tagName, jsonobject); - } - return false; - } - } - } - } else { - throw x.syntaxError("Misshaped tag"); - } - } - } - } - - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. This is much less ambitious than - * JSONObject.stringToValue, especially because it does not attempt to - * convert plus forms, octal forms, hex forms, or E forms lacking decimal - * points. - * @param string A String. - * @return A simple JSON value. - */ - public static Object stringToValue(String string) { - if ("true".equalsIgnoreCase(string)) { - return Boolean.TRUE; - } - if ("false".equalsIgnoreCase(string)) { - return Boolean.FALSE; - } - if ("null".equalsIgnoreCase(string)) { - return JSONObject.NULL; - } - -// If it might be a number, try converting it, first as a Long, and then as a -// Double. If that doesn't work, return the string. - - try { - char initial = string.charAt(0); - if (initial == '-' || (initial >= '0' && initial <= '9')) { - Long value = new Long(string); - if (value.toString().equals(string)) { - return value; - } - } - } catch (Exception ignore) { - try { - Double value = new Double(string); - if (value.toString().equals(string)) { - return value; - } - } catch (Exception ignoreAlso) { - } - } - return string; - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject. Some information may be lost in this transformation - * because JSON is a data format and XML is a document format. XML uses - * elements, attributes, and content text, while JSON uses unordered - * collections of name/value pairs and arrays of values. JSON does not - * does not like to distinguish between elements and attributes. - * Sequences of similar elements are represented as JSONArrays. Content - * text may be placed in a "content" member. Comments, prologs, DTDs, and - * <[ [ ]]> are ignored. - * @param string The source string. - * @return A JSONObject containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - XMLTokener x = new XMLTokener(string); - while (x.more() && x.skipPast("<")) { - parse(x, jo, null); - } - return jo; - } - - - /** - * Convert a JSONObject into a well-formed, element-normal XML string. - * @param object A JSONObject. - * @return A string. - * @throws JSONException - */ - public static String toString(Object object) throws JSONException { - return toString(object, null); - } - - - /** - * Convert a JSONObject into a well-formed, element-normal XML string. - * @param object A JSONObject. - * @param tagName The optional name of the enclosing tag. - * @return A string. - * @throws JSONException - */ - public static String toString(Object object, String tagName) - throws JSONException { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - JSONObject jo; - String key; - Iterator keys; - int length; - String string; - Object value; - if (object instanceof JSONObject) { - -// Emit - - if (tagName != null) { - sb.append('<'); - sb.append(tagName); - sb.append('>'); - } - -// Loop thru the keys. - - jo = (JSONObject)object; - keys = jo.keys(); - while (keys.hasNext()) { - key = keys.next(); - value = jo.opt(key); - if (value == null) { - value = ""; - } - string = value instanceof String ? (String)value : null; - -// Emit content in body - - if ("content".equals(key)) { - if (value instanceof JSONArray) { - ja = (JSONArray)value; - length = ja.length(); - for (i = 0; i < length; i += 1) { - if (i > 0) { - sb.append('\n'); - } - sb.append(escape(ja.get(i).toString())); - } - } else { - sb.append(escape(value.toString())); - } - -// Emit an array of similar keys - - } else if (value instanceof JSONArray) { - ja = (JSONArray)value; - length = ja.length(); - for (i = 0; i < length; i += 1) { - value = ja.get(i); - if (value instanceof JSONArray) { - sb.append('<'); - sb.append(key); - sb.append('>'); - sb.append(toString(value)); - sb.append("'); - } else { - sb.append(toString(value, key)); - } - } - } else if ("".equals(value)) { - sb.append('<'); - sb.append(key); - sb.append("/>"); - -// Emit a new tag - - } else { - sb.append(toString(value, key)); - } - } - if (tagName != null) { - -// Emit the close tag - - sb.append("'); - } - return sb.toString(); - -// XML does not have good support for arrays. If an array appears in a place -// where XML is lacking, synthesize an element. - - } else { - if (object.getClass().isArray()) { - object = new JSONArray(object); - } - if (object instanceof JSONArray) { - ja = (JSONArray)object; - length = ja.length(); - for (i = 0; i < length; i += 1) { - sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); - } - return sb.toString(); - } else { - string = (object == null) ? "null" : escape(object.toString()); - return (tagName == null) ? "\"" + string + "\"" : - (string.length() == 0) ? "<" + tagName + "/>" : - "<" + tagName + ">" + string + ""; - } - } - } -} diff --git a/src/main/java/org/json/XMLTokener.java b/src/main/java/org/json/XMLTokener.java deleted file mode 100644 index 20937f5..0000000 --- a/src/main/java/org/json/XMLTokener.java +++ /dev/null @@ -1,369 +0,0 @@ -package org.json; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/** - * The XMLTokener extends the JSONTokener to provide additional methods - * for the parsing of XML texts. - * @author JSON.org - * @version 2014-05-03 - */ -public class XMLTokener extends JSONTokener { - - - /** The table of entity values. It initially contains Character values for - * amp, apos, gt, lt, quot. - */ - public static final java.util.HashMap entity; - - static { - entity = new java.util.HashMap(8); - entity.put("amp", XML.AMP); - entity.put("apos", XML.APOS); - entity.put("gt", XML.GT); - entity.put("lt", XML.LT); - entity.put("quot", XML.QUOT); - } - - /** - * Construct an XMLTokener from a string. - * @param s A source string. - */ - public XMLTokener(String s) { - super(s); - } - - /** - * Get the text in the CDATA block. - * @return The string up to the ]]>. - * @throws JSONException If the ]]> is not found. - */ - public String nextCDATA() throws JSONException { - char c; - int i; - StringBuilder sb = new StringBuilder(); - for (;;) { - c = next(); - if (end()) { - throw syntaxError("Unclosed CDATA"); - } - sb.append(c); - i = sb.length() - 3; - if (i >= 0 && sb.charAt(i) == ']' && - sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { - sb.setLength(i); - return sb.toString(); - } - } - } - - - /** - * Get the next XML outer token, trimming whitespace. There are two kinds - * of tokens: the '<' character which begins a markup tag, and the content - * text between markup tags. - * - * @return A string, or a '<' Character, or null if there is no more - * source text. - * @throws JSONException - */ - public Object nextContent() throws JSONException { - char c; - StringBuilder sb; - do { - c = next(); - } while (Character.isWhitespace(c)); - if (c == 0) { - return null; - } - if (c == '<') { - return XML.LT; - } - sb = new StringBuilder(); - for (;;) { - if (c == '<' || c == 0) { - back(); - return sb.toString().trim(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - c = next(); - } - } - - - /** - * Return the next entity. These entities are translated to Characters: - * & ' > < ". - * @param ampersand An ampersand character. - * @return A Character or an entity String if the entity is not recognized. - * @throws JSONException If missing ';' in XML entity. - */ - public Object nextEntity(char ampersand) throws JSONException { - StringBuilder sb = new StringBuilder(); - for (;;) { - char c = next(); - if (Character.isLetterOrDigit(c) || c == '#') { - sb.append(Character.toLowerCase(c)); - } else if (c == ';') { - break; - } else { - throw syntaxError("Missing ';' in XML entity: &" + sb); - } - } - String string = sb.toString(); - Object object = entity.get(string); - return object != null ? object : ampersand + string + ";"; - } - - - /** - * Returns the next XML meta token. This is used for skipping over - * and structures. - * @return Syntax characters (< > / = ! ?) are returned as - * Character, and strings and names are returned as Boolean. We don't care - * what the values actually are. - * @throws JSONException If a string is not properly closed or if the XML - * is badly structured. - */ - public Object nextMeta() throws JSONException { - char c; - char q; - do { - c = next(); - } while (Character.isWhitespace(c)); - switch (c) { - case 0: - throw syntaxError("Misshaped meta tag"); - case '<': - return XML.LT; - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); - } - if (c == q) { - return Boolean.TRUE; - } - } - default: - for (;;) { - c = next(); - if (Character.isWhitespace(c)) { - return Boolean.TRUE; - } - switch (c) { - case 0: - case '<': - case '>': - case '/': - case '=': - case '!': - case '?': - case '"': - case '\'': - back(); - return Boolean.TRUE; - default: - //Added default clause - } - } - } - } - - - /** - * Get the next XML Token. These tokens are found inside of angle - * brackets. It may be one of these characters: / > = ! ? or it - * may be a string wrapped in single quotes or double quotes, or it may be a - * name. - * @return a String or a Character. - * @throws JSONException If the XML is not well formed. - */ - public Object nextToken() throws JSONException { - char c; - char q; - StringBuilder sb; - do { - c = next(); - } while (Character.isWhitespace(c)); - switch (c) { - case 0: - throw syntaxError("Misshaped element"); - case '<': - throw syntaxError("Misplaced '<'"); - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - -// Quoted string - - case '"': - case '\'': - q = c; - sb = new StringBuilder(); - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); - } - if (c == q) { - return sb.toString(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - } - default: - -// Name - - sb = new StringBuilder(); - for (;;) { - sb.append(c); - c = next(); - if (Character.isWhitespace(c)) { - return sb.toString(); - } - switch (c) { - case 0: - return sb.toString(); - case '>': - case '/': - case '=': - case '!': - case '?': - case '[': - case ']': - back(); - return sb.toString(); - case '<': - case '"': - case '\'': - throw syntaxError("Bad character in a name"); - default: - //Added default clause - } - } - } - } - - - /** - * Skip characters until past the requested string. - * If it is not found, we are left at the end of the source with a result of false. - * @param to A string to skip past. - * @throws JSONException - */ - public boolean skipPast(String to) throws JSONException { - boolean b; - char c; - int i; - int j; - int offset = 0; - int length = to.length(); - char[] circle = new char[length]; - - /* - * First fill the circle buffer with as many characters as are in the - * to string. If we reach an early end, bail. - */ - - for (i = 0; i < length; i += 1) { - c = next(); - if (c == 0) { - return false; - } - circle[i] = c; - } - - /* We will loop, possibly for all of the remaining characters. */ - - for (;;) { - j = offset; - b = true; - - /* Compare the circle buffer with the to string. */ - - for (i = 0; i < length; i += 1) { - if (circle[j] != to.charAt(i)) { - b = false; - break; - } - j += 1; - if (j >= length) { - j -= length; - } - } - - /* If we exit the loop with b intact, then victory is ours. */ - - if (b) { - return true; - } - - /* Get the next character. If there isn't one, then defeat is ours. */ - - c = next(); - if (c == 0) { - return false; - } - /* - * Shove the character in the circle buffer and advance the - * circle offset. The offset is mod n. - */ - circle[offset] = c; - offset += 1; - if (offset >= length) { - offset -= length; - } - } - } -} From 4d08affe85545b26afed5461585bc8bd710d5a85 Mon Sep 17 00:00:00 2001 From: Fiqare-Emergya Date: Tue, 17 Dec 2019 17:06:34 +0100 Subject: [PATCH 45/51] Fixes --- .gitignore | 6 ------ .travis.yml | 2 +- sonar-project.properties | 9 --------- 3 files changed, 1 insertion(+), 16 deletions(-) delete mode 100644 sonar-project.properties diff --git a/.gitignore b/.gitignore index a4af3ff..05d31dd 100644 --- a/.gitignore +++ b/.gitignore @@ -10,10 +10,6 @@ .idea .swp -.classpath -.project -.scannerwork -.settings # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* @@ -21,5 +17,3 @@ hs_err_pid* target nb-configuration.xml nbactions.xml - -"" diff --git a/.travis.yml b/.travis.yml index 91806fc..3686035 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,7 +30,7 @@ jdk: - openjdk11 branches: only: - - fiqare-perseo-core-improvements + - master install: - mvn test -B diff --git a/sonar-project.properties b/sonar-project.properties deleted file mode 100644 index 36ea78c..0000000 --- a/sonar-project.properties +++ /dev/null @@ -1,9 +0,0 @@ -sonar.projectKey=fiware-perseo-core-dev-jafernandez -sonar.projectName=Fiware Perseo Core Dev JaFernandez -sonar.projectVersion=1.0 -sonar.sources=. -sonar.java.binaries=. -sonar.exclusions=target/** -sonar.junit.reportPaths=target/surefire-reports -sonar.jacoco.reportPaths=target/jacoco.exec -sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml \ No newline at end of file From 05982ba4eefed043b201d8b95eb1c9b6190d2673 Mon Sep 17 00:00:00 2001 From: Fiqare-Emergya Date: Thu, 16 Jan 2020 11:12:55 +0100 Subject: [PATCH 46/51] pr fixes --- .travis.yml | 5 +- perseo-main/pom.xml | 2 +- .../telefonica/iot/perseo/EventsServlet.java | 12 +-- .../iot/perseo/LogLevelServlet.java | 12 +-- .../telefonica/iot/perseo/RulesServlet.java | 34 ++++---- .../iot/perseo/utils/DateTimeUtils.java | 85 ++++++++++++------- 6 files changed, 86 insertions(+), 64 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3686035..97c2b0a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,9 +30,10 @@ jdk: - openjdk11 branches: only: - - master + - /.*/ + install: - mvn test -B before_install: - - mvn clean + - mvn clean \ No newline at end of file diff --git a/perseo-main/pom.xml b/perseo-main/pom.xml index 933056b..b3b960c 100644 --- a/perseo-main/pom.xml +++ b/perseo-main/pom.xml @@ -87,7 +87,7 @@ org.owasp.encoder encoder 1.2.2 - + diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java index 4c17c99..5117213 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java @@ -90,12 +90,12 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) logger.debug(String.format("event was sent: %s", eventMap)); } catch (Exception je) { try { - logger.error(String.format("error: %s" ,je)); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.getOutputStream().print(String.format("{\"error\":\"%s\"}%n", Encode.forHtmlContent(je.getMessage()))); - }catch(IOException exception) { - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - } + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.getOutputStream().print(String.format("{\"error\":\"%s\"}%n", Encode.forHtmlContent(je.getMessage()))); + } catch (IOException exception) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } } diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java index 1218db5..8eb554b 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java @@ -67,7 +67,7 @@ public class LogLevelServlet extends HttpServlet { protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { - String levelName = request.getParameter("level"); + String levelName = request.getParameter("level"); logger.info(String.format("changing log level to %s",levelName)); Level level = levels.get(levelName); if (level == null) { @@ -82,7 +82,7 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) LogManager.getRootLogger().setLevel(level); } response.setStatus(HttpServletResponse.SC_OK); - }catch(IOException e) { + } catch (IOException e) { logger.error("IOException in log level"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; @@ -109,10 +109,10 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().print(String.format("{\"level\":\"%s\"}",Encode.forHtmlContent(currentLevel))); - }catch(IOException e) { - logger.error("IOException in log level"); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; + } catch (IOException e) { + logger.error("IOException in log level"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; } } diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java index 4ca40a2..82c8af6 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java @@ -91,11 +91,10 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) ruleName = ruleName == null ? "/" : ruleName; Result r = RulesManager.get(epService, ruleName.substring(1)); response.setStatus(r.getStatusCode()); - response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); - - }catch(Exception je) { - logger.error(String.format("error: %s" ,je)); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); + } catch (Exception je) { + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } @@ -115,18 +114,17 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.setContentType("application/json;charset=UTF-8"); try { - String body = Utils.getBodyAsString(request); - - // Save temporary rules, not triggered by events external to the core - TimeRulesStore.getInstance().saveTimeRules(body); - - Result r = RulesManager.make(epService, body); - response.setStatus(r.getStatusCode()); - response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); - }catch(Exception je) { - logger.error(String.format("error: %s" ,je)); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + + // Save temporary rules, not triggered by events external to the core + TimeRulesStore.getInstance().saveTimeRules(body); + + Result r = RulesManager.make(epService, body); + response.setStatus(r.getStatusCode()); + response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); + } catch (Exception je) { + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } @@ -155,7 +153,7 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.updateAll(epService, body); response.setStatus(r.getStatusCode()); response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); - }catch(Exception je) { + } catch (Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } @@ -197,7 +195,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response response.setStatus(r.getStatusCode()); response.getOutputStream().print(r.getMessage()); - }catch(Exception je) { + } catch (Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); diff --git a/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java b/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java index d3f64df..487f1e9 100644 --- a/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java +++ b/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java @@ -3,17 +3,23 @@ * * This file is part of perseo-core project. * - * perseo-core is free software: you can redistribute it and/or modify it under the terms of the GNU - * General Public License version 2 as published by the Free Software Foundation. + * perseo-core is free software: you can redistribute it and/or + * modify it under the terms of the GNU + * General Public License version 2 as published by the Free Software + * Foundation. * - * perseo-core is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * perseo-core is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the + * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License * for more details. * - * You should have received a copy of the GNU General Public License along with perseo-core. If not, see + * You should have received a copy of the GNU General Public License + * along with perseo-core. If not, see * http://www.gnu.org/licenses/. * - * For those usages not covered by the GNU General Public License please contact with + * For those usages not covered by the GNU General Public License + * please contact with * iot_support at tid dot es */ @@ -22,12 +28,9 @@ import ca.rmen.sunrisesunset.SunriseSunset; import java.time.LocalDateTime; import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.GregorianCalendar; -import java.util.TimeZone; import java.util.concurrent.TimeUnit; /** @@ -40,19 +43,23 @@ public class DateTimeUtils { * Gets next sunrise. * Uses car.men.sunrisesunset library * It calculates next sunrise considering provided date and time - * If date and time provided is older than sunrise it adds +1 day to date and calculates again + * If date and time provided is older than sunrise it adds +1 day + * to date and calculates again * * @param day the day Calendar object on ISO format * @param latitude the latitude * @param longitude the longitude * @return the next sunrise */ - public static Calendar getNextSunrise(Calendar day, double latitude, double longitude) { - Calendar[] sunriseSunset = SunriseSunset.getSunriseSunset(day, latitude, longitude); + public static Calendar getNextSunrise(Calendar day, + double latitude, double longitude) { + Calendar[] sunriseSunset = SunriseSunset.getSunriseSunset(day, + latitude, longitude); Calendar day2 = (Calendar) day.clone(); if (sunriseSunset[0].compareTo(day) < 0) { day2.add(Calendar.DATE, 1); - sunriseSunset = SunriseSunset.getSunriseSunset(day2, latitude, longitude); + sunriseSunset = SunriseSunset.getSunriseSunset(day2, + latitude, longitude); } return sunriseSunset[0]; } @@ -61,19 +68,23 @@ public static Calendar getNextSunrise(Calendar day, double latitude, double long * Gets next sunset. * Uses car.men.sunrisesunset library * It calculates next sunset considering provided date and time - * If date and time provided is older than sunset it adds +1 day to date and calculates again + * If date and time provided is older than sunset it adds +1 day + * to date and calculates again * * @param day the day Calendar object on ISO format * @param latitude the latitude * @param longitude the longitude * @return the next sunset */ - public static Calendar getNextSunset(Calendar day, double latitude, double longitude) { - Calendar[] sunriseSunset = SunriseSunset.getSunriseSunset(day, latitude, longitude); + public static Calendar getNextSunset(Calendar day, + double latitude, double longitude) { + Calendar[] sunriseSunset = SunriseSunset.getSunriseSunset(day, + latitude, longitude); Calendar day2 = (Calendar) day.clone(); if (sunriseSunset[1].compareTo(day) < 0) { day2.add(Calendar.DATE, 1); - sunriseSunset = SunriseSunset.getSunriseSunset(day2, latitude, longitude); + sunriseSunset = SunriseSunset.getSunriseSunset(day2, + latitude, longitude); } return sunriseSunset[1]; } @@ -81,7 +92,8 @@ public static Calendar getNextSunset(Calendar day, double latitude, double longi /** * Gets milis to next sunrise. * It calculates next sunrise considering provided date and time - * If date and time provided is older than sunrise it adds +1 day to date and calculates again + * If date and time provided is older than sunrise it adds +1 day + * to date and calculates again * Finally, tunrns result into miliseconds * * @param day the day Calendar object on ISO format @@ -89,7 +101,8 @@ public static Calendar getNextSunset(Calendar day, double latitude, double longi * @param longitude the longitude * @return the milis to next sunrise */ - public static long getMilisToNextSunrise(Calendar day, double latitude, double longitude) { + public static long getMilisToNextSunrise(Calendar day, + double latitude, double longitude) { Calendar sunriseSunrise = getNextSunrise(day, latitude, longitude); return (sunriseSunrise.getTimeInMillis() - day.getTimeInMillis()); } @@ -97,7 +110,8 @@ public static long getMilisToNextSunrise(Calendar day, double latitude, double l /** * Gets seconds to next sunset. * It calculates next sunset considering provided date and time - * If date and time provided is older than sunset it adds +1 day to date and calculates again + * If date and time provided is older than sunset it adds +1 day + * to date and calculates again * Finally, tunrns result into seconds * * @param day the day Calendar object on ISO format @@ -105,18 +119,21 @@ public static long getMilisToNextSunrise(Calendar day, double latitude, double l * @param longitude the longitude * @return the seconds to next sunset */ - public static long getSecondsToNextSunset(Calendar day, double latitude, double longitude) { + public static long getSecondsToNextSunset(Calendar day, + double latitude, double longitude) { long sunriseSunset = getMilisToNextSunset(day, latitude, longitude); long seconds = TimeUnit.MILLISECONDS.toSeconds(sunriseSunset); - if ((seconds*1000) < sunriseSunset) + if ((seconds * 1000) < sunriseSunset) { seconds += 1; + } return seconds; } /** * Gets seconds to next sunrise. * It calculates next sunrise considering provided date and time - * If date and time provided is older than sunrise it adds +1 day to date and calculates again + * If date and time provided is older than sunrise it adds +1 day + * to date and calculates again * Finally, tunrns result into seconds * * @param day the day Calendar object on ISO format @@ -124,18 +141,21 @@ public static long getSecondsToNextSunset(Calendar day, double latitude, double * @param longitude the longitude * @return the seconds to next sunrise */ - public static long getSecondsToNextSunrise(Calendar day, double latitude, double longitude) { + public static long getSecondsToNextSunrise(Calendar day, + double latitude, double longitude) { long sunriseSunset = getMilisToNextSunrise(day, latitude, longitude); long seconds = TimeUnit.MILLISECONDS.toSeconds(sunriseSunset); - if ((seconds*1000) < sunriseSunset) + if ((seconds * 1000) < sunriseSunset) { seconds += 1; + } return seconds; } /** * Gets milis to next sunset. * It calculates next sunset considering provided date and time - * If date and time provided is older than sunset it adds +1 day to date and calculates again + * If date and time provided is older than sunset it adds +1 day + * to date and calculates again * Finally, tunrns result into miliseconds * * @param day the day Calendar object on ISO format @@ -143,7 +163,8 @@ public static long getSecondsToNextSunrise(Calendar day, double latitude, double * @param longitude the longitude * @return the milis to next sunset */ - public static long getMilisToNextSunset(Calendar day, double latitude, double longitude) { + public static long getMilisToNextSunset(Calendar day, + double latitude, double longitude) { Calendar sunriseSunset = getNextSunset(day, latitude, longitude); return (sunriseSunset.getTimeInMillis() - day.getTimeInMillis()); } @@ -159,7 +180,8 @@ public static long getMilisToNextSunset(Calendar day, double latitude, double lo public static Calendar dateToUTC(String day) { ZonedDateTime zonedDateTime = ZonedDateTime.parse(day); - ZonedDateTime zonedDateTimeUTC = zonedDateTime.withZoneSameInstant(ZoneId.of("UTC")); + ZonedDateTime zonedDateTimeUTC = zonedDateTime.withZoneSameInstant( + ZoneId.of("UTC")); return (Calendar) GregorianCalendar.from(zonedDateTimeUTC); } @@ -173,10 +195,11 @@ public static Calendar dateToUTC(String day) { * @return hours on UTC format */ - public static int timeToUTC(int time, String timeZone) { - LocalDateTime localDateTime = LocalDateTime.of(LocalDateTime.now().getYear(), + public static int timeToUTC(int time, final String timeZone) { + LocalDateTime localDateTime = LocalDateTime.of(LocalDateTime.now() + .getYear(), LocalDateTime.now().getMonth(), - LocalDateTime.now().getDayOfMonth()+1, + LocalDateTime.now().getDayOfMonth() + 1, time, LocalDateTime.now().getMinute()); ZonedDateTime isoDateZLDT = localDateTime.atZone(ZoneId.of(timeZone)); From 61b8a4c9c7fe92f547917fd56b451a77f39db5f5 Mon Sep 17 00:00:00 2001 From: Fiqare-Emergya Date: Thu, 23 Jan 2020 10:11:04 +0100 Subject: [PATCH 47/51] pr fixes --- .../com/telefonica/iot/perseo/EventsServlet.java | 2 -- .../telefonica/iot/perseo/LogLevelServlet.java | 12 ++++++------ .../com/telefonica/iot/perseo/RulesServlet.java | 16 +++++----------- .../telefonica/iot/perseo/EventsServletTest.java | 2 +- .../iot/perseo/GenericListenerTest.java | 4 ++-- .../iot/perseo/LogLevelServletTest.java | 4 ++-- .../telefonica/iot/perseo/RulesManagerTest.java | 8 ++++---- .../telefonica/iot/perseo/RulesServletTest.java | 10 +++++----- .../com/telefonica/iot/perseo/UtilsTest.java | 12 ++++++------ 9 files changed, 31 insertions(+), 39 deletions(-) diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java index 5117213..0bf7314 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java @@ -96,8 +96,6 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) } catch (IOException exception) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } - - } } diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java index 8eb554b..0ae1d7c 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java @@ -103,12 +103,12 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("getting log level"); synchronized (mutex) { - try { - String currentLevel = LogManager.getRootLogger().getLevel().toString(); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - response.getOutputStream().print(String.format("{\"level\":\"%s\"}",Encode.forHtmlContent(currentLevel))); + try { + String currentLevel = LogManager.getRootLogger().getLevel().toString(); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + response.setStatus(HttpServletResponse.SC_OK); + response.getOutputStream().print(String.format("{\"level\":\"%s\"}",Encode.forHtmlContent(currentLevel))); } catch (IOException e) { logger.error("IOException in log level"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java index 82c8af6..ee0c05d 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java @@ -114,7 +114,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.setContentType("application/json;charset=UTF-8"); try { - String body = Utils.getBodyAsString(request); + String body = Utils.getBodyAsString(request); // Save temporary rules, not triggered by events external to the core TimeRulesStore.getInstance().saveTimeRules(body); @@ -143,8 +143,7 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - try { - + try { String body = Utils.getBodyAsString(request); // Save timed rules, which are not activated by events external to the core @@ -154,11 +153,9 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) response.setStatus(r.getStatusCode()); response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); } catch (Exception je) { - logger.error(String.format("error: %s" ,je)); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } - - } /** @@ -175,9 +172,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - - try { - + try { logger.info(String.format("delete rule %s", request.getPathInfo())); //request.getPathInfo() returns null or the extra path information //that follows the servlet path but precedes the query string and will @@ -198,7 +193,6 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response } catch (Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - } } diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java index 1792f52..7329ec4 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java @@ -62,7 +62,7 @@ public void tearDown() { */ @Test public void testDoPost() throws Exception { - logger.info("doPost"); + logger.info("doPost"); Server server = Help.getServer(EventsServlet.class); server.start(); try { diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java index 4e48668..8ad7c43 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java @@ -65,7 +65,7 @@ public void tearDown() { */ @Test public void testUpdate() { - logger.info("update"); + logger.info("update"); EventBean[] newEvents = new EventBean[0]; EventBean[] oldEvents = new EventBean[0]; GenericListener instance = new GenericListener(); @@ -83,7 +83,7 @@ public void testUpdate() { */ @Test public void testUpdateTimerRule() { - logger.info("update with timed rule"); + logger.info("update with timed rule"); // Add RuleTest in TimeRulesStore Singleton TimeRulesStore tRInfoInstance = TimeRulesStore.getInstance(); tRInfoInstance.cleanAllRules(); diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java index a3a3bd0..5e2ffba 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java @@ -65,7 +65,7 @@ public void tearDown() { */ @Test public void testDoPutOK() throws Exception { - logger.info("doPut log level valid"); + logger.info("doPut log level valid"); Server server = Help.getServer(LogLevelServlet.class); server.start(); try { @@ -87,7 +87,7 @@ public void testDoPutOK() throws Exception { */ @Test public void testDoPutBad() throws Exception { - logger.info("doPut log level invalid"); + logger.info("doPut log level invalid"); Server server = Help.getServer(LogLevelServlet.class); server.start(); try { diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java index ea9d9e1..92dce81 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java @@ -79,7 +79,7 @@ public void tearDown() { */ @Test public void testGet() { - logger.info("get"); + logger.info("get"); String ruleName = "ccc"; String epl = Help.ExampleRules()[0]; EPStatement st = epService.getEPAdministrator().createEPL(epl, ruleName); @@ -96,7 +96,7 @@ public void testGet() { */ @Test public void testMake() { - logger.info("make"); + logger.info("make"); String ruleName = "ccc"; String epl = Help.ExampleRules()[0]; String text = String.format("{\"name\":\"%s\",\"text\":\"%s\"}", ruleName, epl); @@ -113,7 +113,7 @@ public void testMake() { */ @Test public void testUpdateAll() { - logger.info("updateAll"); + logger.info("updateAll"); String ruleName = "ccc"; String epl = Help.ExampleRules()[0]; String text = String.format("[{\"name\":\"%s\",\"text\":\"%s\"}]", ruleName, epl); @@ -133,7 +133,7 @@ public void testUpdateAll() { */ @Test public void testDelete() { - logger.info("delete"); + logger.info("delete"); String ruleName = "ccc"; String epl = Help.ExampleRules()[0]; EPStatement st = epService.getEPAdministrator().createEPL(epl, ruleName); diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java index 3354ff2..92c204c 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java @@ -65,7 +65,7 @@ public void tearDown() { */ @Test public void testDoGet() throws Exception { - logger.info("doGet"); + logger.info("doGet"); Server server = Help.getServer(RulesServlet.class); server.start(); try { @@ -86,7 +86,7 @@ public void testDoGet() throws Exception { */ @Test public void testDoPost() throws Exception { - logger.info("doPost"); + logger.info("doPost"); Server server = Help.getServer(RulesServlet.class); server.start(); try { @@ -114,7 +114,7 @@ public void testDoPost() throws Exception { */ @Test public void testDoPut() throws Exception { - logger.info("doPut"); + logger.info("doPut"); Server server = Help.getServer(RulesServlet.class); server.start(); try { @@ -142,7 +142,7 @@ public void testDoPut() throws Exception { */ @Test public void testDoPutLongSet() throws Exception { - logger.info("doPutLongSet"); + logger.info("doPutLongSet"); Server server = Help.getServer(RulesServlet.class); server.start(); try { @@ -162,7 +162,7 @@ public void testDoPutLongSet() throws Exception { */ @Test public void testDoDelete() throws Exception { - logger.info("doDelete"); + logger.info("doDelete"); Server server = Help.getServer(RulesServlet.class); server.start(); try { diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/UtilsTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/UtilsTest.java index ff9b9b5..3e66782 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/UtilsTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/UtilsTest.java @@ -78,7 +78,7 @@ public void tearDown() { */ @Test public void testInitEPService() { - logger.info("initEPService"); + logger.info("initEPService"); ServletContext sc = new ServletContextMock(); EPServiceProvider result = Utils.initEPService(sc); assertEquals(sc.getAttribute("epService"), result); @@ -93,7 +93,7 @@ public void testInitEPService() { */ @Test public void testDestroyEPService() { - logger.info("destroyEPService"); + logger.info("destroyEPService"); ServletContextMock sc = new ServletContextMock(); //Empty sc Utils.destroyEPService(sc); @@ -109,7 +109,7 @@ public void testDestroyEPService() { */ @Test public void testJSONObject2Map() { - logger.info("JSONObject2Map"); + logger.info("JSONObject2Map"); HashMap m = new HashMap(); m.put("one", "1"); m.put("two", 2); @@ -123,7 +123,7 @@ public void testJSONObject2Map() { */ @Test public void testEvent2JSONObject() { - logger.info("Event2JSONObject"); + logger.info("Event2JSONObject"); HashMap m = new HashMap(); m.put("one", "1"); m.put("two", 2); @@ -163,7 +163,7 @@ public void testStatement2JSONObject() { */ @Test public void testDoHTTPPost() { - logger.info("DoHTTPPost"); + logger.info("DoHTTPPost"); InetSocketAddress address = new InetSocketAddress(Help.PORT); HttpServer httpServer = null; try { @@ -190,7 +190,7 @@ public void handle(HttpExchange exchange) throws IOException { assertEquals(false, result); } catch (IOException ex) { - logger.error(ex.toString()); + logger.error(ex.toString()); fail(ex.toString()); } finally { if (httpServer != null) { From 47ab83625cbfba55660da30a785723e2fd7ecf55 Mon Sep 17 00:00:00 2001 From: Fiqare-Emergya Date: Tue, 28 Jan 2020 10:35:11 +0100 Subject: [PATCH 48/51] pr fixes --- README.md | 6 ++-- documentation/architecture.md | 6 ++-- documentation/deployment.md | 14 +++++----- documentation/images/architecture.dot | 10 +++---- documentation/logs.md | 2 +- .../telefonica/iot/perseo/Configuration.java | 4 +-- .../telefonica/iot/perseo/EventsServlet.java | 6 ++-- .../iot/perseo/LogLevelServlet.java | 8 +++--- .../com/telefonica/iot/perseo/Result.java | 1 - .../telefonica/iot/perseo/RulesManager.java | 5 +--- .../telefonica/iot/perseo/RulesServlet.java | 20 ++++++------- .../java/com/telefonica/iot/perseo/Utils.java | 1 - .../com/telefonica/iot/perseo/Version.java | 1 - .../iot/perseo/EventsServletTest.java | 2 +- .../iot/perseo/GenericListenerTest.java | 2 +- .../iot/perseo/LogLevelServletTest.java | 4 +-- .../iot/perseo/RulesManagerTest.java | 3 -- .../iot/perseo/RulesServletTest.java | 4 +-- .../iot/perseo/TimeRulesStoreTest.java | 7 ++--- .../com/telefonica/iot/perseo/UtilsTest.java | 5 +--- .../com/telefonica/iot/perseo/test/Help.java | 28 ++++++++----------- .../iot/perseo/utils/DateTimeUtils.java | 18 ++++-------- 22 files changed, 66 insertions(+), 91 deletions(-) diff --git a/README.md b/README.md index 3920316..2793183 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,9 @@ This is the code repository for the EPL-server, named perseo-core. * [Architecture](documentation/architecture.md) * [Logs & Alarms](documentation/logs.md) * O&M - * [Deployment](documentation/deployment.md) - * [Configuration](documentation/config.md) - * [Administration](documentation/admin.md) + * [Deployment](documentation/deployment.md) + * [Configuration](documentation/config.md) + * [Administration](documentation/admin.md) * [API](documentation/api.md) * [License](#licence) diff --git a/documentation/architecture.md b/documentation/architecture.md index 816c814..21e73d0 100644 --- a/documentation/architecture.md +++ b/documentation/architecture.md @@ -19,11 +19,11 @@ Being this rule working @Audit select *,"blood_1_action" as iotcepaction, ev.BloodPressure? as Pression, - ev.id? as Meter + ev.id? as Meter from pattern [ every ev=iotEvent(cast(cast(BloodPressure?,String),float)>1.5 - and type="BloodMeter") - ] + and type="BloodMeter") + ] ``` and sending an event ```JSON diff --git a/documentation/deployment.md b/documentation/deployment.md index 5b56280..8b9d6b5 100644 --- a/documentation/deployment.md +++ b/documentation/deployment.md @@ -10,7 +10,7 @@ The only dependecy for perseo-core is the servlet engine container for its WAR f You only need to do this once in your system: - docker build -t perseo . + docker build -t perseo . The parameter `-t perseo` gives the image a name. This name could be anything, or even include an organization like `-t org/fiware-perseo`. This name is later used to run the container based on the image. @@ -22,12 +22,12 @@ If you want to know more about images and the building process you can find it i The following line will run the container, using a manually built image (see above), exposing port `8080`, give it a name -in this case `perseo1`, and present a bash prompt: - docker run -d --name perseo1 -p 8080:8080 perseo + docker run -d --name perseo1 -p 8080:8080 perseo As a result of this command, there is a PERSEO listening on port 8080 on localhost. Try to see if it works now with - curl localhost:8080/perseo-core/version - + curl localhost:8080/perseo-core/version + To get access to the log file of Perseo Core you can run: ``` @@ -40,7 +40,7 @@ The following line will run the container, from Dockerhub, exposing port `8080`, and binding it to a [Perseo Front-End](https://github.com/telefonicaid/perseo-fe) instance (hostname `perseo-frontend`) listening on port 9090. - docker run -d --name perseo_core -h perseocore -p 8080:8080 telefonicaiot/perseo-core:master -perseo_fe_url perseo-frontend:9090 + docker run -d --name perseo_core -h perseocore -p 8080:8080 telefonicaiot/perseo-core:master -perseo_fe_url perseo-frontend:9090 A few points to consider: @@ -121,5 +121,5 @@ Independently of how the service is installed, the log files will need an extern Logrotate is installed as RPM dependency along with perseo. The system is configured to rotate every day and whenever the log file size is greater than 100MB (checked very 30 minutes by default): * For daily rotation: /etc/logrotate.d/logrotate-perseo-daily: which enables daily log rotation * For size-based rotation: - * /etc/sysconfig/logrotate-perseo-size: in addition to the previous rotation, this file ensures log rotation if the log file grows beyond a given threshold (100 MB by default) - * /etc/cron.d/cron-logrotate-perseo-size: which ensures the execution of etc/sysconfig/logrotate-perseo-size at a regular frecuency (default is 30 minutes) + * /etc/sysconfig/logrotate-perseo-size: in addition to the previous rotation, this file ensures log rotation if the log file grows beyond a given threshold (100 MB by default) + * /etc/cron.d/cron-logrotate-perseo-size: which ensures the execution of etc/sysconfig/logrotate-perseo-size at a regular frecuency (default is 30 minutes) diff --git a/documentation/images/architecture.dot b/documentation/images/architecture.dot index 3b5b46a..3e8b9bf 100644 --- a/documentation/images/architecture.dot +++ b/documentation/images/architecture.dot @@ -1,11 +1,11 @@ digraph perseocore { - rankdir=LR + rankdir=LR node [fontname = "arial"]; perseo[shape=circle, style=dashed]; - core[label=" core ", shape=circle]; + core[label=" core ", shape=circle]; - perseo->core[label="rule"] - perseo->core[label="event"] - core->perseo[label="action"] + perseo->core[label="rule"] + perseo->core[label="event"] + core->perseo[label="action"] } diff --git a/documentation/logs.md b/documentation/logs.md index ac8640e..8640faa 100644 --- a/documentation/logs.md +++ b/documentation/logs.md @@ -3,7 +3,7 @@ Logs have levels `FATAL`, `ERROR`, `INFO` and `DEBUG`. The log level must be set in the configuration file `log4j.xml` ```xml - + ``` Each log line contains several fields of the form *name*`=` *value*, separated by `|` diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/Configuration.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/Configuration.java index d8363aa..58996af 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/Configuration.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/Configuration.java @@ -47,7 +47,7 @@ private Configuration() { private static final String PERSEO_MAX_AGE_ENV = "MAX_AGE"; private static final Properties PROPERTIES = new Properties(); - private static final String PATH = ResourceBundle.getBundle("perseo-core").getString("properties.path"); + private static final String PATH = "/etc/perseo-core.properties"; private static final String ACTION_URL_PROP = "action.url"; private static final String MAX_AGE_PROP = "rule.max_age"; @@ -69,7 +69,7 @@ public static synchronized boolean reload() { InputStream stream; String defaultMaxAge; String defaultURL; - String actionPath = ResourceBundle.getBundle("perseo-core").getString("action.path"); + String actionPath = "/actions/do"; // Check configuration file. If exist, set as default configuration for perseo-core try { diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java index 0bf7314..4c7ede8 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/EventsServlet.java @@ -78,7 +78,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) logger.debug("events doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - try { + try { String eventText = Utils.getBodyAsString(request); logger.info(String.format("incoming event: %s", eventText)); org.json.JSONObject jo = new JSONObject(eventText); @@ -89,10 +89,10 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) logger.debug(String.format("event was sent: %s", eventMap)); } catch (Exception je) { - try { + try { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.getOutputStream().print(String.format("{\"error\":\"%s\"}%n", Encode.forHtmlContent(je.getMessage()))); + response.getOutputStream().print(String.format("{\"error\":\"%s\"}%n", Encode.forHtmlContent(je.getMessage()))); } catch (IOException exception) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java index 0ae1d7c..86b7a64 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java @@ -83,11 +83,11 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) } response.setStatus(HttpServletResponse.SC_OK); } catch (IOException e) { - logger.error("IOException in log level"); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; + logger.error("IOException in log level"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; } - + } /** diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/Result.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/Result.java index 2dc9909..f909697 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/Result.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/Result.java @@ -41,7 +41,6 @@ public class Result { Result(int code, String msg) { this.statusCode = code; this.message = msg; - } /** diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesManager.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesManager.java index 8262c6d..95622fe 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesManager.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesManager.java @@ -52,8 +52,7 @@ public class RulesManager { * @return Result object with a code and a JSON response */ public static synchronized Result get(EPServiceProvider epService, String ruleName) { - try { - + try { logger.debug(String.format("rule asked for: %s", ruleName)); ruleName = ruleName == null ? "" : ruleName; EPAdministrator epa = epService.getEPAdministrator(); @@ -98,7 +97,6 @@ public static synchronized Result get(EPServiceProvider epService, String ruleNa */ public static synchronized Result make(EPServiceProvider epService, String text) { try { - logger.debug(String.format("rule text: %s", text)); org.json.JSONObject jo = new JSONObject(text); @@ -254,7 +252,6 @@ public static synchronized Result updateAll(EPServiceProvider epService, String */ public static synchronized Result delete(EPServiceProvider epService, String ruleName) { try { - ruleName = ruleName == null ? "" : ruleName; logger.debug(String.format("delete rule: %s" ,ruleName)); EPAdministrator epa = epService.getEPAdministrator(); diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java index ee0c05d..9c40a54 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/RulesServlet.java @@ -92,7 +92,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.get(epService, ruleName.substring(1)); response.setStatus(r.getStatusCode()); response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); - } catch (Exception je) { + } catch (Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } @@ -121,8 +121,8 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.make(epService, body); response.setStatus(r.getStatusCode()); - response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); - } catch (Exception je) { + response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); + } catch (Exception je) { logger.error(String.format("error: %s" ,je)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } @@ -143,7 +143,7 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - try { + try { String body = Utils.getBodyAsString(request); // Save timed rules, which are not activated by events external to the core @@ -152,9 +152,9 @@ protected void doPut(HttpServletRequest request, HttpServletResponse response) Result r = RulesManager.updateAll(epService, body); response.setStatus(r.getStatusCode()); response.getOutputStream().print(Encode.forHtmlContent(r.getMessage())); - } catch (Exception je) { + } catch (Exception je) { logger.error(String.format("error: %s" ,je)); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } @@ -172,7 +172,7 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response Utils.putCorrelatorAndTrans(request); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); - try { + try { logger.info(String.format("delete rule %s", request.getPathInfo())); //request.getPathInfo() returns null or the extra path information //that follows the servlet path but precedes the query string and will @@ -190,9 +190,9 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response response.setStatus(r.getStatusCode()); response.getOutputStream().print(r.getMessage()); - } catch (Exception je) { - logger.error(String.format("error: %s" ,je)); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } catch (Exception je) { + logger.error(String.format("error: %s" ,je)); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/Utils.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/Utils.java index 313aa20..a1bfc52 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/Utils.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/Utils.java @@ -81,7 +81,6 @@ public static synchronized EPServiceProvider initEPService(ServletContext sc) { // Add Single row function for perseo-utils functions try { - cfg.addPlugInSingleRowFunction("getNextSunrise", "com.telefonica.iot.perseo.utils.DateTimeUtils", "getNextSunrise", ConfigurationPlugInSingleRowFunction.ValueCache.DISABLED); diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/Version.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/Version.java index 45fb315..526bfec 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/Version.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/Version.java @@ -46,7 +46,6 @@ private Version() { LOGGER.error(ioe.getMessage()); POM.setProperty("version", "UNKNOWN"); } - } /** diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java index 7329ec4..4747c0f 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/EventsServletTest.java @@ -36,7 +36,7 @@ * @author brox */ public class EventsServletTest { - private static final Logger logger = LoggerFactory.getLogger(EventsServletTest.class); + private static final Logger logger = LoggerFactory.getLogger(EventsServletTest.class); public EventsServletTest() { } diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java index 8ad7c43..80c84ca 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/GenericListenerTest.java @@ -40,7 +40,7 @@ * @author brox */ public class GenericListenerTest { - private static final Logger logger = LoggerFactory.getLogger(GenericListenerTest.class); + private static final Logger logger = LoggerFactory.getLogger(GenericListenerTest.class); public GenericListenerTest() { } diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java index 5e2ffba..d70c1ed 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/LogLevelServletTest.java @@ -37,8 +37,8 @@ * @author brox */ public class LogLevelServletTest { - - private static final Logger logger = LoggerFactory.getLogger(LogLevelServletTest.class); + + private static final Logger logger = LoggerFactory.getLogger(LogLevelServletTest.class); public LogLevelServletTest() { } diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java index 92dce81..072e4ab 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesManagerTest.java @@ -54,7 +54,6 @@ public RulesManagerTest() { def.put(Constants.SERVICE_FIELD, String.class); ConfigurationOperations cfg = epService.getEPAdministrator().getConfiguration(); cfg.addEventType("iotEvent", def); - } @BeforeClass @@ -125,7 +124,6 @@ public void testUpdateAll() { EPStatement st = epService.getEPAdministrator().getStatement(ruleName); assertEquals(epl, st.getText()); assertEquals(ruleName, st.getName()); - } /** @@ -143,5 +141,4 @@ public void testDelete() { EPStatement st2 = epService.getEPAdministrator().getStatement(ruleName); assertEquals(null, st2); } - } diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java index 92c204c..ffcebe2 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/RulesServletTest.java @@ -39,7 +39,7 @@ * @author brox */ public class RulesServletTest { - private static final Logger logger = LoggerFactory.getLogger(RulesServletTest.class); + private static final Logger logger = LoggerFactory.getLogger(RulesServletTest.class); public RulesServletTest() { } @@ -95,7 +95,7 @@ public void testDoPost() throws Exception { jr.put("name", "test doPost rule"); jr.put("text", Help.ExampleRules()[0]); Help.Res r = Help.sendPost(url, jr.toString(2)); - assertEquals(200,r.getCode()); + assertEquals(200, r.getCode()); jr.remove("name"); r = Help.sendPost(url, jr.toString(2)); assertEquals(400, r.getCode()); diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java index 78edd85..3e6a90d 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java @@ -41,7 +41,7 @@ public class TimeRulesStoreTest { private TimeRulesStore instance = TimeRulesStore.getInstance(); - private static final Logger LOGGER = LoggerFactory.getLogger(TimeRulesStoreTest.class); + private static final Logger logger = LoggerFactory.getLogger(TimeRulesStoreTest.class); public TimeRulesStoreTest() { } @@ -133,7 +133,6 @@ public void testRemoveRule() { body2.put("text", ruleText2); instance.saveTimeRules(body2.toString()); - HashMap result1 = instance.getAllRulesInfo(); assertEquals(2, result1.size()); @@ -176,6 +175,4 @@ public void testCleanAllRules() { assertEquals(0, result.size()); } -} - - +} \ No newline at end of file diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/UtilsTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/UtilsTest.java index 3e66782..7e60d34 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/UtilsTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/UtilsTest.java @@ -53,7 +53,7 @@ * @author brox */ public class UtilsTest { - private static final Logger logger = LoggerFactory.getLogger(UtilsTest.class); + private static final Logger logger = LoggerFactory.getLogger(UtilsTest.class); public UtilsTest() { } @@ -85,7 +85,6 @@ public void testInitEPService() { //Do not create a new one if it already exists EPServiceProvider result2 = Utils.initEPService(sc); assertEquals(result, result2); - } /** @@ -197,7 +196,6 @@ public void handle(HttpExchange exchange) throws IOException { httpServer.stop(0); } } - } /** @@ -205,7 +203,6 @@ public void handle(HttpExchange exchange) throws IOException { */ @Test public void testURLValidator() { - assertEquals(Utils.isValidURL("https://valid.url/forTest"), true); assertEquals(Utils.isValidURL("invalid.url_forTest"), false); } diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/test/Help.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/test/Help.java index 11f00da..6ed2bf1 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/test/Help.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/test/Help.java @@ -42,31 +42,28 @@ public class Help { public static final int PORT = 8129; - public static String[] ExampleRules() { - return new String[]{ - "select id, price? as Price from iotEvent.win:length(100) group by id", - "@Audit select *,\"blood_1_action\" as iotcepaction," - + "ev.BloodPressure? as Pression, ev.id? as Meter from pattern " - + "[every ev=iotEvent(cast(cast(BloodPressure?,String),float)>1.5" - + " and type=\"BloodMeter\")]"}; - + return new String[]{ + "select id, price? as Price from iotEvent.win:length(100) group by id", + "@Audit select *,\"blood_1_action\" as iotcepaction," + + "ev.BloodPressure? as Pression, ev.id? as Meter from pattern " + + "[every ev=iotEvent(cast(cast(BloodPressure?,String),float)>1.5" + + " and type=\"BloodMeter\")]"}; } public static String[] ExampleNotices() { - return new String[]{ + return new String[]{ "{\n" + "\"BloodPressure\": 2,\n" + "\"id\":\"guay!\",\n" + "\"otro\":\"mas\",\n" + "\"numero\":4,\n" + "\"sub\": {\n" - + " \"subnumero\":18,\n" - + " \"subcadena\":\"SUB2\",\n" - + " \"subflotante\": 12.3,\n" - + " \"sub2\": { \"valor\": 3}\n" - + " }\n" + + " \"subnumero\":18,\n" + + " \"subcadena\":\"SUB2\",\n" + + " \"subflotante\": 12.3,\n" + + " \"sub2\": { \"valor\": 3}\n" + + " }\n" + "}"}; - } @@ -96,7 +93,6 @@ public void setText(String text) { this.text = text; } - } diff --git a/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java b/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java index 487f1e9..37a8808 100644 --- a/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java +++ b/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java @@ -3,23 +3,17 @@ * * This file is part of perseo-core project. * - * perseo-core is free software: you can redistribute it and/or - * modify it under the terms of the GNU - * General Public License version 2 as published by the Free Software - * Foundation. + * perseo-core is free software: you can redistribute it and/or modify it under the terms of the GNU + * General Public License version 2 as published by the Free Software Foundation. * - * perseo-core is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the - * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License + * perseo-core is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the + * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * - * You should have received a copy of the GNU General Public License - * along with perseo-core. If not, see + * You should have received a copy of the GNU General Public License along with perseo-core. If not, see * http://www.gnu.org/licenses/. * - * For those usages not covered by the GNU General Public License - * please contact with + * For those usages not covered by the GNU General Public License please contact with * iot_support at tid dot es */ From b4a4d739cc56604002ce38463fa15aeccb64b823 Mon Sep 17 00:00:00 2001 From: Fiqare-Emergya Date: Wed, 29 Jan 2020 12:35:57 +0100 Subject: [PATCH 49/51] pr fixed --- .../test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java index 3e6a90d..6d2cbf8 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/TimeRulesStoreTest.java @@ -72,7 +72,7 @@ public void testGetEmptyRuleMap() { HashMap emptyHasmap = new HashMap(); HashMap result = instance.getAllRulesInfo(); - LOGGER.debug(String.format("testing ------- %s",result)); + logger.debug(String.format("testing ------- %s",result)); assertEquals(result, emptyHasmap); } From b6d7148bbc37f5c8a5de01bf50c6c12a6d80d237 Mon Sep 17 00:00:00 2001 From: Fiqare-Emergya Date: Fri, 31 Jan 2020 14:30:40 +0100 Subject: [PATCH 50/51] pr fixed --- CHANGES_NEXT_RELEASE | 1 + .../telefonica/iot/perseo/Configuration.java | 1 - .../iot/perseo/LogLevelServlet.java | 2 +- .../src/main/resources/perseo-core.properties | 2 -- .../com/telefonica/iot/perseo/test/Help.java | 24 +++++++++---------- 5 files changed, 14 insertions(+), 16 deletions(-) diff --git a/CHANGES_NEXT_RELEASE b/CHANGES_NEXT_RELEASE index e69de29..7a9422e 100644 --- a/CHANGES_NEXT_RELEASE +++ b/CHANGES_NEXT_RELEASE @@ -0,0 +1 @@ + - Hardening: software quality improvement based on ISO25010 recommendations \ No newline at end of file diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/Configuration.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/Configuration.java index 58996af..dffb2dd 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/Configuration.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/Configuration.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.Properties; -import java.util.ResourceBundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java b/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java index 86b7a64..1f8c8ef 100644 --- a/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java +++ b/perseo-main/src/main/java/com/telefonica/iot/perseo/LogLevelServlet.java @@ -103,7 +103,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("getting log level"); synchronized (mutex) { - try { + try { String currentLevel = LogManager.getRootLogger().getLevel().toString(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); diff --git a/perseo-main/src/main/resources/perseo-core.properties b/perseo-main/src/main/resources/perseo-core.properties index e577ac1..08ffc53 100644 --- a/perseo-main/src/main/resources/perseo-core.properties +++ b/perseo-main/src/main/resources/perseo-core.properties @@ -25,5 +25,3 @@ action.url = http://127.0.0.1:9090/actions/do # Time in milliseconds (long) to "expire" a "dangling" rule rule.max_age= 60000 -properties.path = /etc/perseo-core.properties -action.path = /actions/do diff --git a/perseo-main/src/test/java/com/telefonica/iot/perseo/test/Help.java b/perseo-main/src/test/java/com/telefonica/iot/perseo/test/Help.java index 6ed2bf1..76468f6 100644 --- a/perseo-main/src/test/java/com/telefonica/iot/perseo/test/Help.java +++ b/perseo-main/src/test/java/com/telefonica/iot/perseo/test/Help.java @@ -52,18 +52,18 @@ public static String[] ExampleRules() { } public static String[] ExampleNotices() { return new String[]{ - "{\n" - + "\"BloodPressure\": 2,\n" - + "\"id\":\"guay!\",\n" - + "\"otro\":\"mas\",\n" - + "\"numero\":4,\n" - + "\"sub\": {\n" - + " \"subnumero\":18,\n" - + " \"subcadena\":\"SUB2\",\n" - + " \"subflotante\": 12.3,\n" - + " \"sub2\": { \"valor\": 3}\n" - + " }\n" - + "}"}; + "{\n" + + "\"BloodPressure\": 2,\n" + + "\"id\":\"guay!\",\n" + + "\"otro\":\"mas\",\n" + + "\"numero\":4,\n" + + "\"sub\": {\n" + + " \"subnumero\":18,\n" + + " \"subcadena\":\"SUB2\",\n" + + " \"subflotante\": 12.3,\n" + + " \"sub2\": { \"valor\": 3}\n" + + " }\n" + + "}"}; } From 728e6000e3d3743f293c95f6d8207a98ce7e9c22 Mon Sep 17 00:00:00 2001 From: Fiqare-Emergya Date: Mon, 3 Feb 2020 09:47:56 +0100 Subject: [PATCH 51/51] travis fixed --- .../java/com/telefonica/iot/perseo/utils/DateTimeUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java b/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java index 37a8808..467820d 100644 --- a/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java +++ b/perseo-utils/src/main/java/com/telefonica/iot/perseo/utils/DateTimeUtils.java @@ -193,7 +193,7 @@ public static int timeToUTC(int time, final String timeZone) { LocalDateTime localDateTime = LocalDateTime.of(LocalDateTime.now() .getYear(), LocalDateTime.now().getMonth(), - LocalDateTime.now().getDayOfMonth() + 1, + LocalDateTime.now().getDayOfMonth(), time, LocalDateTime.now().getMinute()); ZonedDateTime isoDateZLDT = localDateTime.atZone(ZoneId.of(timeZone));