You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by cz...@apache.org on 2020/09/10 13:25:45 UTC

[sling-org-apache-sling-servlets-get] branch master updated: SLING-9726 : Support more property types for JSON conversion

This is an automated email from the ASF dual-hosted git repository.

cziegeler pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-servlets-get.git


The following commit(s) were added to refs/heads/master by this push:
     new 13cb078  SLING-9726 : Support more property types for JSON conversion
13cb078 is described below

commit 13cb07804a4b88ef8c871211ea420d0183d15ac4
Author: Carsten Ziegeler <cz...@apache.org>
AuthorDate: Thu Sep 10 15:24:59 2020 +0200

    SLING-9726 : Support more property types for JSON conversion
---
 bnd.bnd                                            |   6 +
 pom.xml                                            |  41 ++-----
 .../servlets/get/impl/util/JsonObjectCreator.java  | 130 +++++++++++++++------
 .../get/impl/util/JsonObjectCreatorTest.java       |  78 +++++++++++++
 4 files changed, 193 insertions(+), 62 deletions(-)

diff --git a/bnd.bnd b/bnd.bnd
new file mode 100644
index 0000000..2f8c6bb
--- /dev/null
+++ b/bnd.bnd
@@ -0,0 +1,6 @@
+Import-Package:\
+  javax.jcr;resolution:=optional,\
+  javax.jcr.version;resolution:=optional,\
+  *
+Conditional-Package:\
+  org.apache.jackrabbit.util
diff --git a/pom.xml b/pom.xml
index da3b692..6fc05e9 100644
--- a/pom.xml
+++ b/pom.xml
@@ -22,13 +22,12 @@
     <modelVersion>4.0.0</modelVersion>
     <parent>
         <groupId>org.apache.sling</groupId>
-        <artifactId>sling</artifactId>
-        <version>32</version>
+        <artifactId>sling-bundle-parent</artifactId>
+        <version>39</version>
         <relativePath />
     </parent>
 
     <artifactId>org.apache.sling.servlets.get</artifactId>
-    <packaging>bundle</packaging>
     <version>2.1.41-SNAPSHOT</version>
 
     <name>Apache Sling Default GET Servlets</name>
@@ -51,21 +50,8 @@
     <build>
         <plugins>
             <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                <extensions>true</extensions> 
-                <configuration>
-                    <instructions>
-                        <Import-Package>
-                            javax.jcr;resolution:=optional,
-                            javax.jcr.version;resolution:=optional,
-                            *
-                        </Import-Package>
-                        <Conditional-Package>
-                            org.apache.jackrabbit.util
-                        </Conditional-Package>
-                    </instructions>
-                </configuration>
+                <groupId>biz.aQute.bnd</groupId>
+                <artifactId>bnd-maven-plugin</artifactId>
             </plugin>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
@@ -168,23 +154,20 @@
         <dependency>
             <groupId>org.apache.sling</groupId>
             <artifactId>org.apache.sling.commons.johnzon</artifactId>
-            <version>1.0.0</version>
+            <version>1.2.4</version>
             <scope>provided</scope>
         </dependency>
-                <dependency>
+        <dependency>
         	<groupId>org.apache.sling</groupId>
         	<artifactId>org.apache.sling.testing.sling-mock</artifactId>
         	<version>2.2.10</version>
         	<scope>test</scope>
         </dependency>
-                        <dependency>
-                	<groupId>org.apache.sling</groupId>
-                	<artifactId>
-                		org.apache.sling.servlet-helpers
-                	</artifactId>
-                	<version>1.1.6</version>
-                	<type>bundle</type>
-                	<scope>test</scope>
-                </dependency>
+        <dependency>
+            <groupId>org.apache.sling</groupId>
+            <artifactId>org.apache.sling.servlet-helpers</artifactId>
+            <version>1.1.6</version>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 </project>
diff --git a/src/main/java/org/apache/sling/servlets/get/impl/util/JsonObjectCreator.java b/src/main/java/org/apache/sling/servlets/get/impl/util/JsonObjectCreator.java
index 2452747..72dbb02 100644
--- a/src/main/java/org/apache/sling/servlets/get/impl/util/JsonObjectCreator.java
+++ b/src/main/java/org/apache/sling/servlets/get/impl/util/JsonObjectCreator.java
@@ -24,9 +24,11 @@ import java.lang.reflect.Array;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
+import java.util.Collection;
 import java.util.Iterator;
 import java.util.Locale;
 import java.util.Map;
