Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.fasterxml.jackson.databind;
  
  import java.util.*;
  
 
Context for the process of deserialization a single root-level value. Used to allow passing in configuration settings and reusable temporary objects (scrap arrays, containers).

Instance life-cycle is such that an partially configured "blueprint" object is registered with ObjectMapper (and ObjectReader, and when an actual instance is needed for deserialization, a fully configured instance will be created using a method in excented API of sub-class (com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.createInstance(com.fasterxml.jackson.databind.DeserializationConfig,com.fasterxml.jackson.core.JsonParser,com.fasterxml.jackson.databind.InjectableValues)). Each instance is guaranteed to only be used from single-threaded context; instances may be reused iff no configuration has changed.

Defined as abstract class so that implementations must define methods for reconfiguring blueprints and creating instances.

 
 public abstract class DeserializationContext
     implements java.io.Serializable
 {
     private static final long serialVersionUID = -7727373309391091315L;

    
Let's limit length of error messages, for cases where underlying data may be very large -- no point in spamming logs with megs of meaningless data.
 
     private final static int MAX_ERROR_STR_LEN = 500;
 
     /*
     /**********************************************************
     /* Configuration, immutable
     /**********************************************************
      */
    
    
Object that handle details of JsonDeserializer caching.
 
     protected final DeserializerCache _cache;
 
     /*
     /**********************************************************
     /* Configuration, changeable via fluent factories
     /**********************************************************
      */

    
Read-only factory instance; exposed to let owners (ObjectMapper, ObjectReader) access it.
 
     protected final DeserializerFactory _factory;
 
     /*
     /**********************************************************
     /* Configuration that gets set for instances (not blueprints)
     /* (partly denormalized for performance)
     /**********************************************************
      */

    
Generic deserialization processing configuration
 
     protected final DeserializationConfig _config;

    
Bitmap of DeserializationFeatures that are enabled
 
     protected final int _featureFlags;

    
Currently active view, if any.
 
     protected final Class<?> _view;

    
Currently active parser used for deserialization. May be different from the outermost parser when content is buffered.
    protected transient JsonParser _parser;
    
    
Object used for resolving references to injectable values.
    protected final InjectableValues _injectableValues;
    
    /*
    /**********************************************************
    /* Per-operation reusable helper objects (not for blueprints)
    /**********************************************************
     */
    protected transient ArrayBuilders _arrayBuilders;
    protected transient ObjectBuffer _objectBuffer;
    protected transient DateFormat _dateFormat;
    
    /*
    /**********************************************************
    /* Life-cycle
    /**********************************************************
     */
        this(dfnull);
    }
    
            DeserializerCache cache)
    {
        if (df == null) {
            throw new IllegalArgumentException("Can not pass null DeserializerFactory");
        }
         = df;
         = (cache == null) ? new DeserializerCache() : cache;
        
         = 0;
         = null;
         = null;
         = null;
    }
            DeserializerFactory factory)
    {
         = src._cache;
         = factory;
        
         = src._config;
         = src._featureFlags;
         = src._view;
         = src._parser;
         = src._injectableValues;
    }
    
            DeserializationConfig configJsonParser jp,
            InjectableValues injectableValues)
    {
         = src._cache;
         = src._factory;
        
         = config;
         = config.getDeserializationFeatures();
         = config.getActiveView();
         = jp;
         = injectableValues;
    }
    
    /*
    /**********************************************************
    /* Public API, accessors
    /**********************************************************
     */

    
    public DeserializerFactory getFactory() {
        return ;
    }

    
Method for accessing configuration setting object for currently active deserialization.
    public DeserializationConfig getConfig() { return ; }

    
Convenience method for checking whether specified on/off feature is enabled
    public final boolean isEnabled(DeserializationFeature feat) {
        /* 03-Dec-2010, tatu: minor shortcut; since this is called quite often,
         *   let's use a local copy of feature settings:
         */
        return ( & feat.getMask()) != 0;
    }
    public final boolean isEnabled(MapperFeature feat) {
        return .isEnabled(feat);
    }
    
        return .getAnnotationIntrospector();
    }

    
Method for accessing the currently active parser. May be different from the outermost parser when content is buffered.

Use of this method is discouraged: if code has direct access to the active parser, that should be used instead.

    public final JsonParser getParser() { return ; }
    public final Object findInjectableValue(Object valueId,
            BeanProperty forPropertyObject beanInstance)
    {
        if ( == null) {
            throw new IllegalStateException("No 'injectableValues' configured, can not inject value with id ["+valueId+"]");
        }
        return .findInjectableValue(valueIdthisforPropertybeanInstance);
    }

    
