|
| 1 | +packagecom.stubbornjava.common; |
| 2 | + |
| 3 | +importjava.util.Collection; |
| 4 | +importjava.util.Collections; |
| 5 | +importjava.util.Comparator; |
| 6 | +importjava.util.LinkedHashMap; |
| 7 | +importjava.util.Map.Entry; |
| 8 | +importjava.util.Objects; |
| 9 | + |
| 10 | +importorg.jooq.lambda.Seq; |
| 11 | + |
| 12 | +importcom.fasterxml.jackson.databind.BeanProperty; |
| 13 | +importcom.fasterxml.jackson.databind.JavaType; |
| 14 | +importcom.fasterxml.jackson.databind.JsonMappingException; |
| 15 | +importcom.fasterxml.jackson.databind.JsonSerializer; |
| 16 | +importcom.fasterxml.jackson.databind.MapperFeature; |
| 17 | +importcom.fasterxml.jackson.databind.ObjectMapper; |
| 18 | +importcom.fasterxml.jackson.databind.SerializationFeature; |
| 19 | +importcom.fasterxml.jackson.databind.SerializerProvider; |
| 20 | +importcom.fasterxml.jackson.databind.module.SimpleModule; |
| 21 | +importcom.fasterxml.jackson.databind.ser.std.StdDelegatingSerializer; |
| 22 | +importcom.fasterxml.jackson.databind.util.Converter; |
| 23 | +importcom.fasterxml.jackson.databind.util.StdConverter; |
| 24 | + |
| 25 | +// {{start:DeterministicObjectMapper}} |
| 26 | +publicclassDeterministicObjectMapper { |
| 27 | + |
| 28 | +privateDeterministicObjectMapper() { } |
| 29 | + |
| 30 | +publicstaticObjectMappercreate(ObjectMapperoriginal,CustomComparatorscustomComparators) { |
| 31 | +ObjectMappermapper =original.copy() |
| 32 | + .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS,true) |
| 33 | + .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true); |
| 34 | + |
| 35 | +/* |
| 36 | + * Get the original instance of the SerializerProvider before we add our custom module. |
| 37 | + * Our Collection Delegating code does not call itself. |
| 38 | + */ |
| 39 | +SerializerProviderserializers =mapper.getSerializerProviderInstance(); |
| 40 | + |
| 41 | +// This module is reponsible for replacing non-deterministic objects |
| 42 | +// with deterministic ones. Example convert Set to a sorted List. |
| 43 | +SimpleModulemodule =newSimpleModule(); |
| 44 | +module.addSerializer(Collection.class, |
| 45 | +newCustomDelegatingSerializerProvider(serializers,newCollectionToSortedListConverter(customComparators)) |
| 46 | + ); |
| 47 | +mapper.registerModule(module); |
| 48 | +returnmapper; |
| 49 | + } |
| 50 | + |
| 51 | +/* |
| 52 | + * We need this class to delegate to the original SerializerProvider |
| 53 | + * before we added our module to it. If we have a Collection -> Collection converter |
| 54 | + * it delegates to itself and infinite loops until the stack overflows. |
| 55 | + */ |
| 56 | +privatestaticclassCustomDelegatingSerializerProviderextendsStdDelegatingSerializer |
| 57 | + { |
| 58 | +privatefinalSerializerProviderserializerProvider; |
| 59 | + |
| 60 | +privateCustomDelegatingSerializerProvider(SerializerProviderserializerProvider, |
| 61 | +Converter<?, ?>converter) |
| 62 | + { |
| 63 | +super(converter); |
| 64 | +this.serializerProvider =serializerProvider; |
| 65 | + } |
| 66 | + |
| 67 | +@Override |
| 68 | +protectedStdDelegatingSerializerwithDelegate(Converter<Object,?>converter, |
| 69 | +JavaTypedelegateType,JsonSerializer<?>delegateSerializer) |
| 70 | + { |
| 71 | +returnnewStdDelegatingSerializer(converter,delegateType,delegateSerializer); |
| 72 | + } |
| 73 | + |
| 74 | +/* |
| 75 | + * If we do not override this method to delegate to the original |
| 76 | + * serializerProvider we get a stack overflow exception because it recursively |
| 77 | + * calls itself. Basically we are hijacking the Collection serializer to first |
| 78 | + * sort the list then delegate it back to the original serializer. |
| 79 | + */ |
| 80 | +@Override |
| 81 | +publicJsonSerializer<?>createContextual(SerializerProviderprovider,BeanPropertyproperty) |
| 82 | +throwsJsonMappingException |
| 83 | + { |
| 84 | +returnsuper.createContextual(serializerProvider,property); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | +privatestaticclassCollectionToSortedListConverterextendsStdConverter<Collection<?>,Collection<?>> |
| 89 | + { |
| 90 | +privatefinalCustomComparatorscustomComparators; |
| 91 | + |
| 92 | +publicCollectionToSortedListConverter(CustomComparatorscustomComparators) { |
| 93 | +this.customComparators =customComparators; |
| 94 | + } |
| 95 | +@Override |
| 96 | +publicCollection<?extendsObject>convert(Collection<?>value) |
| 97 | + { |
| 98 | +if (value ==null ||value.isEmpty()) |
| 99 | + { |
| 100 | +returnCollections.emptyList(); |
| 101 | + } |
| 102 | + |
| 103 | +/** |
| 104 | + * Sort all elements by class first, then by our custom comparator. |
| 105 | + * If the collection is heterogeneous or has anonymous classes its useful |
| 106 | + * to first sort by the class name then by the comparator. We don't care |
| 107 | + * about that actual sort order, just that it is deterministic. |
| 108 | + */ |
| 109 | +Comparator<Object>comparator =Comparator.comparing(x ->x.getClass().getName()) |
| 110 | + .thenComparing(customComparators::compare); |
| 111 | +Collection<?extendsObject>filtered =Seq.seq(value) |
| 112 | + .filter(Objects::nonNull) |
| 113 | + .sorted(comparator) |
| 114 | + .toList(); |
| 115 | +if (filtered.isEmpty()) |
| 116 | + { |
| 117 | +returnCollections.emptyList(); |
| 118 | + } |
| 119 | + |
| 120 | +returnfiltered; |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | +publicstaticclassCustomComparators { |
| 125 | +privatefinalLinkedHashMap<Class<?>,Comparator<?extendsObject>>customComparators; |
| 126 | + |
| 127 | +publicCustomComparators() { |
| 128 | +customComparators =newLinkedHashMap<>(); |
| 129 | + } |
| 130 | + |
| 131 | +public <T>voidaddConverter(Class<T>clazz,Comparator<?>comparator) { |
| 132 | +customComparators.put(clazz,comparator); |
| 133 | + } |
| 134 | + |
| 135 | +@SuppressWarnings({"unchecked","rawtypes" }) |
| 136 | +publicintcompare(Objectfirst,Objectsecond) { |
| 137 | +// If the object is comparable use its comparator |
| 138 | +if (firstinstanceofComparable) { |
| 139 | +return ((Comparable)first).compareTo(second); |
| 140 | + } |
| 141 | + |
| 142 | +// If the object is not comparable try a custom supplied comparator |
| 143 | +for (Entry<Class<?>,Comparator<?>>entry :customComparators.entrySet()) { |
| 144 | +Class<?>clazz =entry.getKey(); |
| 145 | +if (first.getClass().isAssignableFrom(clazz)) { |
| 146 | +Comparator<Object>comparator = (Comparator<Object>)entry.getValue(); |
| 147 | +returncomparator.compare(first,second); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | +// we have no way to order the collection so fail hard |
| 152 | +Stringmessage =String.format("Cannot compare object of type %s without a custom comparator",first.getClass().getName()); |
| 153 | +thrownewUnsupportedOperationException(message); |
| 154 | + } |
| 155 | + } |
| 156 | +} |
| 157 | +// {{end:DeterministicObjectMapper}} |