You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@johnzon.apache.org by rm...@apache.org on 2019/08/10 16:06:34 UTC

[johnzon] branch master updated: JOHNZON-240 ensure child attributes are serialized after parent ones by default

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

rmannibucau pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/johnzon.git


The following commit(s) were added to refs/heads/master by this push:
     new c9cbe0e  JOHNZON-240 ensure child attributes are serialized after parent ones by default
c9cbe0e is described below

commit c9cbe0e598e7b60713cea15f58ab783879439612
Author: Romain Manni-Bucau <rm...@apache.org>
AuthorDate: Sat Aug 10 18:06:29 2019 +0200

    JOHNZON-240 ensure child attributes are serialized after parent ones by default
---
 .../org/apache/johnzon/jsonb/JohnzonBuilder.java   |  4 +-
 .../org/apache/johnzon/jsonb/JsonbAccessMode.java  |  9 +--
 ...rchyAndLexicographicalOrderFieldComparator.java | 69 ++++++++++++++++++++++
 .../apache/johnzon/jsonb/DefaultMappingTest.java   |  2 +-
 .../johnzon/jsonb/HierarchySerializationTest.java  | 43 ++++++++++++++
 5 files changed, 120 insertions(+), 7 deletions(-)

diff --git a/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/JohnzonBuilder.java b/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/JohnzonBuilder.java
index eaf4465..722a1d0 100644
--- a/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/JohnzonBuilder.java
+++ b/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/JohnzonBuilder.java
@@ -29,7 +29,7 @@ import static java.time.temporal.ChronoField.YEAR;
 import static java.util.Collections.emptyMap;
 import static java.util.Optional.ofNullable;
 import static javax.json.bind.config.PropertyNamingStrategy.IDENTITY;
-import static javax.json.bind.config.PropertyOrderStrategy.LEXICOGRAPHICAL;
+import static javax.json.bind.config.PropertyOrderStrategy.ANY;
 
 import java.io.Closeable;
 import java.lang.reflect.InvocationTargetException;