Accessor for locating currently active view, if any; returns null if no view has been set.
    public final Class<?> getActiveView() {
        return ;
    }

    
Convenience method, functionally equivalent to:
  getConfig().canOverrideAccessModifiers();
 
    public final boolean canOverrideAccessModifiers() {
        return .canOverrideAccessModifiers();
    }

    
Convenience method for accessing the default Base64 encoding used for decoding base64 encoded binary content. Same as calling:
  getConfig().getBase64Variant();
    public final Base64Variant getBase64Variant() {
        return .getBase64Variant();
    }

    
Convenience method, functionally equivalent to:
  getConfig().getNodeFactory();
 
    public final JsonNodeFactory getNodeFactory() {
        return .getNodeFactory();
    }

    
Convenience method, functionally equivalent to:
  getConfig().getTypeFactory();
 
    public final TypeFactory getTypeFactory() {
        return .getTypeFactory();
    }

    
Method for accessing default Locale to use: convenience method for
   getConfig().getLocale();
    public Locale getLocale() {
        return .getLocale();
    }

    
Method for accessing default TimeZone to use: convenience method for
   getConfig().getTimeZone();
    public TimeZone getTimeZone() {
        return .getTimeZone();
    }
    
    /*
    /**********************************************************
    /* Public API, pass-through to DeserializerCache
    /**********************************************************
     */

    
Method for checking whether we could find a deserializer for given type.
    public boolean hasValueDeserializerFor(JavaType type) {
        return .hasValueDeserializerFor(thistype);
    }
    
    
    
