|
| 1 | +package com.fasterxml.jackson.databind.jsontype.impl; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.BitSet; |
| 5 | +import java.util.Collection; |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.Iterator; |
| 8 | +import java.util.LinkedList; |
| 9 | +import java.util.List; |
| 10 | +import java.util.Map; |
| 11 | + |
| 12 | +import com.fasterxml.jackson.annotation.JsonTypeInfo; |
| 13 | +import com.fasterxml.jackson.core.JsonParser; |
| 14 | +import com.fasterxml.jackson.core.JsonToken; |
| 15 | +import com.fasterxml.jackson.databind.BeanProperty; |
| 16 | +import com.fasterxml.jackson.databind.DeserializationConfig; |
| 17 | +import com.fasterxml.jackson.databind.DeserializationContext; |
| 18 | +import com.fasterxml.jackson.databind.JavaType; |
| 19 | +import com.fasterxml.jackson.databind.MapperFeature; |
| 20 | +import com.fasterxml.jackson.databind.exc.InvalidTypeIdException; |
| 21 | +import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition; |
| 22 | +import com.fasterxml.jackson.databind.jsontype.NamedType; |
| 23 | +import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; |
| 24 | +import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; |
| 25 | +import com.fasterxml.jackson.databind.util.TokenBuffer; |
| 26 | + |
| 27 | +/** |
| 28 | + * A {@link TypeDeserializer} capable of deducing polymorphic types based on the fields available. Deduction |
| 29 | + * is limited to the <i>names</i> of child fields (not their values or, consequently, any nested descendants). |
| 30 | + * Exceptions will be thrown if not enough unique information is present to select a single subtype. |
| 31 | + */ |
| 32 | +public class AsDeductionTypeDeserializer extends AsPropertyTypeDeserializer { |
| 33 | + |
| 34 | + // Fieldname -> bitmap-index of every field discovered, across all subtypes |
| 35 | + private final Map<String, Integer> fieldBitIndex; |
| 36 | + // Bitmap of available fields in each subtype (including its parents) |
| 37 | + private final Map<BitSet, String> subtypeFingerprints; |
| 38 | + |
| 39 | + public AsDeductionTypeDeserializer(JavaType bt, TypeIdResolver idRes, JavaType defaultImpl, DeserializationConfig config, Collection<NamedType> subtypes) { |
| 40 | + super(bt, idRes, null, false, defaultImpl); |
| 41 | + fieldBitIndex = new HashMap<>(); |
| 42 | + subtypeFingerprints = buildFingerprints(config, subtypes); |
| 43 | + } |
| 44 | + |
| 45 | + public AsDeductionTypeDeserializer(AsDeductionTypeDeserializer src, BeanProperty property) { |
| 46 | + super(src, property); |
| 47 | + fieldBitIndex = src.fieldBitIndex; |
| 48 | + subtypeFingerprints = src.subtypeFingerprints; |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public JsonTypeInfo.As getTypeInclusion() { |
| 53 | + return null; |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public TypeDeserializer forProperty(BeanProperty prop) { |
| 58 | + return (prop == _property) ? this : new AsDeductionTypeDeserializer(this, prop); |
| 59 | + } |
| 60 | + |
| 61 | + protected Map<BitSet, String> buildFingerprints(DeserializationConfig config, Collection<NamedType> subtypes) { |
| 62 | + boolean ignoreCase = config.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); |
| 63 | + |
| 64 | + int nextField = 0; |
| 65 | + Map<BitSet, String> fingerprints = new HashMap<>(); |
| 66 | + |
| 67 | + for (NamedType subtype : subtypes) { |
| 68 | + JavaType subtyped = config.getTypeFactory().constructType(subtype.getType()); |
| 69 | + List<BeanPropertyDefinition> properties = config.introspect(subtyped).findProperties(); |
| 70 | + |
| 71 | + BitSet fingerprint = new BitSet(nextField + properties.size()); |
| 72 | + for (BeanPropertyDefinition property : properties) { |
| 73 | + String name = property.getName(); |
| 74 | + if (ignoreCase) name = name.toLowerCase(); |
| 75 | + Integer bitIndex = fieldBitIndex.get(name); |
| 76 | + if (bitIndex == null) { |
| 77 | + bitIndex = nextField; |
| 78 | + fieldBitIndex.put(name, nextField++); |
| 79 | + } |
| 80 | + fingerprint.set(bitIndex); |
| 81 | + } |
| 82 | + |
| 83 | + String existingFingerprint = fingerprints.put(fingerprint, subtype.getType().getName()); |
| 84 | + |
| 85 | + // Validate uniqueness |
| 86 | + if (existingFingerprint != null) { |
| 87 | + throw new IllegalStateException( |
| 88 | + String.format("Subtypes %s and %s have the same signature and cannot be uniquely deduced.", existingFingerprint, subtype.getType().getName()) |
| 89 | + ); |
| 90 | + } |
| 91 | + |
| 92 | + } |
| 93 | + return fingerprints; |
| 94 | + } |
| 95 | + |
| 96 | + @Override |
| 97 | + public Object deserializeTypedFromObject(JsonParser p, DeserializationContext ctxt) throws IOException { |
| 98 | + |
| 99 | + JsonToken t = p.currentToken(); |
| 100 | + if (t == JsonToken.START_OBJECT) { |
| 101 | + t = p.nextToken(); |
| 102 | + } else { |
| 103 | + /* This is most likely due to the fact that not all Java types are |
| 104 | + * serialized as JSON Objects; so if "as-property" inclusion is requested, |
| 105 | + * serialization of things like Lists must be instead handled as if |
| 106 | + * "as-wrapper-array" was requested. |
| 107 | + * But this can also be due to some custom handling: so, if "defaultImpl" |
| 108 | + * is defined, it will be asked to handle this case. |
| 109 | + */ |
| 110 | + return _deserializeTypedUsingDefaultImpl(p, ctxt, null); |
| 111 | + } |
| 112 | + |
| 113 | + List<BitSet> candidates = new LinkedList<>(subtypeFingerprints.keySet()); |
| 114 | + |
| 115 | + // Record processed tokens as we must rewind once after deducing the deserializer to use |
| 116 | + TokenBuffer tb = new TokenBuffer(p, ctxt); |
| 117 | + boolean ignoreCase = ctxt.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); |
| 118 | + |
| 119 | + for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) { |
| 120 | + String name = p.getCurrentName(); |
| 121 | + if (ignoreCase) name = name.toLowerCase(); |
| 122 | + |
| 123 | + tb.copyCurrentStructure(p); |
| 124 | + |
| 125 | + Integer bit = fieldBitIndex.get(name); |
| 126 | + if (bit != null) { |
| 127 | + // field is known by at least one subtype |
| 128 | + prune(candidates, bit); |
| 129 | + if (candidates.size() == 1) { |
| 130 | + return _deserializeTypedForId(p, ctxt, tb, subtypeFingerprints.get(candidates.get(0))); |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + throw new InvalidTypeIdException( |
| 136 | + p, |
| 137 | + String.format("Cannot deduce unique subtype of %s (%d candidates match)", _baseType.toString(), candidates.size()), |
| 138 | + _baseType |
| 139 | + , "DEDUCED" |
| 140 | + ); |
| 141 | + } |
| 142 | + |
| 143 | + // Keep only fingerprints containing this field |
| 144 | + private static void prune(List<BitSet> candidates, int bit) { |
| 145 | + for (Iterator<BitSet> iter = candidates.iterator(); iter.hasNext(); ) { |
| 146 | + if (!iter.next().get(bit)) { |
| 147 | + iter.remove(); |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | +} |
0 commit comments