Search in sources :

Example 21 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class BuilderBasedDeserializer method deserializeWithUnwrapped.

/*
    /**********************************************************
    /* Handling for cases where we have "unwrapped" values
    /**********************************************************
     */
/**
     * Method called when there are declared "unwrapped" properties
     * which need special handling
     */
@SuppressWarnings("resource")
protected Object deserializeWithUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException {
    if (_delegateDeserializer != null) {
        return _valueInstantiator.createUsingDelegate(ctxt, _delegateDeserializer.deserialize(p, ctxt));
    }
    if (_propertyBasedCreator != null) {
        return deserializeUsingPropertyBasedWithUnwrapped(p, ctxt);
    }
    TokenBuffer tokens = new TokenBuffer(p, ctxt);
    tokens.writeStartObject();
    Object bean = _valueInstantiator.createUsingDefault(ctxt);
    if (_injectables != null) {
        injectValues(ctxt, bean);
    }
    final Class<?> activeView = _needViewProcesing ? ctxt.getActiveView() : null;
    for (; p.getCurrentToken() != JsonToken.END_OBJECT; p.nextToken()) {
        String propName = p.getCurrentName();
        p.nextToken();
        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) {
            // normal case
            if (activeView != null && !prop.visibleInView(activeView)) {
                p.skipChildren();
                continue;
            }
            try {
                bean = prop.deserializeSetAndReturn(p, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        // ignorable things should be ignored
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(p, ctxt, bean, propName);
            continue;
        }
        // but... others should be passed to unwrapped property deserializers
        tokens.writeFieldName(propName);
        tokens.copyCurrentStructure(p);
        // how about any setter? We'll get copies but...
        if (_anySetter != null) {
            try {
                _anySetter.deserializeAndSet(p, ctxt, bean, propName);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
    }
    tokens.writeEndObject();
    _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
    return bean;
}
Also used : TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer) IOException(java.io.IOException)

Example 22 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class ExternalTypeHandler method handlePropertyValue.

/**
     * Method called to ask handler to handle value of given property,
     * at point where parser points to the first token of the value.
     * Handling can mean either resolving type id it contains (if it matches type
     * property name), or by buffering the value for further use.
     * 
     * @return True, if the given property was properly handled
     */
@SuppressWarnings("unchecked")
public boolean handlePropertyValue(JsonParser p, DeserializationContext ctxt, String propName, Object bean) throws IOException {
    Object ob = _nameToPropertyIndex.get(propName);
    if (ob == null) {
        return false;
    }
    // 28-Nov-2016, tatu: For [databind#291], need separate handling
    if (ob instanceof List<?>) {
        Iterator<Integer> it = ((List<Integer>) ob).iterator();
        Integer index = it.next();
        ExtTypedProperty prop = _properties[index];
        // for all mappings, so we'll only check first one
        if (prop.hasTypePropertyName(propName)) {
            String typeId = p.getText();
            p.skipChildren();
            _typeIds[index] = typeId;
            while (it.hasNext()) {
                _typeIds[it.next()] = typeId;
            }
        } else {
            @SuppressWarnings("resource") TokenBuffer tokens = new TokenBuffer(p, ctxt);
            tokens.copyCurrentStructure(p);
            _tokens[index] = tokens;
            while (it.hasNext()) {
                _tokens[it.next()] = tokens;
            }
        }
        return true;
    }
    // Otherwise only maps to a single value, in which case we can
    // handle things in bit more optimal way...
    int index = ((Integer) ob).intValue();
    ExtTypedProperty prop = _properties[index];
    boolean canDeserialize;
    if (prop.hasTypePropertyName(propName)) {
        _typeIds[index] = p.getText();
        p.skipChildren();
        canDeserialize = (bean != null) && (_tokens[index] != null);
    } else {
        @SuppressWarnings("resource") TokenBuffer tokens = new TokenBuffer(p, ctxt);
        tokens.copyCurrentStructure(p);
        _tokens[index] = tokens;
        canDeserialize = (bean != null) && (_typeIds[index] != null);
    }
    // we have all pertinent information:
    if (canDeserialize) {
        String typeId = _typeIds[index];
        // clear stored data, to avoid deserializing+setting twice:
        _typeIds[index] = null;
        _deserializeAndSet(p, ctxt, bean, index, typeId);
        _tokens[index] = null;
    }
    return true;
}
Also used : TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer)

Example 23 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class ExternalTypeHandler method complete.

/**
     * Method called after JSON Object closes, and has to ensure that all external
     * type ids have been handled.
     */
@SuppressWarnings("resource")
public Object complete(JsonParser p, DeserializationContext ctxt, Object bean) throws IOException {
    for (int i = 0, len = _properties.length; i < len; ++i) {
        String typeId = _typeIds[i];
        if (typeId == null) {
            TokenBuffer tokens = _tokens[i];
            // but not just one
            if (tokens == null) {
                continue;
            }
            // [databind#118]: Need to mind natural types, for which no type id
            // will be included.
            JsonToken t = tokens.firstToken();
            if (t.isScalarValue()) {
                // can't be null as we never store empty buffers
                JsonParser buffered = tokens.asParser(p);
                buffered.nextToken();
                SettableBeanProperty extProp = _properties[i].getProperty();
                Object result = TypeDeserializer.deserializeIfNatural(buffered, ctxt, extProp.getType());
                if (result != null) {
                    extProp.set(bean, result);
                    continue;
                }
                // 26-Oct-2012, tatu: As per [databind#94], must allow use of 'defaultImpl'
                if (!_properties[i].hasDefaultType()) {
                    ctxt.reportInputMismatch(bean.getClass(), "Missing external type id property '%s'", _properties[i].getTypePropertyName());
                } else {
                    typeId = _properties[i].getDefaultTypeId();
                }
            }
        } else if (_tokens[i] == null) {
            SettableBeanProperty prop = _properties[i].getProperty();
            if (prop.isRequired() || ctxt.isEnabled(DeserializationFeature.FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY)) {
                ctxt.reportInputMismatch(bean.getClass(), "Missing property '%s' for external type id '%s'", prop.getName(), _properties[i].getTypePropertyName());
            }
            return bean;
        }
        _deserializeAndSet(p, ctxt, bean, i, typeId);
    }
    return bean;
}
Also used : SettableBeanProperty(com.fasterxml.jackson.databind.deser.SettableBeanProperty) TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer)

