This is an automated email from the ASF dual-hosted git repository. jensdeppe pushed a commit to branch develop in repository https://gitbox.apache.org/repos/asf/geode.git
The following commit(s) were added to refs/heads/develop by this push: new 6defb1b GEODE-6743: Remove GFJsonObject and GFJsonArray classes (#3555) 6defb1b is described below commit 6defb1b8e2a663afb5d23124a9a63b5107ab85a2 Author: Jens Deppe <jde...@pivotal.io> AuthorDate: Tue May 7 09:04:24 2019 -0700 GEODE-6743: Remove GFJsonObject and GFJsonArray classes (#3555) --- .../geode/management/QueryDataDUnitTest.java | 27 +- .../DestroyAsyncEventQueueCommandDUnitTest.java | 8 +- .../geode/pdx/JSONPdxClientServerDUnitTest.java | 6 +- .../QueryResultFormatterQueryIntegrationTest.java | 14 +- .../management/DataQueryEngineIntegrationTest.java | 33 +- .../QueryResultFormatterPdxIntegrationTest.java | 11 +- .../apache/geode/pdx/JSONFormatterJUnitTest.java | 8 +- .../apache/geode/distributed/AbstractLauncher.java | 14 +- .../apache/geode/distributed/LocatorLauncher.java | 36 +- .../apache/geode/distributed/ServerLauncher.java | 34 +- .../management/internal/beans/DataQueryEngine.java | 16 +- .../management/internal/cli/json/GfJsonArray.java | 198 ----------- .../internal/cli/json/GfJsonException.java | 35 -- .../management/internal/cli/json/GfJsonObject.java | 384 --------------------- .../internal/cli/json/QueryResultFormatter.java | 18 +- .../management/internal/cli/util/JsonUtil.java | 381 +------------------- .../sanctioned-geode-core-serializables.txt | 1 - .../AbstractLauncherServiceStateTest.java | 33 +- .../apache/geode/distributed/LocatorStateTest.java | 23 +- .../internal/cli/DataCommandJsonJUnitTest.java | 54 --- .../internal/cli/json/GfJsonArrayTest.java | 107 ------ .../internal/cli/json/GfJsonObjectTest.java | 181 ---------- .../cli/json/QueryResultFormatterTest.java | 10 +- .../apache/geode/pdx/JSONFormatVerifyUtility.java | 45 ++- .../geode/pdx/TestObjectForJSONFormatter.java | 14 +- 25 files changed, 188 insertions(+), 1503 deletions(-) diff --git a/geode-core/src/distributedTest/java/org/apache/geode/management/QueryDataDUnitTest.java b/geode-core/src/distributedTest/java/org/apache/geode/management/QueryDataDUnitTest.java index 0fcb6c9..2a0b61f 100644 --- a/geode-core/src/distributedTest/java/org/apache/geode/management/QueryDataDUnitTest.java +++ b/geode-core/src/distributedTest/java/org/apache/geode/management/QueryDataDUnitTest.java @@ -37,6 +37,8 @@ import java.util.concurrent.TimeoutException; import javax.management.ObjectName; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -61,8 +63,6 @@ import org.apache.geode.internal.cache.partitioned.fixed.SingleHopQuarterPartiti import org.apache.geode.management.internal.SystemManagementService; import org.apache.geode.management.internal.beans.BeanUtilFuncs; import org.apache.geode.management.internal.beans.QueryDataFunction; -import org.apache.geode.management.internal.cli.json.GfJsonArray; -import org.apache.geode.management.internal.cli.json.GfJsonObject; import org.apache.geode.pdx.PdxInstance; import org.apache.geode.pdx.PdxInstanceFactory; import org.apache.geode.pdx.internal.PdxInstanceFactoryImpl; @@ -245,16 +245,12 @@ public class QueryDataDUnitTest implements Serializable { assertThat(jsonString).contains("result").doesNotContain("No Data Found"); assertThat(jsonString).contains(BIG_COLLECTION_ELEMENT_); - GfJsonObject jsonObject = new GfJsonObject(jsonString); - GfJsonArray jsonArray = jsonObject.getJSONArray("result"); - assertThat(jsonArray.length()).isEqualTo(DEFAULT_QUERY_LIMIT); - - // Get the first element - GfJsonArray jsonArray1 = jsonArray.getJSONArray(0); - assertThat(jsonArray1).isNotNull(); + JsonNode jsonObject = new ObjectMapper().readTree(jsonString); + JsonNode jsonArray = jsonObject.get("result"); + assertThat(jsonArray.size()).isEqualTo(DEFAULT_QUERY_LIMIT); // Get the ObjectValue - GfJsonObject collectionObject = jsonArray1.getJsonObject(1); + JsonNode collectionObject = jsonArray.get(0).get(1); assertThat(collectionObject.size()).isEqualTo(100); // Query With Override Values @@ -274,17 +270,14 @@ public class QueryDataDUnitTest implements Serializable { verifyJsonIsValid(jsonString); assertThat(jsonString).contains("result").doesNotContain("No Data Found"); - jsonObject = new GfJsonObject(jsonString); + jsonObject = new ObjectMapper().readTree(jsonString); assertThat(jsonString).contains(BIG_COLLECTION_ELEMENT_); - jsonArray = jsonObject.getJSONArray("result"); - assertThat(jsonArray.length()).isEqualTo(newQueryResultSetLimit); - - // Get the first element - jsonArray1 = jsonArray.getJSONArray(0); + jsonArray = jsonObject.get("result"); + assertThat(jsonArray.size()).isEqualTo(newQueryResultSetLimit); // Get the ObjectValue - collectionObject = jsonArray1.getJsonObject(1); + collectionObject = jsonArray.get(0).get(1); assertThat(collectionObject.size()).isEqualTo(newQueryCollectionDepth); }); } diff --git a/geode-core/src/distributedTest/java/org/apache/geode/management/internal/cli/commands/DestroyAsyncEventQueueCommandDUnitTest.java b/geode-core/src/distributedTest/java/org/apache/geode/management/internal/cli/commands/DestroyAsyncEventQueueCommandDUnitTest.java index b775ac5..11e2edf 100644 --- a/geode-core/src/distributedTest/java/org/apache/geode/management/internal/cli/commands/DestroyAsyncEventQueueCommandDUnitTest.java +++ b/geode-core/src/distributedTest/java/org/apache/geode/management/internal/cli/commands/DestroyAsyncEventQueueCommandDUnitTest.java @@ -16,8 +16,6 @@ package org.apache.geode.management.internal.cli.commands; import static org.assertj.core.api.Assertions.assertThat; -import java.io.IOException; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -26,7 +24,6 @@ import org.junit.experimental.categories.Category; import org.apache.geode.distributed.internal.InternalConfigurationPersistenceService; import org.apache.geode.internal.cache.wan.MyAsyncEventListener; import org.apache.geode.management.internal.cli.i18n.CliStrings; -import org.apache.geode.management.internal.cli.json.GfJsonException; import org.apache.geode.management.internal.configuration.domain.Configuration; import org.apache.geode.test.dunit.rules.ClusterStartupRule; import org.apache.geode.test.dunit.rules.MemberVM; @@ -162,8 +159,7 @@ public class DestroyAsyncEventQueueCommandDUnitTest { } @Test - public void destroyAeq_selectsQueuesOnGroup_showsErrorForServersNotInGroup() - throws GfJsonException { + public void destroyAeq_selectsQueuesOnGroup_showsErrorForServersNotInGroup() { gfsh.executeAndAssertThat("create async-event-queue --id=queue1 --group=group1 --listener=" + MyAsyncEventListener.class.getName()).statusIsSuccess(); @@ -181,7 +177,7 @@ public class DestroyAsyncEventQueueCommandDUnitTest { } @Test - public void destroyAeq_selectsQueuesByGroup_returnsSuccess() throws GfJsonException, IOException { + public void destroyAeq_selectsQueuesByGroup_returnsSuccess() { server3 = lsRule.startServerVM(3, "group3", locator.getPort()); gfsh.executeAndAssertThat("create async-event-queue --id=queue1 --group=group1 --listener=" diff --git a/geode-core/src/distributedTest/java/org/apache/geode/pdx/JSONPdxClientServerDUnitTest.java b/geode-core/src/distributedTest/java/org/apache/geode/pdx/JSONPdxClientServerDUnitTest.java index 3a68ded..21a3970 100755 --- a/geode-core/src/distributedTest/java/org/apache/geode/pdx/JSONPdxClientServerDUnitTest.java +++ b/geode-core/src/distributedTest/java/org/apache/geode/pdx/JSONPdxClientServerDUnitTest.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Properties; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; @@ -44,7 +43,6 @@ import org.apache.geode.cache.server.CacheServer; import org.apache.geode.internal.Assert; import org.apache.geode.internal.AvailablePortHelper; import org.apache.geode.internal.cache.GemFireCacheImpl; -import org.apache.geode.management.internal.cli.json.GfJsonException; import org.apache.geode.pdx.internal.json.PdxToJSON; import org.apache.geode.test.dunit.Host; import org.apache.geode.test.dunit.NetworkUtils; @@ -185,7 +183,7 @@ public class JSONPdxClientServerDUnitTest extends JUnit4CacheTestCase { }); } - public void VerifyPdxInstanceAndJsonConversion() throws JsonProcessingException, GfJsonException { + public void VerifyPdxInstanceAndJsonConversion() throws Exception { Region region = getRootRegion("testSimplePdx"); // Create Object and initialize its members. @@ -215,7 +213,7 @@ public class JSONPdxClientServerDUnitTest extends JUnit4CacheTestCase { } private void validateReceivedJSON(Region region, TestObjectForJSONFormatter actualTestObject, - ObjectMapper objectMapper) throws JsonProcessingException, GfJsonException { + ObjectMapper objectMapper) throws Exception { // 1. get the json from the object using Jackson Object Mapper String json = objectMapper.writeValueAsString(actualTestObject); String jsonWithClassType = actualTestObject.addClassTypeToJson(json); diff --git a/geode-core/src/integrationTest/java/org/apache/geode/cache/query/QueryResultFormatterQueryIntegrationTest.java b/geode-core/src/integrationTest/java/org/apache/geode/cache/query/QueryResultFormatterQueryIntegrationTest.java index 1e9373c..8cbc317 100644 --- a/geode-core/src/integrationTest/java/org/apache/geode/cache/query/QueryResultFormatterQueryIntegrationTest.java +++ b/geode-core/src/integrationTest/java/org/apache/geode/cache/query/QueryResultFormatterQueryIntegrationTest.java @@ -16,14 +16,16 @@ package org.apache.geode.cache.query; import static org.assertj.core.api.Assertions.assertThat; +import java.io.IOException; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.cache.query.data.Portfolio; import org.apache.geode.cache.query.data.Position; import org.apache.geode.cache.util.ObjectSizer; -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; import org.apache.geode.management.internal.cli.json.QueryResultFormatter; import org.apache.geode.management.internal.cli.json.QueryResultFormatterPdxIntegrationTest; import org.apache.geode.test.junit.categories.OQLQueryTest; @@ -96,9 +98,9 @@ public class QueryResultFormatterQueryIntegrationTest { return portfolios; } - private void checkResult(final QueryResultFormatter queryResultFormatter) throws GfJsonException { - GfJsonObject gfJsonObject = new GfJsonObject(queryResultFormatter.toString()); - System.out.println(gfJsonObject); - assertThat(gfJsonObject.get(RESULT)).isNotNull(); + private void checkResult(final QueryResultFormatter queryResultFormatter) throws IOException { + JsonNode jsonObject = new ObjectMapper().readTree(queryResultFormatter.toString()); + System.out.println(jsonObject.toString()); + assertThat(jsonObject.get(RESULT)).isNotNull(); } } diff --git a/geode-core/src/integrationTest/java/org/apache/geode/management/DataQueryEngineIntegrationTest.java b/geode-core/src/integrationTest/java/org/apache/geode/management/DataQueryEngineIntegrationTest.java index d2d9091..3a4dc7b 100644 --- a/geode-core/src/integrationTest/java/org/apache/geode/management/DataQueryEngineIntegrationTest.java +++ b/geode-core/src/integrationTest/java/org/apache/geode/management/DataQueryEngineIntegrationTest.java @@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collection; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -32,7 +33,6 @@ import org.apache.geode.management.internal.ManagementConstants; import org.apache.geode.management.internal.SystemManagementService; import org.apache.geode.management.internal.beans.DataQueryEngine; import org.apache.geode.management.internal.beans.QueryDataFunction; -import org.apache.geode.management.internal.cli.json.GfJsonObject; import org.apache.geode.management.model.EmptyObject; import org.apache.geode.management.model.Item; import org.apache.geode.management.model.Order; @@ -105,7 +105,7 @@ public class DataQueryEngineIntegrationTest { assertThat(queryResult).isEqualToIgnoringWhitespace(expectedResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } /** @@ -135,7 +135,7 @@ public class DataQueryEngineIntegrationTest { assertThat(queryResult).isEqualToIgnoringWhitespace(expectedResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } /** @@ -165,7 +165,7 @@ public class DataQueryEngineIntegrationTest { assertThat(queryResult).isEqualToIgnoringWhitespace(expectedResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } @Test @@ -189,7 +189,7 @@ public class DataQueryEngineIntegrationTest { System.out.println("Query Result: " + queryResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } @Test @@ -215,7 +215,7 @@ public class DataQueryEngineIntegrationTest { System.out.println("Query Result: " + queryResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } @Test @@ -241,7 +241,7 @@ public class DataQueryEngineIntegrationTest { System.out.println("Query Result: " + queryResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } @@ -254,7 +254,7 @@ public class DataQueryEngineIntegrationTest { System.out.println(queryResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } @Test @@ -267,7 +267,7 @@ public class DataQueryEngineIntegrationTest { assertThat(queryResult).isEqualToIgnoringWhitespace(expectedResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } @Test @@ -281,7 +281,7 @@ public class DataQueryEngineIntegrationTest { assertThat(queryResult).isEqualToIgnoringWhitespace(expectedResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } @Test @@ -304,7 +304,7 @@ public class DataQueryEngineIntegrationTest { assertThat(queryResult).isEqualToIgnoringWhitespace(expectedResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } @Test @@ -322,7 +322,7 @@ public class DataQueryEngineIntegrationTest { assertThat(queryResult).isEqualToIgnoringWhitespace(expectedResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); } @Test @@ -340,7 +340,14 @@ public class DataQueryEngineIntegrationTest { assertThat(queryResult).isEqualToIgnoringWhitespace(expectedResult); // If not correct JSON format this will throw a JSONException - new GfJsonObject(queryResult); + new ObjectMapper().readTree(queryResult); + } + + @Test + public void testWithUnknownRegion() throws Exception { + String queryResult = queryEngine.queryForJsonResult("select * from /unknonwn", 1, 1, 1); + assertThat(queryResult) + .isEqualTo("{\"message\":\"Cannot find regions /unknonwn in any of the members\"}"); } diff --git a/geode-core/src/integrationTest/java/org/apache/geode/management/internal/cli/json/QueryResultFormatterPdxIntegrationTest.java b/geode-core/src/integrationTest/java/org/apache/geode/management/internal/cli/json/QueryResultFormatterPdxIntegrationTest.java index dfe9f8c..0f7e793 100644 --- a/geode-core/src/integrationTest/java/org/apache/geode/management/internal/cli/json/QueryResultFormatterPdxIntegrationTest.java +++ b/geode-core/src/integrationTest/java/org/apache/geode/management/internal/cli/json/QueryResultFormatterPdxIntegrationTest.java @@ -18,9 +18,12 @@ import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.assertj.core.api.Assertions.assertThat; +import java.io.IOException; import java.io.Serializable; import java.util.Properties; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -90,10 +93,10 @@ public class QueryResultFormatterPdxIntegrationTest { checkResult(queryResultFormatter); } - private void checkResult(QueryResultFormatter queryResultFormatter) throws GfJsonException { - GfJsonObject gfJsonObject = new GfJsonObject(queryResultFormatter.toString()); - System.out.println(gfJsonObject); - assertThat(gfJsonObject.get(RESULT)).isNotNull(); + private void checkResult(QueryResultFormatter queryResultFormatter) throws IOException { + JsonNode jsonObject = new ObjectMapper().readTree(queryResultFormatter.toString()); + System.out.println(jsonObject.toString()); + assertThat(jsonObject.get(RESULT)).isNotNull(); } private static class SerializableObject implements Serializable { diff --git a/geode-core/src/integrationTest/java/org/apache/geode/pdx/JSONFormatterJUnitTest.java b/geode-core/src/integrationTest/java/org/apache/geode/pdx/JSONFormatterJUnitTest.java index 5eb0cb3..0995fb8 100755 --- a/geode-core/src/integrationTest/java/org/apache/geode/pdx/JSONFormatterJUnitTest.java +++ b/geode-core/src/integrationTest/java/org/apache/geode/pdx/JSONFormatterJUnitTest.java @@ -21,7 +21,6 @@ import static org.junit.Assert.assertTrue; import java.text.SimpleDateFormat; import java.util.List; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.After; @@ -33,7 +32,6 @@ import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.DataPolicy; import org.apache.geode.cache.Region; -import org.apache.geode.management.internal.cli.json.GfJsonException; import org.apache.geode.pdx.internal.PdxInstanceImpl; import org.apache.geode.pdx.internal.PeerTypeRegistration; import org.apache.geode.test.junit.categories.SerializationTest; @@ -58,7 +56,7 @@ public class JSONFormatterJUnitTest { } @Test - public void ValidatePdxInstanceToJsonConversion() throws GfJsonException { + public void ValidatePdxInstanceToJsonConversion() throws Exception { TestObjectForJSONFormatter actualTestObject = new TestObjectForJSONFormatter(); actualTestObject.defaultInitialization(); @@ -78,7 +76,7 @@ public class JSONFormatterJUnitTest { } @Test - public void verifyJsonToPdxInstanceConversion() throws JsonProcessingException, GfJsonException { + public void verifyJsonToPdxInstanceConversion() throws Exception { TestObjectForJSONFormatter expectedTestObject = new TestObjectForJSONFormatter(); expectedTestObject.defaultInitialization(); @@ -113,7 +111,7 @@ public class JSONFormatterJUnitTest { } @Test - public void verifyJsonToPdxInstanceConversionWithJSONFormatter() throws GfJsonException { + public void verifyJsonToPdxInstanceConversionWithJSONFormatter() throws Exception { TestObjectForJSONFormatter expectedTestObject = new TestObjectForJSONFormatter(); expectedTestObject.defaultInitialization(); diff --git a/geode-core/src/main/java/org/apache/geode/distributed/AbstractLauncher.java b/geode-core/src/main/java/org/apache/geode/distributed/AbstractLauncher.java index 4fd2280..864a509 100644 --- a/geode-core/src/main/java/org/apache/geode/distributed/AbstractLauncher.java +++ b/geode-core/src/main/java/org/apache/geode/distributed/AbstractLauncher.java @@ -41,6 +41,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + import org.apache.geode.annotations.Immutable; import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.InternalDistributedSystem; @@ -52,7 +55,6 @@ import org.apache.geode.internal.process.PidUnavailableException; import org.apache.geode.internal.process.ProcessUtils; import org.apache.geode.internal.util.ArgumentRedactor; import org.apache.geode.internal.util.SunAPINotFoundException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; /** * The AbstractLauncher class is a base class for implementing various launchers to construct and @@ -597,7 +599,15 @@ public abstract class AbstractLauncher<T extends Comparable<T>> implements Runna map.put(JSON_TIMESTAMP, getTimestamp().getTime()); map.put(JSON_UPTIME, getUptime()); map.put(JSON_WORKINGDIRECTORY, getWorkingDirectory()); - return new GfJsonObject(map).toString(); + + String jsonStatus = null; + try { + jsonStatus = new ObjectMapper().writeValueAsString(map); + } catch (JsonProcessingException e) { + // Ignored + } + + return jsonStatus; } public static boolean isStartingNotRespondingOrNull(final ServiceState serviceState) { diff --git a/geode-core/src/main/java/org/apache/geode/distributed/LocatorLauncher.java b/geode-core/src/main/java/org/apache/geode/distributed/LocatorLauncher.java index cb7a7d9..1733b8e 100644 --- a/geode-core/src/main/java/org/apache/geode/distributed/LocatorLauncher.java +++ b/geode-core/src/main/java/org/apache/geode/distributed/LocatorLauncher.java @@ -46,6 +46,8 @@ import java.util.logging.Level; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; @@ -78,9 +80,8 @@ import org.apache.geode.internal.process.ProcessType; import org.apache.geode.internal.process.ProcessUtils; import org.apache.geode.internal.process.UnableToControlProcessException; import org.apache.geode.lang.AttachAPINotFoundException; -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; import org.apache.geode.management.internal.cli.util.HostUtils; +import org.apache.geode.management.internal.cli.util.JsonUtil; /** * The LocatorLauncher class is a launcher for a GemFire Locator. @@ -1995,22 +1996,21 @@ public class LocatorLauncher extends AbstractLauncher<String> { */ public static LocatorState fromJson(final String json) { try { - final GfJsonObject gfJsonObject = new GfJsonObject(json); - - final Status status = Status.valueOfDescription(gfJsonObject.getString(JSON_STATUS)); - - final List<String> jvmArguments = - gfJsonObject.getJSONArray(JSON_JVMARGUMENTS).toStringList(); - - return new LocatorState(status, gfJsonObject.getString(JSON_STATUSMESSAGE), - gfJsonObject.getLong(JSON_TIMESTAMP), gfJsonObject.getString(JSON_LOCATION), - gfJsonObject.getInt(JSON_PID), gfJsonObject.getLong(JSON_UPTIME), - gfJsonObject.getString(JSON_WORKINGDIRECTORY), jvmArguments, - gfJsonObject.getString(JSON_CLASSPATH), gfJsonObject.getString(JSON_GEMFIREVERSION), - gfJsonObject.getString(JSON_JAVAVERSION), gfJsonObject.getString(JSON_LOGFILE), - gfJsonObject.getString(JSON_HOST), gfJsonObject.getString(JSON_PORT), - gfJsonObject.getString(JSON_MEMBERNAME)); - } catch (GfJsonException e) { + final JsonNode jsonObject = new ObjectMapper().readTree(json); + + final Status status = Status.valueOfDescription(jsonObject.get(JSON_STATUS).asText()); + + final List<String> jvmArguments = JsonUtil.toStringList(jsonObject.get(JSON_JVMARGUMENTS)); + + return new LocatorState(status, jsonObject.get(JSON_STATUSMESSAGE).asText(), + jsonObject.get(JSON_TIMESTAMP).asLong(), jsonObject.get(JSON_LOCATION).asText(), + jsonObject.get(JSON_PID).asInt(), jsonObject.get(JSON_UPTIME).asLong(), + jsonObject.get(JSON_WORKINGDIRECTORY).asText(), jvmArguments, + jsonObject.get(JSON_CLASSPATH).asText(), jsonObject.get(JSON_GEMFIREVERSION).asText(), + jsonObject.get(JSON_JAVAVERSION).asText(), jsonObject.get(JSON_LOGFILE).asText(), + jsonObject.get(JSON_HOST).asText(), jsonObject.get(JSON_PORT).asText(), + jsonObject.get(JSON_MEMBERNAME).asText()); + } catch (Exception e) { throw new IllegalArgumentException( "Unable to create LocatorStatus from JSON: ".concat(json), e); } diff --git a/geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java b/geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java index a12de6e..2b1f093 100755 --- a/geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java +++ b/geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java @@ -47,6 +47,8 @@ import java.util.concurrent.atomic.AtomicReference; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; @@ -85,9 +87,8 @@ import org.apache.geode.internal.process.ProcessType; import org.apache.geode.internal.process.UnableToControlProcessException; import org.apache.geode.lang.AttachAPINotFoundException; import org.apache.geode.management.internal.cli.i18n.CliStrings; -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; import org.apache.geode.management.internal.cli.util.HostUtils; +import org.apache.geode.management.internal.cli.util.JsonUtil; import org.apache.geode.pdx.PdxSerializer; import org.apache.geode.security.AuthenticationRequiredException; import org.apache.geode.security.GemFireSecurityException; @@ -2591,21 +2592,20 @@ public class ServerLauncher extends AbstractLauncher<String> { */ public static ServerState fromJson(final String json) { try { - final GfJsonObject gfJsonObject = new GfJsonObject(json); - - final Status status = Status.valueOfDescription(gfJsonObject.getString(JSON_STATUS)); - final List<String> jvmArguments = - gfJsonObject.getJSONArray(JSON_JVMARGUMENTS).toStringList(); - - return new ServerState(status, gfJsonObject.getString(JSON_STATUSMESSAGE), - gfJsonObject.getLong(JSON_TIMESTAMP), gfJsonObject.getString(JSON_LOCATION), - gfJsonObject.getInt(JSON_PID), gfJsonObject.getLong(JSON_UPTIME), - gfJsonObject.getString(JSON_WORKINGDIRECTORY), jvmArguments, - gfJsonObject.getString(JSON_CLASSPATH), gfJsonObject.getString(JSON_GEMFIREVERSION), - gfJsonObject.getString(JSON_JAVAVERSION), gfJsonObject.getString(JSON_LOGFILE), - gfJsonObject.getString(JSON_HOST), gfJsonObject.getString(JSON_PORT), - gfJsonObject.getString(JSON_MEMBERNAME)); - } catch (GfJsonException e) { + final JsonNode jsonObject = new ObjectMapper().readTree(json); + + final Status status = Status.valueOfDescription(jsonObject.get(JSON_STATUS).asText()); + final List<String> jvmArguments = JsonUtil.toStringList(jsonObject.get(JSON_JVMARGUMENTS)); + + return new ServerState(status, jsonObject.get(JSON_STATUSMESSAGE).asText(), + jsonObject.get(JSON_TIMESTAMP).asLong(), jsonObject.get(JSON_LOCATION).asText(), + jsonObject.get(JSON_PID).asInt(), jsonObject.get(JSON_UPTIME).asLong(), + jsonObject.get(JSON_WORKINGDIRECTORY).asText(), jvmArguments, + jsonObject.get(JSON_CLASSPATH).asText(), jsonObject.get(JSON_GEMFIREVERSION).asText(), + jsonObject.get(JSON_JAVAVERSION).asText(), jsonObject.get(JSON_LOGFILE).asText(), + jsonObject.get(JSON_HOST).asText(), jsonObject.get(JSON_PORT).asText(), + jsonObject.get(JSON_MEMBERNAME).asText()); + } catch (Exception e) { throw new IllegalArgumentException("Unable to create ServerStatus from JSON: " + json, e); } } diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/beans/DataQueryEngine.java b/geode-core/src/main/java/org/apache/geode/management/internal/beans/DataQueryEngine.java index 13f0f30..bb1699f 100644 --- a/geode-core/src/main/java/org/apache/geode/management/internal/beans/DataQueryEngine.java +++ b/geode-core/src/main/java/org/apache/geode/management/internal/beans/DataQueryEngine.java @@ -40,8 +40,6 @@ import org.apache.geode.management.DistributedRegionMXBean; import org.apache.geode.management.internal.ManagementConstants; import org.apache.geode.management.internal.SystemManagementService; import org.apache.geode.management.internal.cli.CliUtil; -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; /** * this is used by DistributedSystemBridge.queryData() call. It calls QueryDataFunction on each @@ -289,21 +287,15 @@ public class DataQueryEngine { static class JsonisedErrorMessage { - private static final String message = "message"; + private final String message; - private GfJsonObject gFJsonObject = new GfJsonObject(); - - public JsonisedErrorMessage(final String errorMessage) throws Exception { - try { - gFJsonObject.put(message, errorMessage); - } catch (GfJsonException e) { - throw new Exception(e); - } + public JsonisedErrorMessage(final String errorMessage) { + message = errorMessage; } @Override public String toString() { - return gFJsonObject.toString(); + return String.format("{\"message\":\"%s\"}", message); } } } diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/GfJsonArray.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/GfJsonArray.java deleted file mode 100644 index 0d8d7d4..0000000 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/GfJsonArray.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.apache.geode.management.internal.cli.json; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import org.apache.logging.log4j.Logger; - -import org.apache.geode.internal.logging.LogService; - -/** - * Wrapper over JSONArray. - * - * - * @since GemFire 7.0 - */ -public class GfJsonArray extends AbstractJSONFormatter { - private static final Logger logger = LogService.getLogger(); - - private final ArrayNode jsonArray; - - public GfJsonArray() { - super(-1, -1, false); - this.jsonArray = mapper.createArrayNode(); - } - - /** - * @throws GfJsonException If not an array. - */ - public GfJsonArray(Object array) throws GfJsonException { - super(-1, -1, false); - try { - if (array instanceof ArrayNode) { - this.jsonArray = (ArrayNode) array; - } else { - this.jsonArray = mapper.valueToTree(array); - } - if (this.jsonArray == null) { - throw new IllegalArgumentException("Array translated into null JSON node: " + array); - } - } catch (IllegalArgumentException e) { - throw new GfJsonException(e); - } - } - - void postCreateMapper() { - mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); - mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); - } - - /** - * Get the object value associated with an index. - * - * @return An object value. - * @throws GfJsonException If there is no value for the index. - */ - public String getString(int index) throws GfJsonException { - try { - JsonNode node = jsonArray.get(index); - if (node.textValue() != null) { - return node.asText(); - } else { - return node.toString(); - } - } catch (IllegalArgumentException e) { - throw new GfJsonException(e); - } - } - - public GfJsonObject getJsonObject(int index) throws GfJsonException { - try { - return new GfJsonObject(jsonArray.get(index)); - } catch (IllegalArgumentException e) { - throw new GfJsonException(e); - } - } - - public GfJsonArray put(Object value) { - this.jsonArray.add(toJsonNode(value)); - return this; - } - - public int length() { - return this.jsonArray.size(); - } - - /** - * @return this GfJsonArray - * @throws GfJsonException If the index is negative or if the the value is an invalid number. - */ - public GfJsonArray put(int index, Object value) throws GfJsonException { - JsonNode json = null; - try { - json = toJsonNode(value); - this.jsonArray.set(index, json); - } catch (IndexOutOfBoundsException e) { - while (this.jsonArray.size() < index) { - this.jsonArray.add((JsonNode) null); - } - this.jsonArray.add(json); - } catch (IllegalArgumentException e) { - throw new GfJsonException(e); - } - return this; - } - - /** - * @return this GfJsonArray - * @throws GfJsonException If the index is negative or if the the value is an invalid number. - */ - public GfJsonArray put(int index, Map<?, ?> value) throws GfJsonException { - try { - this.jsonArray.set(index, toJsonNode(value)); - } catch (IllegalArgumentException e) { - throw new GfJsonException(e); - } - return this; - } - - public int size() { - return jsonArray.size(); - } - - @Override - public String toString() { - return jsonArray.toString(); - } - - public static byte[] toByteArray(GfJsonArray jsonArray) throws GfJsonException { - byte[] byteArray = null; - if (jsonArray != null) { - int length = jsonArray.size(); - - byteArray = new byte[length]; - for (int i = 0; i < length; i++) { - try { - byteArray[i] = Byte.valueOf(String.valueOf(jsonArray.getString(i))); - } catch (GfJsonException e) { - throw new GfJsonException(e.getMessage()); - } - } - } - - return byteArray; - } - - public List<String> toStringList() { - List<String> stringArray = null; - int length = jsonArray.size(); - stringArray = new ArrayList<>(length); - for (int i = 0; i < length; i++) { - try { - stringArray.add(getString(i)); - } catch (GfJsonException e) { - logger.info("", e); - stringArray = null; - } - } - return stringArray; - } - - public ArrayNode getInternalJsonArray() { - return jsonArray; - } - - private JsonNode toJsonNode(Object value) { - if (value instanceof GfJsonObject) { - return ((GfJsonObject) value).getInternalJsonObject(); - } - if (value instanceof GfJsonArray) { - return ((GfJsonArray) value).getInternalJsonArray(); - } else if (value == null) { - return mapper.valueToTree(GfJsonObject.NULL); - } - return mapper.valueToTree(value); - } - - public GfJsonArray getJSONArray(int i) throws GfJsonException { - return new GfJsonArray(jsonArray.get(i)); - } -} diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/GfJsonException.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/GfJsonException.java deleted file mode 100644 index 16bece2..0000000 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/GfJsonException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.apache.geode.management.internal.cli.json; - -/** - * Wraps GemFire JSON Exceptions - * - * - * - * @since GemFire 7.0 - */ -public class GfJsonException extends Exception { - - private static final long serialVersionUID = 36449998984143318L; - - public GfJsonException(String message) { - super(message); - } - - public GfJsonException(Exception e) { - super(e); - } -} diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/GfJsonObject.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/GfJsonObject.java deleted file mode 100644 index 5f54639..0000000 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/GfJsonObject.java +++ /dev/null @@ -1,384 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.apache.geode.management.internal.cli.json; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; - -/** - * Simiulation of org.json.JSONObject based on Jackson Databind - */ -public class GfJsonObject extends AbstractJSONFormatter { - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - public static final Object NULL = new Object() { - @Override - public boolean equals(Object o) { - if (Objects.isNull(o)) { - return true; - } - return o == this; - } - - @Override - public int hashCode() { - return 0; - } - - @Override - public String toString() { - return "null"; - } - }; - - private ObjectNode rootNode; - - public GfJsonObject() { - super(-1, -1, false); - this.rootNode = mapper.createObjectNode(); - } - - public GfJsonObject(Map<?, ?> map) { - super(-1, -1, false); - this.rootNode = mapper.valueToTree(map); - } - - public GfJsonObject(Object bean) { - super(-1, -1, false); - if (bean instanceof ObjectNode) { - this.rootNode = (ObjectNode) bean; - } else { - this.rootNode = mapper.valueToTree(bean); - } - } - - /** - * - * @param source A string beginning with { (left brace) and ending with } (right brace). - * @throws GfJsonException - If there is a syntax error in the source string or a duplicated key. - */ - public GfJsonObject(String source) throws GfJsonException { - super(-1, -1, false); - try { - this.rootNode = (ObjectNode) mapper.readTree(source); - } catch (IOException e) { - throw new GfJsonException(e.getMessage()); - } - if (rootNode == null) { - throw new GfJsonException("Unable to parse JSON document"); - } - } - - void postCreateMapper() { - mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); - mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); - } - - /** - * - * @return this GfJsonObject - * @throws GfJsonException If the key is null OR if the value is non-finite number - */ - public GfJsonObject accumulate(String key, Object value) throws GfJsonException { - try { - if (rootNode.has(key)) { - append(key, value); - } else { - // first time always add JSONArray for accumulate - for convenience - ArrayNode array = mapper.createArrayNode(); - array.add(mapper.valueToTree(value)); - rootNode.set(key, array); - } - } catch (RuntimeException e) { - throw new GfJsonException(e); - } - return this; - } - - /** - * - * @return this GfJsonObject - * @throws GfJsonException - If the key is null or if the current value associated with the key is - * not a JSONArray. - */ - public GfJsonObject append(String key, Object value) throws GfJsonException { - try { - JsonNode current = rootNode.get(key); - if (current instanceof ArrayNode) { - ArrayNode array = (ArrayNode) current; - array.add(mapper.valueToTree(value)); - } else if (current == null) { - ArrayNode array = mapper.createArrayNode(); - array.add(mapper.valueToTree(value)); - rootNode.set(key, array); - } else { - throw new GfJsonException("Cannot append to a non-array field"); - } - } catch (RuntimeException e) { - throw new GfJsonException(e); - } - return this; - } - - /** - * return the Jackson JsonNode associated with the given key - */ - public JsonNode get(String key) { - return rootNode.get(key); - } - - public String getString(String key) { - JsonNode node = rootNode.get(key); - if (node == null) { - return null; // "null"; - } - if (node.textValue() != null) { - return node.textValue(); - } - return node.toString(); - } - - public int getInt(String key) { - return rootNode.get(key).asInt(); - } - - public long getLong(String key) { - return rootNode.get(key).asLong(); - } - - public double getDouble(String key) { - return rootNode.get(key).asDouble(); - } - - public boolean getBoolean(String key) { - return rootNode.get(key).asBoolean(); - } - - public GfJsonObject getJSONObject(String key) { - Object value = rootNode.get(key); - if (value == null) { - return null; - } - return new GfJsonObject(value); - } - - public JsonNode getInternalJsonObject() { - return rootNode; - } - - /** - * - * @return this GfJsonObject - * @throws GfJsonException If there is a syntax error while preparing GfJsonArray. - */ - public GfJsonArray getJSONArray(String key) throws GfJsonException { - JsonNode node = rootNode.get(key); - if (node == null) { - return null; - } - if (!(node instanceof ArrayNode)) { - // convert from list format to array format - ArrayNode newNode = mapper.createArrayNode(); - for (int i = 0; i < node.size(); i++) { - newNode.add(node.get("" + i)); - } - rootNode.set(key, newNode); - return new GfJsonArray(newNode); - } - return new GfJsonArray(node); - } - - /** - * - * @return A GfJsonArray containing the key strings, or null if the internal JSONObject is empty. - * @throws GfJsonException If there is a syntax error while preparing GfJsonArray. - */ - public GfJsonArray names() throws GfJsonException { - int size = rootNode.size(); - if (size == 0) { - return new GfJsonArray(); - } - String[] fieldNames = new String[rootNode.size()]; - Iterator<String> fieldNameIter = rootNode.fieldNames(); - int i = 0; - while (fieldNameIter.hasNext()) { - fieldNames[i++] = fieldNameIter.next(); - } - return new GfJsonArray(fieldNames); - } - - /** - * - * @return this GfJsonObject object - * @throws GfJsonException If the value is non-finite number or if the key is null. - */ - public GfJsonObject put(String key, Object value) throws GfJsonException { - try { - rootNode.set(key, toJsonNode(value)); - } catch (IllegalArgumentException e) { - throw new GfJsonException(e); - } - return this; - } - - public GfJsonObject putAsJSONObject(String key, Object value) throws GfJsonException { - try { - JsonNode internalJsonObj = toJsonNode(value); - rootNode.set(key, internalJsonObj); - } catch (IllegalArgumentException e) { - throw new GfJsonException(e); - } - return this; - } - - /** - * - * @return this GfJsonObject - * @throws GfJsonException If the value is a non-finite number. - */ - public GfJsonObject putOpt(String key, Object value) throws GfJsonException { - if (key == null || value == null) { - return this; - } - try { - rootNode.set(key, toJsonNode(value)); - } catch (IllegalArgumentException e) { - throw new GfJsonException(e); - } - return this; - } - - // /** - // * - // * @return this GfJsonObject - // * @throws GfJsonException If the value is a non-finite number. - // */ - // public GfJsonObject put(String key, Collection<?> value) throws GfJsonException { - // if (key == null || value == null) { - // return this; - // } - // try { - // rootNode.set(key, toJsonNode(value)); - // } catch (IllegalArgumentException e) { - // throw new GfJsonException(e); - // } - // return this; - // } - // - // public GfJsonObject put(String key, Map<?, ?> value) throws GfJsonException { - // try { - // rootNode.set(key, toJsonNode(value)); - // } catch (IllegalArgumentException e) { - // throw new GfJsonException(e); - // } - // return this; - // } - - // public static String quote(String string) { - // return JSONObject.quote(string); - // } - - // public Object remove(String key) { - // return rootNode.remove(key); - // } - - public boolean has(String key) { - return rootNode.has(key); - } - - public Iterator<String> keys() { - return rootNode.fieldNames(); - } - - /** - * @return the column size of this GfJsonObject - */ - public int size() { - return rootNode.size(); - } - - public String toString() { - return rootNode.toString(); - } - - // public String getType() { - // return rootNode.optString("type-class"); - // } - - /** - * - * @return this GfJsonObject - * @throws GfJsonException If the object contains an invalid number. - */ - public String toIndentedString() throws GfJsonException { - try { - return rootNode.toString(); - } catch (Exception e) { - throw new GfJsonException(e); - } - } - - public List<String> getArrayValues(String key) { - List<String> result = new ArrayList<>(); - if (rootNode.has(key)) { - JsonNode node = rootNode.get(key); - if (!(node instanceof ArrayNode)) { - throw new IllegalStateException("requested field is not an array: " + key); - } - ArrayNode array = (ArrayNode) node; - for (int i = 0; i < array.size(); i++) { - JsonNode valueNode = array.get(i); - result.add(valueNode.textValue() == null ? valueNode.toString() : valueNode.asText()); - } - } - return result; - } - - private JsonNode toJsonNode(Object value) { - if (value instanceof JsonNode) { - return (JsonNode) value; - } - if (value instanceof GfJsonObject) { - return ((GfJsonObject) value).getInternalJsonObject(); - } - if (value instanceof GfJsonArray) { - return ((GfJsonArray) value).getInternalJsonArray(); - } - if (value == null) { - return mapper.valueToTree(NULL); - } - return mapper.valueToTree(value); - } - - public static GfJsonObject getGfJsonErrorObject(String errorMessage) { - Map<String, String> errorMap = new HashMap<String, String>(); - errorMap.put("error", errorMessage); - return new GfJsonObject(errorMap); - } - - public ObjectMapper getObjectMapper() { - return mapper; - } -} diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/QueryResultFormatter.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/QueryResultFormatter.java index 7a67e9c..7ae4b22 100644 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/QueryResultFormatter.java +++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/json/QueryResultFormatter.java @@ -22,6 +22,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.eclipse.jetty.io.RuntimeIOException; + /** * A JSON serializer that has special handling for collections to limit the number of elements * written to the document. It also has special handling for PdxInstance and query Structs. @@ -34,8 +36,8 @@ public class QueryResultFormatter extends AbstractJSONFormatter { private final Map<String, List<Object>> map; /** - * Create a formatter that will limit collection sizes to maxCollectionElements - * and will limit object traversal to being the same but in depth. + * Create a formatter that will limit collection sizes to maxCollectionElements and will limit + * object traversal to being the same but in depth. * * @param maxCollectionElements limit on collection elements and depth-first object traversal */ @@ -55,8 +57,8 @@ public class QueryResultFormatter extends AbstractJSONFormatter { } /** - * After instantiating a formatter add the objects you want to be formatted - * using this method. Typically this will be add("result", queryResult) + * After instantiating a formatter add the objects you want to be formatted using this method. + * Typically this will be add("result", queryResult) */ public synchronized QueryResultFormatter add(String key, Object value) { List<Object> list = this.map.get(key); @@ -91,16 +93,14 @@ public class QueryResultFormatter extends AbstractJSONFormatter { writer.write('}'); return writer.toString(); - } catch (IOException exception) { - new GfJsonException(exception).printStackTrace(); - } catch (GfJsonException e) { + } catch (Exception e) { e.printStackTrace(); } return null; } - private Writer writeList(Writer writer, List<Object> values) throws GfJsonException { + private Writer writeList(Writer writer, List<Object> values) { // for each object we clear out the serializedObjects recursion map so that // we don't immediately see "duplicate" entries serializedObjects.clear(); @@ -123,7 +123,7 @@ public class QueryResultFormatter extends AbstractJSONFormatter { } writer.write(']'); } catch (IOException e) { - throw new GfJsonException(e); + throw new RuntimeIOException(e); } return writer; } diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/JsonUtil.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/JsonUtil.java index 7af37f0..af64c4d 100644 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/JsonUtil.java +++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/JsonUtil.java @@ -14,336 +14,20 @@ */ package org.apache.geode.management.internal.cli.util; -import java.lang.reflect.Array; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; +import java.util.Collections; import java.util.List; -import java.util.Map; -import java.util.Set; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.JsonNodeType; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.apache.commons.beanutils.ConvertUtils; - -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; /** * This class contains utility methods for JSON (http://www.json.org/) which is used by classes used * for the Command Line Interface (CLI). * - * * @since GemFire 7.0 */ public class JsonUtil { - /** - * Converts given JSON String in to a Object. Refer http://www.json.org/ to construct a JSON - * format. - * - * @param jsonString jsonString to be converted in to a Map. - * @return an object constructed from given JSON String - * - * @throws IllegalArgumentException if the specified JSON string can not be converted in to an - * Object - */ - public static <T> T jsonToObject(String jsonString, Class<T> klass) { - T objectFromJson = null; - try { - GfJsonObject jsonObject = new GfJsonObject(jsonString); - objectFromJson = klass.newInstance(); - Method[] declaredMethods = klass.getMethods(); - Map<String, Method> methodsMap = new HashMap<String, Method>(); - for (Method method : declaredMethods) { - methodsMap.put(method.getName(), method); - } - - int noOfFields = jsonObject.size(); - Iterator<String> keys = jsonObject.keys(); - - while (keys.hasNext()) { - String key = keys.next(); - Method method = methodsMap.get("set" + capitalize(key)); - if (method != null) { - Class<?>[] parameterTypes = method.getParameterTypes(); - if (parameterTypes.length == 1) { - Class<?> parameterType = parameterTypes[0]; - - Object value = jsonObject.get(key); - if (isPrimitiveOrWrapper(parameterType)) { - value = ConvertUtils.convert(getPrimitiveOrWrapperValue(parameterType, value), - parameterType); - } - // Bug #51175 - else if (isArray(parameterType)) { - value = toArray(value, parameterType); - } else if (isList(parameterType)) { - value = toList(value, parameterType); - } else if (isMap(parameterType)) { - value = toMap(value, parameterType); - } else if (isSet(parameterType)) { - value = toSet(value, parameterType); - } else { - value = jsonToObject(value.toString(), parameterType); - } - method.invoke(objectFromJson, new Object[] {value}); - noOfFields--; - } - - } - } - - if (noOfFields != 0) { - throw new IllegalArgumentException( - "Not enough setter methods for fields in given JSON String : " + jsonString - + " in class : " + klass); - } - - } catch (InstantiationException e) { - throw new IllegalArgumentException("Couldn't convert JSON to Object of type " + klass, e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException("Couldn't convert JSON to Object of type " + klass, e); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Couldn't convert JSON to Object of type " + klass, e); - } catch (InvocationTargetException e) { - throw new IllegalArgumentException("Couldn't convert JSON to Object of type " + klass, e); - } catch (GfJsonException e) { - throw new IllegalArgumentException(e); - } - return objectFromJson; - } - - private static void throwUnsupportedType(String containerType, JsonNodeType valueType) - throws GfJsonException { - throw new GfJsonException(String.format( - "Only primitive types are supported in %s type for input commands but found %s", - containerType, valueType.toString())); - } - - private static Object toArray(Object value, Class<?> parameterType) throws GfJsonException { - Class arrayComponentType = parameterType.getComponentType(); - if (isPrimitiveOrWrapper(arrayComponentType)) { - if (value instanceof ArrayNode) { - try { - ArrayNode jsonArray = (ArrayNode) value; - Object jArray = Array.newInstance(arrayComponentType, jsonArray.size()); - for (int i = 0; i < jsonArray.size(); i++) { - JsonNode elem = jsonArray.get(i); - switch (elem.getNodeType()) { - case ARRAY: - throwUnsupportedType("array", elem.getNodeType()); - case BINARY: - throwUnsupportedType("array", elem.getNodeType()); - case BOOLEAN: - Array.set(jArray, i, jsonArray.get(i).booleanValue()); - case MISSING: - throwUnsupportedType("array", elem.getNodeType()); - case NULL: - throwUnsupportedType("array", elem.getNodeType()); - case NUMBER: - if (elem.isIntegralNumber()) { - Array.set(jArray, i, elem.longValue()); - } else { - Array.set(jArray, i, elem.doubleValue()); - } - break; - case OBJECT: - throwUnsupportedType("array", elem.getNodeType()); - case POJO: - throwUnsupportedType("array", elem.getNodeType()); - case STRING: - if (elem.textValue() != null) { - Array.set(jArray, i, elem.textValue()); - } else { - Array.set(jArray, i, elem.toString()); - } - } - } - return jArray; - } catch (ArrayIndexOutOfBoundsException e) { - throw new GfJsonException(e); - } catch (IllegalArgumentException e) { - throw new GfJsonException(e); - } - } else { - throw new GfJsonException("Expected JSONArray for array type"); - } - } else - throw new GfJsonException( - "Array contains non-primitive element. Non-primitive elements are not supported in json array"); - } - - - - /** - * This is used in Put command this method uses HashSet as default implementation - * - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - private static Object toSet(Object value, Class<?> parameterType) throws GfJsonException { - try { - ArrayNode array = (ArrayNode) value; - Set set = new HashSet(); - for (int i = 0; i < array.size(); i++) { - JsonNode elem = array.get(i); - switch (elem.getNodeType()) { - case ARRAY: - throwUnsupportedType("list", elem.getNodeType()); - case BINARY: - throwUnsupportedType("list", elem.getNodeType()); - case BOOLEAN: - set.add(elem.booleanValue()); - case MISSING: - throwUnsupportedType("list", elem.getNodeType()); - case NULL: - throwUnsupportedType("list", elem.getNodeType()); - case NUMBER: - if (elem.isIntegralNumber()) { - set.add(elem.longValue()); - } else { - set.add(elem.doubleValue()); - } - break; - case OBJECT: - throwUnsupportedType("list", elem.getNodeType()); - case POJO: - throwUnsupportedType("list", elem.getNodeType()); - case STRING: - if (elem.textValue() != null) { - set.add(elem.textValue()); - } else { - set.add(elem.toString()); - } - } - } - return set; - } catch (Exception e) { - throw new GfJsonException(e); - } - } - - private static Object toMap(Object value, Class<?> parameterType) throws GfJsonException { - try { - if (value instanceof ObjectNode) { - ObjectNode obj = (ObjectNode) value; - Iterator iterator = obj.fieldNames(); - Map map = new HashMap(); - while (iterator.hasNext()) { - String key = (String) iterator.next(); - JsonNode elem = obj.get(key); - switch (elem.getNodeType()) { - case ARRAY: - throwUnsupportedType("map", elem.getNodeType()); - case BINARY: - throwUnsupportedType("map", elem.getNodeType()); - case BOOLEAN: - map.put(key, elem.booleanValue()); - case MISSING: - throwUnsupportedType("map", elem.getNodeType()); - case NULL: - throwUnsupportedType("map", elem.getNodeType()); - case NUMBER: - if (elem.isIntegralNumber()) { - map.put(key, elem.longValue()); - } else { - map.put(key, elem.doubleValue()); - } - break; - case OBJECT: - throwUnsupportedType("map", elem.getNodeType()); - case POJO: - throwUnsupportedType("map", elem.getNodeType()); - case STRING: - if (elem.textValue() != null) { - map.put(key, elem.textValue()); - } else { - map.put(key, elem.toString()); - } - } - } - return map; - } else - throw new GfJsonException( - "Expected JSONObject for Map. Retrieved type is " + value.getClass()); - } catch (Exception e) { - throw new GfJsonException(e); - } - } - - private static Object toList(Object value, Class<?> parameterType) throws GfJsonException { - try { - ArrayNode array = (ArrayNode) value; - List list = new ArrayList(); - for (int i = 0; i < array.size(); i++) { - JsonNode elem = array.get(i); - switch (elem.getNodeType()) { - case ARRAY: - throwUnsupportedType("list", elem.getNodeType()); - case BINARY: - throwUnsupportedType("list", elem.getNodeType()); - case BOOLEAN: - list.add(elem.booleanValue()); - case MISSING: - throwUnsupportedType("list", elem.getNodeType()); - case NULL: - throwUnsupportedType("list", elem.getNodeType()); - case NUMBER: - if (elem.isIntegralNumber()) { - list.add(elem.longValue()); - } else { - list.add(elem.doubleValue()); - } - break; - case OBJECT: - throwUnsupportedType("list", elem.getNodeType()); - case POJO: - throwUnsupportedType("list", elem.getNodeType()); - case STRING: - if (elem.textValue() != null) { - list.add(elem.textValue()); - } else { - list.add(elem.toString()); - } - } - } - return list; - } catch (Exception e) { - throw new GfJsonException(e); - } - } - - public static String capitalize(String str) { - String capitalized = str; - if (str == null || str.isEmpty()) { - return capitalized; - } - capitalized = String.valueOf(str.charAt(0)).toUpperCase() + str.substring(1); - - return capitalized; - } - - private static boolean isArray(Class<?> parameterType) { - return parameterType.isArray(); - } - - public static boolean isList(Class<?> klass) { - return klass.isAssignableFrom(List.class); - } - - public static boolean isSet(Class<?> klass) { - return klass.isAssignableFrom(Set.class); - } - - public static boolean isMap(Class<?> klass) { - return klass.isAssignableFrom(Map.class); - } - public static boolean isPrimitiveOrWrapper(Class<?> klass) { return klass.isAssignableFrom(Byte.class) || klass.isAssignableFrom(byte.class) || klass.isAssignableFrom(Short.class) || klass.isAssignableFrom(short.class) @@ -356,59 +40,16 @@ public class JsonUtil { || klass.isAssignableFrom(char.class); } - public static Object getPrimitiveOrWrapperValue(Class<?> klass, Object value) - throws IllegalArgumentException { - if (klass.isAssignableFrom(Byte.class) || klass.isAssignableFrom(byte.class)) { - return value; - } else if (klass.isAssignableFrom(Short.class) || klass.isAssignableFrom(short.class)) { - return value; - } else if (klass.isAssignableFrom(Integer.class) || klass.isAssignableFrom(int.class)) { - return value; - } else if (klass.isAssignableFrom(Long.class) || klass.isAssignableFrom(long.class)) { - return value; - } else if (klass.isAssignableFrom(Float.class) || klass.isAssignableFrom(float.class)) { - return value; - } else if (klass.isAssignableFrom(Double.class) || klass.isAssignableFrom(double.class)) { - return value; - } else if (klass.isAssignableFrom(Boolean.class) || klass.isAssignableFrom(boolean.class)) { - return value; - } else if (klass.isAssignableFrom(String.class)) { - return String.valueOf(value); - } else if (klass.isAssignableFrom(Character.class)) { - // Need to take care of converting between string to char values - if (value instanceof String) { - String str = (String) value; - if (str.length() == 1) - return new Character(str.charAt(0)); - else if (str.length() > 1 || str.length() == 0) { - throw new IllegalArgumentException( - "Expected Character value but found String with length " + str.length()); - } - } else if (value instanceof Character) { - return value; - } else { - throw new IllegalArgumentException( - "Expected Character value but found " + value.getClass()); - } - } else if (klass.isAssignableFrom(char.class)) { - // Need to take care of converting between string to char values - if (value instanceof String) { - String str = (String) value; - if (str.length() == 1) - return str.charAt(0); - else if (str.length() > 1 || str.length() == 0) { - throw new IllegalArgumentException( - "Expected Character value but found String with length " + str.length()); - } - } else if (value instanceof Character) { - return ((Character) value).charValue(); - } else { - throw new IllegalArgumentException( - "Expected Character value but found " + value.getClass()); - } - } else { - return null; + public static List<String> toStringList(JsonNode jsonArray) { + if (!jsonArray.isArray()) { + return Collections.emptyList(); } - return value; + + List<String> result = new ArrayList<>(); + for (JsonNode node : jsonArray) { + result.add(node.asText()); + } + + return result; } } diff --git a/geode-core/src/main/resources/org/apache/geode/internal/sanctioned-geode-core-serializables.txt b/geode-core/src/main/resources/org/apache/geode/internal/sanctioned-geode-core-serializables.txt index 2ad9818..fabf1c7 100644 --- a/geode-core/src/main/resources/org/apache/geode/internal/sanctioned-geode-core-serializables.txt +++ b/geode-core/src/main/resources/org/apache/geode/internal/sanctioned-geode-core-serializables.txt @@ -549,7 +549,6 @@ org/apache/geode/management/internal/cli/functions/UnregisterFunction,true,1 org/apache/geode/management/internal/cli/functions/UpdateCacheFunction,false org/apache/geode/management/internal/cli/functions/UpdateCacheFunction$CacheElementOperation,false org/apache/geode/management/internal/cli/functions/UserFunctionExecution,true,1 -org/apache/geode/management/internal/cli/json/GfJsonException,true,36449998984143318 org/apache/geode/management/internal/cli/result/CommandResultException,true,1,result:org/apache/geode/management/cli/Result org/apache/geode/management/internal/cli/result/TableBuilder$Align,false org/apache/geode/management/internal/cli/result/TableBuilderHelper$TooManyColumnsException,false diff --git a/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStateTest.java b/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStateTest.java index 07d0a36..d8cf92e 100755 --- a/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStateTest.java +++ b/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStateTest.java @@ -35,6 +35,8 @@ import java.net.InetAddress; import java.util.Arrays; import java.util.List; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.junit.After; import org.junit.Before; @@ -42,8 +44,7 @@ import org.junit.Test; import org.apache.geode.internal.GemFireVersion; import org.apache.geode.internal.process.ProcessUtils; -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; +import org.apache.geode.management.internal.cli.util.JsonUtil; /** * Unit tests for {@link AbstractLauncher.ServiceState}. Tests marshalling of ServiceState to and @@ -801,20 +802,20 @@ public class AbstractLauncherServiceStateTest { protected static TestState fromJson(final String json) { try { - GfJsonObject gfJsonObject = new GfJsonObject(json); - - Status status = valueOfDescription(gfJsonObject.getString(JSON_STATUS)); - List<String> jvmArguments = gfJsonObject.getJSONArray(JSON_JVMARGUMENTS).toStringList(); - - return new TestState(status, gfJsonObject.getString(JSON_STATUSMESSAGE), - gfJsonObject.getLong(JSON_TIMESTAMP), gfJsonObject.getString(JSON_LOCATION), - gfJsonObject.getInt(JSON_PID), gfJsonObject.getLong(JSON_UPTIME), - gfJsonObject.getString(JSON_WORKINGDIRECTORY), jvmArguments, - gfJsonObject.getString(JSON_CLASSPATH), gfJsonObject.getString(JSON_GEMFIREVERSION), - gfJsonObject.getString(JSON_JAVAVERSION), gfJsonObject.getString(JSON_LOGFILE), - gfJsonObject.getString(JSON_HOST), gfJsonObject.getString(JSON_PORT), - gfJsonObject.getString(JSON_MEMBERNAME)); - } catch (GfJsonException e) { + JsonNode jsonObject = new ObjectMapper().readTree(json); + + Status status = valueOfDescription(jsonObject.get(JSON_STATUS).asText()); + List<String> jvmArguments = JsonUtil.toStringList(jsonObject.get(JSON_JVMARGUMENTS)); + + return new TestState(status, jsonObject.get(JSON_STATUSMESSAGE).asText(), + jsonObject.get(JSON_TIMESTAMP).asLong(), jsonObject.get(JSON_LOCATION).asText(), + jsonObject.get(JSON_PID).asInt(), jsonObject.get(JSON_UPTIME).asLong(), + jsonObject.get(JSON_WORKINGDIRECTORY).asText(), jvmArguments, + jsonObject.get(JSON_CLASSPATH).asText(), jsonObject.get(JSON_GEMFIREVERSION).asText(), + jsonObject.get(JSON_JAVAVERSION).asText(), jsonObject.get(JSON_LOGFILE).asText(), + jsonObject.get(JSON_HOST).asText(), jsonObject.get(JSON_PORT).asText(), + jsonObject.get(JSON_MEMBERNAME).asText()); + } catch (Exception e) { throw new IllegalArgumentException("Unable to create TestState from JSON: " + json); } } diff --git a/geode-core/src/test/java/org/apache/geode/distributed/LocatorStateTest.java b/geode-core/src/test/java/org/apache/geode/distributed/LocatorStateTest.java index 843f8b2..8339820 100755 --- a/geode-core/src/test/java/org/apache/geode/distributed/LocatorStateTest.java +++ b/geode-core/src/test/java/org/apache/geode/distributed/LocatorStateTest.java @@ -22,14 +22,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.apache.geode.distributed.AbstractLauncher.ServiceState; import org.apache.geode.distributed.AbstractLauncher.Status; import org.apache.geode.distributed.LocatorLauncher.LocatorState; -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; /** * Unit tests for {@link LocatorLauncher.LocatorState}. @@ -79,10 +79,9 @@ public class LocatorStateTest { // when: passed to fromJson Throwable thrown = catchThrowable(() -> fromJson(emptyString)); - // then: throws IllegalArgumentException with cause of GfJsonException assertThat(thrown).isInstanceOf(IllegalArgumentException.class) - .hasCauseInstanceOf(GfJsonException.class); - assertThat(thrown.getCause()).isInstanceOf(GfJsonException.class).hasNoCause(); + .hasCauseInstanceOf(NullPointerException.class); + assertThat(thrown.getCause()).isInstanceOf(NullPointerException.class).hasNoCause(); } @Test @@ -95,8 +94,8 @@ public class LocatorStateTest { // then: throws IllegalArgumentException with cause of GfJsonException assertThat(thrown).isInstanceOf(IllegalArgumentException.class) - .hasCauseInstanceOf(GfJsonException.class); - assertThat(thrown.getCause()).isInstanceOf(GfJsonException.class).hasNoCause(); + .hasCauseInstanceOf(NullPointerException.class); + assertThat(thrown.getCause()).isInstanceOf(NullPointerException.class).hasNoCause(); } @Test @@ -165,6 +164,14 @@ public class LocatorStateTest { map.put(ServiceState.JSON_TIMESTAMP, timestampTime); map.put(ServiceState.JSON_UPTIME, uptime); map.put(ServiceState.JSON_WORKINGDIRECTORY, workingDirectory); - return new GfJsonObject(map).toString(); + + String status = null; + try { + status = new ObjectMapper().writeValueAsString(map); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + + return status; } } diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/DataCommandJsonJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/DataCommandJsonJUnitTest.java deleted file mode 100644 index bcb83be..0000000 --- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/DataCommandJsonJUnitTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.apache.geode.management.internal.cli; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; - -import org.junit.Test; - -import org.apache.geode.management.internal.cli.dto.Car; -import org.apache.geode.management.internal.cli.util.JsonUtil; - -public class DataCommandJsonJUnitTest { - - @Test - public void testCollectionTypesInJson() { - String json = - "{'attributes':{'power':'90hp'},'make':'502.1825','model':'502.1825','colors':['red','white','blue'],'attributeSet':['red','white','blue'], 'attributeArray':['red','white','blue']}"; - Car car = (Car) JsonUtil.jsonToObject(json, Car.class); - assertNotNull(car.getAttributeSet()); - assertTrue(car.getAttributeSet() instanceof HashSet); - assertEquals(3, car.getAttributeSet().size()); - - assertNotNull(car.getColors()); - assertTrue(car.getColors() instanceof ArrayList); - assertEquals(3, car.getColors().size()); - - assertNotNull(car.getAttributes()); - assertTrue(car.getAttributes() instanceof HashMap); - assertEquals(1, car.getAttributes().size()); - assertTrue(car.getAttributes().containsKey("power")); - - assertNotNull(car.getAttributeArray()); - assertTrue(car.getAttributeArray() instanceof String[]); - assertEquals(3, car.getAttributeArray().length); - } -} diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/GfJsonArrayTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/GfJsonArrayTest.java deleted file mode 100644 index 409dcd9..0000000 --- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/GfJsonArrayTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package org.apache.geode.management.internal.cli.json; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Before; -import org.junit.Test; - - -public class GfJsonArrayTest { - - private GfJsonArray gfJsonArray; - - public static class Simple { - private int key; - private String value; - - public Simple(int key, String value) { - this.key = key; - this.value = value; - } - - public int getKey() { - return key; - } - - public String getValue() { - return value; - } - } - - @Before - public void setup() { - gfJsonArray = new GfJsonArray(); - } - - @Test - public void emptyArray() { - assertThat(gfJsonArray.size()).isEqualTo(0); - assertThat(gfJsonArray.toString()).isEqualTo("[]"); - } - - @Test - public void arrayFromPrimitives() throws Exception { - gfJsonArray = new GfJsonArray(new String[] {"a", "b", "c"}); - - assertThat(gfJsonArray.size()).isEqualTo(3); - assertThat(gfJsonArray.getString(0)).isEqualTo("a"); - assertThat(gfJsonArray.getString(1)).isEqualTo("b"); - assertThat(gfJsonArray.getString(2)).isEqualTo("c"); - } - - @Test - public void addSingleObject() throws Exception { - gfJsonArray.put("a"); - assertThat(gfJsonArray.getString(0)).isEqualTo("a"); - assertThat(gfJsonArray.toString()).isEqualTo("[\"a\"]"); - } - - @Test - public void addMultipleObjects() throws Exception { - gfJsonArray.put("a"); - gfJsonArray.put("b"); - gfJsonArray.put("c"); - - assertThat(gfJsonArray.getString(0)).isEqualTo("a"); - assertThat(gfJsonArray.getString(1)).isEqualTo("b"); - assertThat(gfJsonArray.getString(2)).isEqualTo("c"); - assertThat(gfJsonArray.toString()).isEqualTo("[\"a\",\"b\",\"c\"]"); - } - - @Test - public void putObject() throws Exception { - GfJsonObject obj = new GfJsonObject(new Simple(1, "a")); - gfJsonArray.put(obj); - gfJsonArray.put(1, obj); - - assertThat(gfJsonArray.getJsonObject(0).getInt("key")).isEqualTo(1); - assertThat(gfJsonArray.getJsonObject(0).getString("value")).isEqualTo("a"); - assertThat(gfJsonArray.getJsonObject(1).getInt("key")).isEqualTo(1); - assertThat(gfJsonArray.getJsonObject(1).getString("value")).isEqualTo("a"); - } - - @Test - public void putOutOfBoundsAddsNull() throws Exception { - gfJsonArray.put(1, "a"); - - assertThat(gfJsonArray.size()).isEqualTo(2); - assertThat(gfJsonArray.toString()).isEqualTo("[null,\"a\"]"); - } - - -} diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/GfJsonObjectTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/GfJsonObjectTest.java deleted file mode 100644 index 1a6e2a9..0000000 --- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/GfJsonObjectTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package org.apache.geode.management.internal.cli.json; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.Before; -import org.junit.Test; - - -public class GfJsonObjectTest { - - private GfJsonObject gfJsonObject; - - public static class Simple { - private int key; - private String value; - - public int getKey() { - return key; - } - - public String getValue() { - return value; - } - - public Simple(int key, String value) { - this.key = key; - this.value = value; - } - } - - public static class GetMethodReturnsObjectReferencingMe { - private String id; - private GetMethodReturnsObjectReferencingMe peer; - - static GetMethodReturnsObjectReferencingMe createTestInstance() { - GetMethodReturnsObjectReferencingMe inst1 = new GetMethodReturnsObjectReferencingMe(); - inst1.id = "instance1"; - GetMethodReturnsObjectReferencingMe inst2 = new GetMethodReturnsObjectReferencingMe(); - inst2.id = "instance2"; - inst1.peer = inst2; - inst2.peer = inst1; - return inst1; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public GetMethodReturnsObjectReferencingMe getPeer() { - return peer; - } - - } - - - @Before - public void setup() { - gfJsonObject = new GfJsonObject(); - } - - @Test - public void emptyObject() { - assertThat(gfJsonObject.toString()).isEqualTo("{}"); - } - - @Test - public void addObject() { - gfJsonObject = new GfJsonObject(new Simple(1, "a")); - - assertThat(gfJsonObject.getString("key")).isEqualTo("1"); - assertThat(gfJsonObject.getString("value")).isEqualTo("a"); - } - - @Test - public void addBidirectionalReferenceObject() throws GfJsonException { - // JSONObject.cyclicDepChkEnabled.set(true); - // JSONObject.cyclicDependencySet.set(new HashSet()); - new GfJsonObject(new GetMethodReturnsObjectReferencingMe()); - } - - @Test - public void addRawObject() throws Exception { - gfJsonObject = new GfJsonObject("{\"key\":1}"); - assertThat(gfJsonObject.getString("key")).isEqualTo("1"); - } - - @Test - public void accumulatePrimitives() throws Exception { - gfJsonObject.accumulate("string", "value1"); - gfJsonObject.accumulate("string", "value2"); - - assertThat(gfJsonObject.getString("string")).isEqualTo("[\"value1\",\"value2\"]"); - } - - @Test - public void putAndGetPrimitives() throws Exception { - gfJsonObject.put("string", "value1"); - gfJsonObject.put("int", Integer.MAX_VALUE); - gfJsonObject.put("boolean", true); - gfJsonObject.put("double", Double.MAX_VALUE); - gfJsonObject.put("long", Long.MAX_VALUE); - - assertThat(gfJsonObject.getString("string")).isEqualTo("value1"); - - assertThat(gfJsonObject.getString("int")).isEqualTo(Integer.toString(Integer.MAX_VALUE)); - assertThat(gfJsonObject.getInt("int")).isEqualTo(Integer.MAX_VALUE); - - assertThat(gfJsonObject.getString("boolean")).isEqualTo("true"); - assertThat(gfJsonObject.getBoolean("boolean")).isEqualTo(true); - - assertThat(gfJsonObject.getString("double")).isEqualTo(Double.toString(Double.MAX_VALUE)); - assertThat(gfJsonObject.getDouble("double")).isEqualTo(Double.MAX_VALUE); - - assertThat(gfJsonObject.getString("long")).isEqualTo(Long.toString(Long.MAX_VALUE)); - assertThat(gfJsonObject.getDouble("long")).isEqualTo(Long.MAX_VALUE); - } - - @Test - public void appendCreatesAndAddsToArray() throws Exception { - gfJsonObject.append("array", 1); - gfJsonObject.append("array", 2); - - assertThat(gfJsonObject.getString("array")).isEqualTo("[1,2]"); - } - - @Test - public void cannotAppendToExistingKey() throws Exception { - gfJsonObject.put("wat", 1); - assertThatThrownBy(() -> gfJsonObject.append("wat", 2)).isInstanceOf(GfJsonException.class); - } - - @Test - public void canGetGfJsonObject() throws Exception { - GfJsonObject sub = new GfJsonObject(); - sub.put("foo", "bar"); - gfJsonObject.put("sub", sub); - - assertThat(gfJsonObject.getJSONObject("sub").toString()).isEqualTo("{\"foo\":\"bar\"}"); - } - - @Test - public void canGetGfJsonArray() throws Exception { - gfJsonObject.append("array", 1); - gfJsonObject.append("array", "a"); - - assertThat(gfJsonObject.getJSONArray("array").toString()).isEqualTo("[1,\"a\"]"); - } - - @Test - public void canGetNames() throws Exception { - gfJsonObject.put("string", "value1"); - gfJsonObject.put("int", Integer.MAX_VALUE); - gfJsonObject.put("boolean", true); - gfJsonObject.put("double", Double.MAX_VALUE); - gfJsonObject.put("long", Long.MAX_VALUE); - - assertThat(gfJsonObject.names().size()).isEqualTo(5); - assertThat(gfJsonObject.names().toString()) - .isEqualTo("[\"string\",\"int\",\"boolean\",\"double\",\"long\"]"); - } -} diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/QueryResultFormatterTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/QueryResultFormatterTest.java index 888fa0f..9849d4e 100644 --- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/QueryResultFormatterTest.java +++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/json/QueryResultFormatterTest.java @@ -25,6 +25,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; @@ -140,12 +142,12 @@ public class QueryResultFormatterTest { checkResult(queryResultFormatter); } - private void checkResult(final QueryResultFormatter queryResultFormatter) throws GfJsonException { + private void checkResult(final QueryResultFormatter queryResultFormatter) throws Exception { String jsonString = queryResultFormatter.toString(); System.out.println("queryResultFormatter.toString=" + jsonString); - GfJsonObject gfJsonObject = new GfJsonObject(jsonString); - System.out.println("gfJsonObject=" + gfJsonObject); - assertThat(gfJsonObject.get(RESULT)).isNotNull(); + JsonNode jsonObject = new ObjectMapper().readTree(jsonString); + System.out.println("jsonObject=" + jsonObject); + assertThat(jsonObject.get(RESULT)).isNotNull(); } private enum Currency { diff --git a/geode-dunit/src/main/java/org/apache/geode/pdx/JSONFormatVerifyUtility.java b/geode-dunit/src/main/java/org/apache/geode/pdx/JSONFormatVerifyUtility.java index c371744..0b8fa71 100644 --- a/geode-dunit/src/main/java/org/apache/geode/pdx/JSONFormatVerifyUtility.java +++ b/geode-dunit/src/main/java/org/apache/geode/pdx/JSONFormatVerifyUtility.java @@ -16,67 +16,64 @@ package org.apache.geode.pdx; -import org.junit.Assert; +import java.io.IOException; -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Assert; public class JSONFormatVerifyUtility { static void verifyJsonWithJavaObject(String json, TestObjectForJSONFormatter testObject) - throws GfJsonException { - GfJsonObject jsonObject = new GfJsonObject(json); + throws IOException { + JsonNode jsonObject = new ObjectMapper().readTree(json); // Testcase-1: Validate json string against the pdxInstance. // validation for primitive types Assert.assertEquals("VerifyPdxInstanceToJson: Int type values are not matched", testObject.getP_int(), - jsonObject.getInt(testObject.getP_intFN())); + jsonObject.get(testObject.getP_intFN()).asInt()); Assert.assertEquals("VerifyPdxInstanceToJson: long type values are not matched", - testObject.getP_long(), jsonObject.getLong(testObject.getP_longFN())); + testObject.getP_long(), jsonObject.get(testObject.getP_longFN()).asLong()); // validation for wrapper types Assert.assertEquals("VerifyPdxInstanceToJson: Boolean type values are not matched", - testObject.getW_bool().booleanValue(), jsonObject.getBoolean(testObject.getW_boolFN())); + testObject.getW_bool().booleanValue(), + jsonObject.get(testObject.getW_boolFN()).asBoolean()); Assert.assertEquals("VerifyPdxInstanceToJson: Float type values are not matched", - testObject.getW_double().doubleValue(), jsonObject.getDouble(testObject.getW_doubleFN()), + testObject.getW_double().doubleValue(), + jsonObject.get(testObject.getW_doubleFN()).asDouble(), 0); Assert.assertEquals("VerifyPdxInstanceToJson: bigDec type values are not matched", - testObject.getW_bigDec().longValue(), jsonObject.getLong(testObject.getW_bigDecFN())); + testObject.getW_bigDec().longValue(), jsonObject.get(testObject.getW_bigDecFN()).asLong()); // validation for array types Assert.assertEquals("VerifyPdxInstanceToJson: Byte[] type values are not matched", (int) testObject.getW_byteArray()[1], - jsonObject.getJSONArray(testObject.getW_byteArrayFN()).getInternalJsonArray().get(1) - .asInt()); + jsonObject.get(testObject.getW_byteArrayFN()).get(1).asInt()); Assert.assertEquals("VerifyPdxInstanceToJson: Double[] type values are not matched", testObject.getW_doubleArray()[0], - jsonObject.getJSONArray(testObject.getW_doubleArrayFN()).getInternalJsonArray().get(0) - .asDouble(0), - 0); + jsonObject.get(testObject.getW_doubleArrayFN()).get(0).asDouble(0), 0); Assert.assertEquals("VerifyPdxInstanceToJson: String[] type values are not matched", testObject.getW_strArray()[2], - jsonObject.getJSONArray(testObject.getW_strArrayFN()).getInternalJsonArray().get(2) - .textValue()); + jsonObject.get(testObject.getW_strArrayFN()).get(2).textValue()); // validation for collection types Assert.assertEquals("VerifyPdxInstanceToJson: list type values are not matched", testObject.getC_list().get(0), - jsonObject.getJSONArray(testObject.getC_listFN()).getInternalJsonArray().get(0) - .textValue()); + jsonObject.get(testObject.getC_listFN()).get(0).textValue()); Assert.assertEquals("VerifyPdxInstanceToJson: stack type values are not matched", testObject.getC_stack().get(2), - jsonObject.getJSONArray(testObject.getC_stackFN()).getInternalJsonArray().get(2) - .textValue()); + jsonObject.get(testObject.getC_stackFN()).get(2).textValue()); // validation for Map Assert.assertEquals("VerifyPdxInstanceToJson: Map type values are not matched", testObject.getM_empByCity().get("Ahmedabad").get(0).getFname(), - jsonObject.getJSONObject(testObject.getM_empByCityFN()).getJSONArray("Ahmedabad") - .getJsonObject(0).getString("fname")); + jsonObject.get(testObject.getM_empByCityFN()).get("Ahmedabad") + .get(0).get("fname").asText()); // validation Enum Assert.assertEquals("VerifyPdxInstanceToJson: Enum type values are not matched", - testObject.getDay().toString(), jsonObject.getString(testObject.getDayFN())); + testObject.getDay().toString(), jsonObject.get(testObject.getDayFN()).asText()); } } diff --git a/geode-junit/src/main/java/org/apache/geode/pdx/TestObjectForJSONFormatter.java b/geode-junit/src/main/java/org/apache/geode/pdx/TestObjectForJSONFormatter.java index 85fd4a8..f2c3b59 100755 --- a/geode-junit/src/main/java/org/apache/geode/pdx/TestObjectForJSONFormatter.java +++ b/geode-junit/src/main/java/org/apache/geode/pdx/TestObjectForJSONFormatter.java @@ -14,6 +14,7 @@ */ package org.apache.geode.pdx; +import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayDeque; @@ -29,11 +30,9 @@ import java.util.Queue; import java.util.Set; import java.util.Stack; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; - enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } @@ -99,11 +98,10 @@ public class TestObjectForJSONFormatter implements PdxSerializable { public TestObjectForJSONFormatter() {} - public String addClassTypeToJson(String json) throws GfJsonException { - GfJsonObject jsonObj = new GfJsonObject(json); - ((ObjectNode) jsonObj.getInternalJsonObject()).put("@type", - "org.apache.geode.pdx.TestObjectForJSONFormatter"); - return jsonObj.toString(); + public String addClassTypeToJson(String json) throws IOException { + ObjectNode node = (ObjectNode) new ObjectMapper().readTree(json); + node.put("@type", "org.apache.geode.pdx.TestObjectForJSONFormatter"); + return node.toString(); } public void defaultInitialization() {