Method for finding a value deserializer, and creating a contextual version if necessary, for value reached via specified property.
    @SuppressWarnings("unchecked")
            BeanProperty propertythrows JsonMappingException
    {
        JsonDeserializer<Objectdeser = .findValueDeserializer(this,
                type);
        if (deser != null) {
            if (deser instanceof ContextualDeserializer) {
                deser = (JsonDeserializer<Object>)((ContextualDeserializerdeser).createContextual(thisproperty);
            }
        }
        return deser;
    }
    
    
Method for finding a deserializer for root-level value.
    @SuppressWarnings("unchecked")
            throws JsonMappingException
    {
        JsonDeserializer<Objectdeser = .findValueDeserializer(this,
                type);
        if (deser == null) { // can this occur?
            return null;
        }
        if (deser instanceof ContextualDeserializer) {
            deser = (JsonDeserializer<Object>)((ContextualDeserializerdeser).createContextual(thisnull);
        }
        TypeDeserializer typeDeser = .findTypeDeserializer(type);
        if (typeDeser != null) {
            // important: contextualize to indicate this is for root value
            typeDeser = typeDeser.forProperty(null);
            return new TypeWrappedDeserializer(typeDeserdeser);
        }
        return deser;
    }

    
Convenience method, functionally same as:
  getDeserializerProvider().findKeyDeserializer(getConfig(), propertyType, property);
    public final KeyDeserializer findKeyDeserializer(JavaType keyType,
            BeanProperty propertythrows JsonMappingException {
        KeyDeserializer kd = .findKeyDeserializer(this,
                keyType);
        // Second: contextualize?
        if (kd instanceof ContextualKeyDeserializer) {
            kd = ((ContextualKeyDeserializerkd).createContextual(thisproperty);
        }
        return kd;
    }
    
    /*
    /**********************************************************
    /* Public API, ObjectId handling
    /**********************************************************
     */

    
Method called to find and return entry corresponding to given Object Id: will add an entry if necessary, and never returns null
    public abstract ReadableObjectId findObjectId(Object id,
            ObjectIdGenerator<?> generator);
    /*
    /**********************************************************
    /* Public API, type handling
    /**********************************************************
     */
    
    
Convenience method, functionally equivalent to:
  getConfig().constructType(cls);
 
    public final JavaType constructType(Class<?> cls) {
        return .constructType(cls);
    }

    
Helper method to use for locating Class for given name. Should be used instead of basic Class.forName(className); as it can try using contextual class loader, or use platform-specific workarounds (like on Android, GAE).
    public Class<?> findClass(String classNamethrows ClassNotFoundException
    {
        // By default, delegate to ClassUtil: can be overridden with custom handling
        return ClassUtil.findClass(className);
    }
    
    /*
    /**********************************************************
    /* Extended API: handler instantiation
    /**********************************************************
     */
    public abstract JsonDeserializer<ObjectdeserializerInstance(Annotated annotated,
            Object deserDef)
        throws JsonMappingException;
    public abstract KeyDeserializer keyDeserializerInstance(Annotated annotated,
            Object deserDef)
        throws JsonMappingException;
    public abstract ObjectIdGenerator<?> objectIdGeneratorInstance(Annotated annotated,
            ObjectIdInfo objectIdInfo)
        throws JsonMappingException;
    
    /*
    /**********************************************************
    /* Public API, helper object recycling
    /**********************************************************
     */

    
Method that can be used to get access to a reusable ObjectBuffer, useful for efficiently constructing Object arrays and Lists. Note that leased buffers should be returned once deserializer is done, to allow for reuse during same round of deserialization.
    public final ObjectBuffer leaseObjectBuffer()
    {
        ObjectBuffer buf = ;
        if (buf == null) {
            buf = new ObjectBuffer();
        } else {
             = null;
        }
        return buf;
    }

    
Method to call to return object buffer previously leased with leaseObjectBuffer().

Parameters:
buf Returned object buffer
    public final void returnObjectBuffer(ObjectBuffer buf)
    {
        /* Already have a reusable buffer? Let's retain bigger one
         * (or if equal, favor newer one, shorter life-cycle)
         */
        if ( == null
            || buf.initialCapacity() >= .initialCapacity()) {
             = buf;
        }
    }

    
Method for accessing object useful for building arrays of primitive types (such as int[]).
    public final ArrayBuilders getArrayBuilders()
    {
        if ( == null) {
             = new ArrayBuilders();
        }
        return ;
    }
    /*
    /**********************************************************
    /* Parsing methods that may use reusable/-cyclable objects
    /**********************************************************
     */

    
Convenience method for parsing a Date from given String, using currently configured date format (accessed using com.fasterxml.jackson.databind.cfg.MapperConfig.getDateFormat()).

Implementation will handle thread-safety issues related to date formats such that first time this method is called, date format is cloned, and cloned instance will be retained for use during this deserialization round.

    public Date parseDate(String dateStr)
        throws IllegalArgumentException
    {
        try {
            return getDateFormat().parse(dateStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Failed to parse Date value '"+dateStr+"': "+e.getMessage());
        }
    }

    
Convenience method for constructing Calendar instance set to specified time, to be modified and used by caller.
    public Calendar constructCalendar(Date d)
    {
        /* 08-Jan-2008, tatu: not optimal, but should work for the
         *   most part; let's revise as needed.
         */
        Calendar c = Calendar.getInstance(getTimeZone());
        c.setTime(d);
        return c;
    }
    /*
    /**********************************************************
    /* Methods for problem handling, reporting
    /**********************************************************
     */

    
Method deserializers can call to inform configured DeserializationProblemHandlers of an unrecognized property.

Returns:
True if there was a configured problem handler that was able to handle the problem

    
Method deserializers can call to inform configured com.fasterxml.jackson.databind.deser.DeserializationProblemHandlers of an unrecognized property.
    public boolean handleUnknownProperty(JsonParser jpJsonDeserializer<?> deser,
            Object instanceOrClassString propName)
        throws IOExceptionJsonProcessingException
    {
        if (h != null) {
            while (h != null) {
                // Can bail out if it's handled
                if (h.value().handleUnknownProperty(thisjpdeserinstanceOrClasspropName)) {
                    return true;
                }
                h = h.next();
            }
        }
        return false;
    }

    
Helper method for reporting a problem with unhandled unknown exception

Parameters:
instanceOrClass Either value being populated (if one has been instantiated), or Class that indicates type that would be (or have been) instantiated
deser Deserializer that had the problem, if called by deserializer (or on behalf of one)
    public void reportUnknownProperty(Object instanceOrClassString fieldName,
            JsonDeserializer<?> deser)
        throws JsonMappingException
    {
            return;
        }
        // Do we know properties that are expected instead?
        Collection<ObjectpropIds = (deser == null) ? null : deser.getKnownPropertyNames();
        throw UnrecognizedPropertyException.from(,
                instanceOrClassfieldNamepropIds);
    }
    
    /*
    /**********************************************************
    /* Methods for constructing exceptions
    /**********************************************************
     */
    
    
Helper method for constructing generic mapping exception for specified type
    public JsonMappingException mappingException(Class<?> targetClass) {
        return mappingException(targetClass.getCurrentToken());
    }
    public JsonMappingException mappingException(Class<?> targetClassJsonToken token)
    {
        String clsName = _calcName(targetClass);
        return JsonMappingException.from(,
                "Can not deserialize instance of "+clsName+" out of "+token+" token");
    }
    
    
Helper method for constructing generic mapping exception with specified message and current location information
    public JsonMappingException mappingException(String message) {
        return JsonMappingException.from(getParser(), message);
    }
    
    
Helper method for constructing instantiation exception for specified type, to indicate problem with physically constructing instance of specified class (missing constructor, exception from constructor)
    public JsonMappingException instantiationException(Class<?> instClassThrowable t)
    {
        return JsonMappingException.from(,
                "Can not construct instance of "+instClass.getName()+", problem: "+t.getMessage(),
                t);
    }
    public JsonMappingException instantiationException(Class<?> instClassString msg) {
        return JsonMappingException.from("Can not construct instance of "+instClass.getName()+", problem: "+msg);
    }
    
    
Method that will construct an exception suitable for throwing when some String values are acceptable, but the one encountered is not.

Deprecated:
Since 2.1 should use variant that takes value
    @Deprecated
    public JsonMappingException weirdStringException(Class<?> instClassString msg) {
        return weirdStringException(nullinstClassmsg);
    }

    
Method that will construct an exception suitable for throwing when some String values are acceptable, but the one encountered is not.

Parameters:
value String value from input being deserialized
instClass Type that String should be deserialized into
msg Message that describes specific problem
Since:
2.1
    public JsonMappingException weirdStringException(String valueClass<?> instClassString msg) {
        return InvalidFormatException.from(,
                "Can not construct instance of "+instClass.getName()+" from String value '"+_valueDesc()+"': "+msg,
                valueinstClass);
    }

    
Helper method for constructing exception to indicate that input JSON Number was not suitable for deserializing into given type.
    @Deprecated
    public JsonMappingException weirdNumberException(Class<?> instClassString msg) {
        return weirdStringException(nullinstClassmsg);
    }

    
Helper method for constructing exception to indicate that input JSON Number was not suitable for deserializing into given target type.
    public JsonMappingException weirdNumberException(Number valueClass<?> instClassString msg) {
        return InvalidFormatException.from(,
                "Can not construct instance of "+instClass.getName()+" from number value ("+_valueDesc()+"): "+msg,
                nullinstClass);
    }
    
    
Helper method for constructing exception to indicate that given JSON Object field name was not in format to be able to deserialize specified key type.
    public JsonMappingException weirdKeyException(Class<?> keyClassString keyValueString msg)
    {
        return InvalidFormatException.from(,
                "Can not construct Map key of type "+keyClass.getName()+" from String \""+_desc(keyValue)+"\": "+msg,
                keyValuekeyClass);
    }

    
Helper method for indicating that the current token was expected to be another token.
    public JsonMappingException wrongTokenException(JsonParser jpJsonToken expTokenString msg)
    {
        return JsonMappingException.from(jp"Unexpected token ("+jp.getCurrentToken()+"), expected "+expToken+": "+msg);
    }

    
Helper method for constructing exception to indicate that given type id (parsed from JSON) could not be converted to a Java type.
    {
        return JsonMappingException.from("Could not resolve type id '"+id+"' into a subtype of "+type);
    }
    public JsonMappingException endOfInputException(Class<?> instClass)
    {
        return JsonMappingException.from("Unexpected end-of-input when trying to deserialize a "
                +instClass.getName());
    }
    
    /*
    /**********************************************************
    /* Overridable internal methods
    /**********************************************************
     */
    protected DateFormat getDateFormat()
    {
        if ( != null) {
            return ;
        }
        /* 24-Feb-2012, tatu: At this point, all timezone configuration
         *    should have occured, with respect to default dateformat
         *    and timezone configuration. But we still better clone
         *    an instance as formatters may be stateful.
         */
        DateFormat df = .getDateFormat();
         = df = (DateFormatdf.clone();
        return df;
    }
    protected String determineClassName(Object instance)
    {
        return ClassUtil.getClassDescription(instance);
    }
    
    /*
    /**********************************************************
    /* Other internal methods
    /**********************************************************
     */
    protected String _calcName(Class<?> cls)
    {
        if (cls.isArray()) {
            return _calcName(cls.getComponentType())+"[]";
        }
        return cls.getName();
    }
    
    protected String _valueDesc()
    {
        try {
            return _desc(.getText());
        } catch (Exception e) {
            return "[N/A]";
        }
    }
    protected String _desc(String desc)
    {
        // !!! should we quote it? (in case there are control chars, linefeeds)
        if (desc.length() > ) {
            desc = desc.substring(0, ) + "]...[" + desc.substring(desc.length() - );
        }
        return desc;
    }
New to GrepCode? Check out our FAQ X