Example 24 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class AsArrayTypeDeserializer method _deserialize.

/*
    /***************************************************************
    /* Internal methods
    /***************************************************************
     */
/**
     * Method that handles type information wrapper, locates actual
     * subtype deserializer to use, and calls it to do actual
     * deserialization.
     */
@SuppressWarnings("resource")
protected Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    // 02-Aug-2013, tatu: May need to use native type ids
    if (p.canReadTypeId()) {
        Object typeId = p.getTypeId();
        if (typeId != null) {
            return _deserializeWithNativeTypeId(p, ctxt, typeId);
        }
    }
    boolean hadStartArray = p.isExpectedStartArrayToken();
    String typeId = _locateTypeId(p, ctxt);
    JsonDeserializer<Object> deser = _findDeserializer(ctxt, typeId);
    // Minor complication: we may need to merge type id in?
    if (_typeIdVisible && //  TODO: but does it need to be injected in external case? Why not?
    !_usesExternalId() && p.getCurrentToken() == JsonToken.START_OBJECT) {
        // but what if there's nowhere to add it in? Error? Or skip? For now, skip.
        TokenBuffer tb = new TokenBuffer(null, false);
        // recreate START_OBJECT
        tb.writeStartObject();
        tb.writeFieldName(_typePropertyName);
        tb.writeString(typeId);
        // 02-Jul-2016, tatu: Depending on for JsonParserSequence is initialized it may
        //   try to access current token; ensure there isn't one
        p.clearCurrentToken();
        p = JsonParserSequence.createFlattened(false, tb.asParser(p), p);
        p.nextToken();
    }
    Object value = deser.deserialize(p, ctxt);
    // And then need the closing END_ARRAY
    if (hadStartArray && p.nextToken() != JsonToken.END_ARRAY) {
        ctxt.reportWrongTokenException(baseType(), JsonToken.END_ARRAY, "expected closing END_ARRAY after type information and deserialized value");
    // 05-May-2016, tatu: Not 100% what to do if exception is stored for
    //     future, and not thrown immediately: should probably skip until END_ARRAY
    // ... but for now, fall through
    }
    return value;
}
Also used : TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer)