+import java.util.function.Supplier;
 
 import javax.json.Json;
 import javax.json.JsonArrayBuilder;
@@ -51,17 +53,25 @@ public class JsonObjectCreator {
 
     private boolean ecmaSupport;
 
+    /**
+     * Create a new json object creator
+     * @param resource The source
+     * @param ecmaSupport ECMA date format for Calendar
+     */
     public JsonObjectCreator(Resource resource, boolean ecmaSupport) {
         this.resource = resource;
         this.valueMap = resource.getValueMap();
         this.ecmaSupport = ecmaSupport;
     }
 
+    /**
+     * Create the object builder
+     * @return The object builder
+     */
     public JsonObjectBuilder create() {
         final JsonObjectBuilder obj = Json.createObjectBuilder();
 
-        ValueMap valueMap = resource.getValueMap();
-        if (valueMap.isEmpty()) {
+         if (valueMap.isEmpty()) {
             final String value = resource.adaptTo(String.class);
             if (value != null) {
                 obj.add(resource.getName(), value.toString());
@@ -82,14 +92,17 @@ public class JsonObjectCreator {
 
         while (props.hasNext()) {
             final Map.Entry<String, Object> prop = props.next();
-            if (prop.getValue() != null) {
-                createProperty(obj, prop.getKey(), prop.getValue());
-            }
+            createProperty(obj, prop.getKey(), prop.getValue());
         }
 
         return obj;
     }
 
+    /**
+     * Helper method to format a calendar
+     * @param date The calendar
+     * @return The formated output
+     */
     public static String formatEcma(final Calendar date) {
         DateFormat formatter = new SimpleDateFormat(ECMA_DATE_FORMAT, DATE_FORMAT_LOCALE);
         formatter.setTimeZone(date.getTimeZone());
@@ -97,36 +110,90 @@ public class JsonObjectCreator {
     }
 
     /** Dump only a value in the correct format */
-    private JsonValue getValue(final Object value) {
-        JsonObjectBuilder builder = Json.createObjectBuilder();
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    private JsonValue getValue(Object value) {
+        if ( value instanceof Supplier ) {
+            return getValue(((Supplier)value).get());
+        }
 
+        if (value == null) {
+            return Json.createValue("");
+        }
         if (value instanceof InputStream) {
             // input stream is already handled
-            builder.add("entry", 0);
+            return Json.createValue(0);
+
         } else if (value instanceof Calendar) {
             if (ecmaSupport) {
-                builder.add("entry", JsonObjectCreator.formatEcma((Calendar) value));
+                return Json.createValue(JsonObjectCreator.formatEcma((Calendar) value));
             } else {
-                builder.add("entry", ISO8601.format(((Calendar) value)));
+                return Json.createValue(ISO8601.format(((Calendar) value)));
             }
+
         } else if (value instanceof Boolean) {
-            builder.add("entry", (Boolean) value);
+            final Boolean bool = (Boolean)value;
+            return bool ? JsonValue.TRUE : JsonValue.FALSE;
+
         } else if (value instanceof Long) {
-            builder.add("entry", (Long) value);
+            return Json.createValue((Long) value);
+
         } else if (value instanceof Double) {
-            builder.add("entry", (Double) value);
-        } else if (value != null) {
-            builder.add("entry", value.toString());
-        } else {
-            builder.add("entry", "");
+
+            return Json.createValue((Double) value);
+
+        } else if (value instanceof String) {
+            return Json.createValue((String) value);
+
+        } else if (value instanceof Integer) {
+            return Json.createValue((Integer) value);
+
+        } else if (value instanceof Short) {
+            return Json.createValue((Short) value);
+
+        } else if (value instanceof Byte) {
+            return Json.createValue((Byte) value);
+
+        } else if (value instanceof Float) {
+            return Json.createValue((Float) value);
+
+        } else if (value instanceof Map) {
+            final JsonObjectBuilder builder = Json.createObjectBuilder();
+            for (final Map.Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet()) {
+                final JsonValue v = getValue(entry.getValue());
+                builder.add(entry.getKey().toString(), v);
+            }
+            return builder.build();
+
+        } else if (value instanceof Collection) {
+            final JsonArrayBuilder builder = Json.createArrayBuilder();
+            for (final Object obj : (Collection) value) {
+                builder.add(getValue(obj));
+            }
+            return builder.build();
+
+        } else if (value.getClass().isArray()) {
+            final JsonArrayBuilder builder = Json.createArrayBuilder();
+            for (int i = 0; i < Array.getLength(value); i++) {
+                builder.add(getValue(Array.get(value, i)));
+            }
+            return builder.build();
         }
-        return builder.build().get("entry");
+        return Json.createValue(value.toString());
     }
 
     /**
      * Write a single property
      */
+    @SuppressWarnings("rawtypes")
     private void createProperty(final JsonObjectBuilder obj, final String key, final Object value) {
+        if ( value == null ) {
+            return;
+        }
+        if ( value instanceof Supplier ) {
+            createProperty(obj, key, ((Supplier)value).get());
+            return;
+        }
+
         Object[] values = null;
         if (value.getClass().isArray()) {
             final int length = Array.getLength(value);
@@ -138,6 +205,9 @@ public class JsonObjectCreator {
             values = new Object[Array.getLength(value)];
             for (int i = 0; i < length; i++) {
                 values[i] = Array.get(value, i);
+                while ( values[i] instanceof Supplier ) {
+                    values[i] = ((Supplier)values[i]).get();
+                }
             }
         }
 
@@ -159,14 +229,10 @@ public class JsonObjectCreator {
             return;
         }
 
-        if (!value.getClass().isArray()) {
-            obj.add(key, getValue(value));
+        if (values != null ) {
+            obj.add(key, getValue(values));
         } else {
-            final JsonArrayBuilder result = Json.createArrayBuilder();
-            for (Object v : values) {
-                result.add(getValue(v));
-            }
-            obj.add(key, result);
+            obj.add(key, getValue(value));
         }
     }
 
@@ -175,14 +241,12 @@ public class JsonObjectCreator {
             stream.close();
         } catch (IOException ignore) {
         }
-        if (valueMap != null) {
-            if (index == -1) {
-                return valueMap.get(key, index);
-            }
-            Long[] lengths = valueMap.get(key, Long[].class);
-            if (lengths != null && lengths.length > index) {
-                return lengths[index];
-            }
+        if (index == -1) {
+            return valueMap.get(key, Long.class);
+        }
+        final Long[] lengths = valueMap.get(key, Long[].class);
+        if (lengths != null && lengths.length > index) {
+            return lengths[index];
         }
         return -1;
     }
diff --git a/src/test/java/org/apache/sling/servlets/get/impl/util/JsonObjectCreatorTest.java b/src/test/java/org/apache/sling/servlets/get/impl/util/JsonObjectCreatorTest.java
new file mode 100644
index 0000000..293bff0
--- /dev/null
+++ b/src/test/java/org/apache/sling/servlets/get/impl/util/JsonObjectCreatorTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.sling.servlets.get.impl.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.json.JsonString;
+import javax.json.JsonValue;
+import javax.json.JsonValue.ValueType;
+
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.wrappers.ValueMapDecorator;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+public class JsonObjectCreatorTest {
+
+    private JsonValue createJsonValue(final Object value) {
+        final Resource rsrc = Mockito.mock(Resource.class);
+        final Map<String, Object> values = new HashMap<>();
+        values.put("v", value);
+        Mockito.when(rsrc.getValueMap()).thenReturn(new ValueMapDecorator(values));
+
+        final JsonObjectCreator joc = new JsonObjectCreator(rsrc, false);
+
+        return joc.create().build().get("v");
+    }
+
+    @Test public void testBoolean() {
+        final JsonValue t = createJsonValue(Boolean.TRUE);
+        assertEquals(JsonValue.TRUE, t);
+
+        final JsonValue f = createJsonValue(Boolean.FALSE);
+        assertEquals(JsonValue.FALSE, f);
+    }
+
+    @Test public void testBooleanArray() {
+        final JsonValue t = createJsonValue(new boolean[] {true, false, true});
+        assertEquals(ValueType.ARRAY, t.getValueType());
+        assertEquals(3, t.asJsonArray().size());
+        assertEquals(JsonValue.TRUE, t.asJsonArray().get(0));
+        assertEquals(JsonValue.FALSE, t.asJsonArray().get(1));
+        assertEquals(JsonValue.TRUE, t.asJsonArray().get(2));
+    }
+
+    @Test public void testNull() {
+        final JsonValue t = createJsonValue(null);
+        assertNull(t);
+    }
+
+    @Test public void testNullInArray() {
+        final JsonValue t = createJsonValue(new String[] {null});
+        assertEquals(ValueType.ARRAY, t.getValueType());
+        assertEquals(1, t.asJsonArray().size());
+        assertEquals("", ((JsonString)t.asJsonArray().get(0)).getString());
+    }
+
+}
\ No newline at end of file