@@ -168,7 +168,7 @@ public class JohnzonBuilder implements JsonbBuilder {
         final Optional<Object> namingStrategyValue = config.getProperty(JsonbConfig.PROPERTY_NAMING_STRATEGY);
 
         final PropertyNamingStrategy propertyNamingStrategy = new PropertyNamingStrategyFactory(namingStrategyValue.orElse(IDENTITY)).create();
-        final String orderValue = config.getProperty(JsonbConfig.PROPERTY_ORDER_STRATEGY).map(String::valueOf).orElse(LEXICOGRAPHICAL);
+        final String orderValue = config.getProperty(JsonbConfig.PROPERTY_ORDER_STRATEGY).map(String::valueOf).orElse(ANY);
         final PropertyVisibilityStrategy visibilityStrategy = config.getProperty(JsonbConfig.PROPERTY_VISIBILITY_STRATEGY)
                 .map(PropertyVisibilityStrategy.class::cast).orElse(new DefaultPropertyVisibilityStrategy());
 
diff --git a/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/JsonbAccessMode.java b/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/JsonbAccessMode.java
index a7ce489..d430960 100644
--- a/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/JsonbAccessMode.java
+++ b/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/JsonbAccessMode.java
@@ -93,6 +93,7 @@ import org.apache.johnzon.jsonb.converter.JsonbLocalDateTimeConverter;
 import org.apache.johnzon.jsonb.converter.JsonbNumberConverter;
 import org.apache.johnzon.jsonb.converter.JsonbValueConverter;
 import org.apache.johnzon.jsonb.converter.JsonbZonedDateTimeConverter;
+import org.apache.johnzon.jsonb.order.PerHierarchyAndLexicographicalOrderFieldComparator;
 import org.apache.johnzon.jsonb.serializer.JohnzonDeserializationContext;
 import org.apache.johnzon.jsonb.serializer.JohnzonSerializationContext;
 import org.apache.johnzon.jsonb.spi.JohnzonAdapterFactory;
@@ -746,11 +747,11 @@ public class JsonbAccessMode implements AccessMode, Closeable {
                     if (i2 < 0) {
                         if (order != null) {
                             switch (order) {
+                                case PropertyOrderStrategy.ANY:
                                 case PropertyOrderStrategy.LEXICOGRAPHICAL:
                                     return o1.compareTo(o2);
                                 case PropertyOrderStrategy.REVERSE:
                                     return o2.compareTo(o1);
-                                case PropertyOrderStrategy.ANY:
                                 default:
                                     return 1;
                             }
@@ -766,7 +767,7 @@ public class JsonbAccessMode implements AccessMode, Closeable {
         } else if (order != null) {
             switch (order) {
                 case PropertyOrderStrategy.ANY:
-                    keyComparator = null;
+                    keyComparator = new PerHierarchyAndLexicographicalOrderFieldComparator(clazz);
                     break;
                 case PropertyOrderStrategy.LEXICOGRAPHICAL:
                     keyComparator = String::compareTo;
@@ -774,10 +775,10 @@ public class JsonbAccessMode implements AccessMode, Closeable {
                 case PropertyOrderStrategy.REVERSE:
                     keyComparator = Comparator.reverseOrder();
                     break;
-                default:
+                default: // unlikely
                     keyComparator = null;
             }
-        } else {
+        } else { // unlikely
             keyComparator = null;
         }
         return keyComparator;
diff --git a/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/order/PerHierarchyAndLexicographicalOrderFieldComparator.java b/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/order/PerHierarchyAndLexicographicalOrderFieldComparator.java
new file mode 100644
index 0000000..83f1deb
--- /dev/null
+++ b/johnzon-jsonb/src/main/java/org/apache/johnzon/jsonb/order/PerHierarchyAndLexicographicalOrderFieldComparator.java
@@ -0,0 +1,69 @@
+/*
+ * 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.johnzon.jsonb.order;
+
+import java.util.Comparator;
+
+public class PerHierarchyAndLexicographicalOrderFieldComparator implements Comparator<String> {
+    private final Class<?> clazz;
+
+    public PerHierarchyAndLexicographicalOrderFieldComparator(final Class<?> clazz) {
+        this.clazz = clazz;
+    }
+
+    @Override
+    public int compare(final String o1, final String o2) {
+        final int d1 = distance(o1);
+        final int d2 = distance(o2);
+        final int res = d2 - d1; // reversed!
+        if (res == 0) {
+            return o1.compareTo(o2);
+        }
+        return res;
+    }
+
+    private int distance(final String o1) {
+        Class<?> current = clazz;
+        int i = 0;
+        while (current != null && current != Object.class) {
+            try {
+                current.getDeclaredField(o1);
+                return i;
+            } catch (final NoSuchFieldException e) {
+                // no-op
+            }
+            final String methodSuffix = Character.toUpperCase(o1.charAt(0)) + (o1.length() > 1 ? o1.substring(1) : "");
+            try {
+                current.getDeclaredMethod("get" + methodSuffix);
+                return i;
+            } catch (final Exception e) {
+                // no-op
+            }
+            try {
+                current.getDeclaredMethod("is" + methodSuffix);
+                return i;
+            } catch (final Exception e) {
+                // no-op
+            }
+            i++;
+            current = current.getSuperclass();
+        }
+        return i;
+    }
+}
diff --git a/johnzon-jsonb/src/test/java/org/apache/johnzon/jsonb/DefaultMappingTest.java b/johnzon-jsonb/src/test/java/org/apache/johnzon/jsonb/DefaultMappingTest.java
index e707663..da59137 100644
--- a/johnzon-jsonb/src/test/java/org/apache/johnzon/jsonb/DefaultMappingTest.java
+++ b/johnzon-jsonb/src/test/java/org/apache/johnzon/jsonb/DefaultMappingTest.java
@@ -1064,7 +1064,7 @@ public class DefaultMappingTest {
         attributesOrderingWithInheritance.cc = "cc";
         attributesOrderingWithInheritance.bb = "bb";
 
-        assertEquals("{\"aField\":\"aField\",\"aa\":\"aa\",\"bField\":\"bField\",\"bb\":\"bb\",\"cField\":\"cField\",\"cc\":\"cc\"}",
+        assertEquals("{\"aField\":\"aField\",\"bField\":\"bField\",\"cField\":\"cField\",\"aa\":\"aa\",\"bb\":\"bb\",\"cc\":\"cc\"}",
             JSONB.toJson(attributesOrderingWithInheritance));
 
         // important, see OrderTest#deserializationRespectsOrderToo
diff --git a/johnzon-jsonb/src/test/java/org/apache/johnzon/jsonb/HierarchySerializationTest.java b/johnzon-jsonb/src/test/java/org/apache/johnzon/jsonb/HierarchySerializationTest.java
new file mode 100644
index 0000000..9e960f2
--- /dev/null
+++ b/johnzon-jsonb/src/test/java/org/apache/johnzon/jsonb/HierarchySerializationTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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.johnzon.jsonb;
+
+import static org.junit.Assert.assertEquals;
+
+import org.apache.johnzon.jsonb.test.JsonbRule;
+import org.junit.Rule;
+import org.junit.Test;
+
+public class HierarchySerializationTest {
+    @Rule
+    public final JsonbRule jsonb = new JsonbRule();
+
+    @Test
+    public void parentFieldsAreSerializedBeforeChildOnes() {
+        assertEquals("{\"parent\":\"parent\",\"child\":\"child\"}", jsonb.toJson(new Child()));
+    }
+
+    public static class Parent {
+        public String parent = "parent";
+    }
+
+    public static class Child extends Parent {
+        public String child = "child";
+    }
+}