Example 25 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class BeanDeserializer method deserializeUsingPropertyBasedWithUnwrapped.

@SuppressWarnings("resource")
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException {
    // 01-Dec-2016, tatu: Note: This IS legal to call, but only when unwrapped
    //    value itself is NOT passed via `CreatorProperty` (which isn't supported).
    //    Ok however to pass via setter or field.
    final PropertyBasedCreator creator = _propertyBasedCreator;
    PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
    TokenBuffer tokens = new TokenBuffer(p, ctxt);
    tokens.writeStartObject();
    JsonToken t = p.getCurrentToken();
    for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
        String propName = p.getCurrentName();
        // to point to value
        p.nextToken();
        // creator property?
        SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
        if (creatorProp != null) {
            // Last creator property to set?
            if (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {
                // to move to following FIELD_NAME/END_OBJECT
                t = p.nextToken();
                Object bean;
                try {
                    bean = creator.build(ctxt, buffer);
                } catch (Exception e) {
                    bean = wrapInstantiationProblem(e, ctxt);
                }
                // [databind#631]: Assign current value, to be accessible by custom serializers
                p.setCurrentValue(bean);
                // if so, need to copy all remaining tokens into buffer
                while (t == JsonToken.FIELD_NAME) {
                    // to skip name
                    p.nextToken();
                    tokens.copyCurrentStructure(p);
                    t = p.nextToken();
                }
                tokens.writeEndObject();
                if (bean.getClass() != _beanType.getRawClass()) {
                    // !!! 08-Jul-2011, tatu: Could probably support; but for now
                    //   it's too complicated, so bail out
                    ctxt.reportInputMismatch(creatorProp, "Can not create polymorphic instances with unwrapped values");
                    return null;
                }
                return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
            }
            continue;
        }
        // Object Id property?
        if (buffer.readIdProperty(propName)) {
            continue;
        }
        // regular property? needs buffering
        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) {
            buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop));
            continue;
        }
        // Things marked as ignorable should not be passed to any setter
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(p, ctxt, handledType(), propName);
            continue;
        }
        // how about any setter? We'll get copies but...
        if (_anySetter == null) {
            // but... others should be passed to unwrapped property deserializers
            tokens.writeFieldName(propName);
            tokens.copyCurrentStructure(p);
        } else {
            // Need to copy to a separate buffer first
            TokenBuffer b2 = TokenBuffer.asCopyOfValue(p);
            tokens.writeFieldName(propName);
            tokens.append(b2);
            try {
                buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(b2.asParserOnFirstToken(), ctxt));
            } catch (Exception e) {
                wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
            }
            continue;
        }
    }
    // We hit END_OBJECT, so:
    Object bean;
    try {
        bean = creator.build(ctxt, buffer);
    } catch (Exception e) {
        wrapInstantiationProblem(e, ctxt);
        // never gets here
        return null;
    }
    return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
}
Also used : TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer) IOException(java.io.IOException)

Aggregations

TokenBuffer (com.fasterxml.jackson.databind.util.TokenBuffer)37 IOException (java.io.IOException)11 JsonParser (com.fasterxml.jackson.core.JsonParser)3 RexLiteral (org.apache.calcite.rex.RexLiteral)3 NlsString (org.apache.calcite.util.NlsString)3 ExtendedJsonOutput (org.apache.drill.exec.vector.complex.fn.ExtendedJsonOutput)3 JsonOutput (org.apache.drill.exec.vector.complex.fn.JsonOutput)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 DataBuffer (org.springframework.core.io.buffer.DataBuffer)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)1 SettableBeanProperty (com.fasterxml.jackson.databind.deser.SettableBeanProperty)1 InvalidFormatException (com.fasterxml.jackson.databind.exc.InvalidFormatException)1 UUID (java.util.UUID)1 Test (org.junit.jupiter.api.Test)1 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)1