• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package com.fasterxml.jackson.databind;
2 
3 import java.io.*;
4 import java.net.URL;
5 import java.util.*;
6 import java.util.concurrent.ConcurrentHashMap;
7 
8 import com.fasterxml.jackson.core.*;
9 import com.fasterxml.jackson.core.filter.FilteringParserDelegate;
10 import com.fasterxml.jackson.core.filter.JsonPointerBasedFilter;
11 import com.fasterxml.jackson.core.filter.TokenFilter;
12 import com.fasterxml.jackson.core.type.ResolvedType;
13 import com.fasterxml.jackson.core.type.TypeReference;
14 
15 import com.fasterxml.jackson.databind.cfg.ContextAttributes;
16 import com.fasterxml.jackson.databind.deser.DataFormatReaders;
17 import com.fasterxml.jackson.databind.deser.DefaultDeserializationContext;
18 import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
19 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
20 import com.fasterxml.jackson.databind.node.TreeTraversingParser;
21 import com.fasterxml.jackson.databind.type.TypeFactory;
22 import com.fasterxml.jackson.databind.util.ClassUtil;
23 
24 /**
25  * Builder object that can be used for per-serialization configuration of
26  * deserialization parameters, such as root type to use or object
27  * to update (instead of constructing new instance).
28  *<p>
29  * Uses "mutant factory" pattern so that instances are immutable
30  * (and thus fully thread-safe with no external synchronization);
31  * new instances are constructed for different configurations.
32  * Instances are initially constructed by {@link ObjectMapper} and can be
33  * reused, shared, cached; both because of thread-safety and because
34  * instances are relatively light-weight.
35  *<p>
36  * NOTE: this class is NOT meant as sub-classable (with Jackson 2.8 and
37  * above) by users. It is left as non-final mostly to allow frameworks
38  * that require bytecode generation for proxying and similar use cases,
39  * but there is no expecation that functionality should be extended
40  * by sub-classing.
41  */
42 public class ObjectReader
43     extends ObjectCodec
44     implements Versioned, java.io.Serializable // since 2.1
45 {
46     private static final long serialVersionUID = 2L; // since 2.9
47 
48     /*
49     /**********************************************************
50     /* Immutable configuration from ObjectMapper
51     /**********************************************************
52      */
53 
54     /**
55      * General serialization configuration settings; while immutable,
56      * can use copy-constructor to create modified instances as necessary.
57      */
58     protected final DeserializationConfig _config;
59 
60     /**
61      * Blueprint instance of deserialization context; used for creating
62      * actual instance when needed.
63      */
64     protected final DefaultDeserializationContext _context;
65 
66     /**
67      * Factory used for constructing {@link JsonGenerator}s
68      */
69     protected final JsonFactory _parserFactory;
70 
71     /**
72      * Flag that indicates whether root values are expected to be unwrapped or not
73      */
74     protected final boolean _unwrapRoot;
75 
76     /**
77      * Filter to be consider for JsonParser.
78      * Default value to be null as filter not considered.
79      */
80     private final TokenFilter _filter;
81 
82     /*
83     /**********************************************************
84     /* Configuration that can be changed during building
85     /**********************************************************
86      */
87 
88     /**
89      * Declared type of value to instantiate during deserialization.
90      * Defines which deserializer to use; as well as base type of instance
91      * to construct if an updatable value is not configured to be used
92      * (subject to changes by embedded type information, for polymorphic
93      * types). If {@link #_valueToUpdate} is non-null, only used for
94      * locating deserializer.
95      */
96     protected final JavaType _valueType;
97 
98     /**
99      * We may pre-fetch deserializer as soon as {@link #_valueType}
100      * is known, and if so, reuse it afterwards.
101      * This allows avoiding further deserializer lookups and increases
102      * performance a bit on cases where readers are reused.
103      *
104      * @since 2.1
105      */
106     protected final JsonDeserializer<Object> _rootDeserializer;
107 
108     /**
109      * Instance to update with data binding; if any. If null,
110      * a new instance is created, if non-null, properties of
111      * this value object will be updated instead.
112      * Note that value can be of almost any type, except not
113      * {@link com.fasterxml.jackson.databind.type.ArrayType}; array
114      * types cannot be modified because array size is immutable.
115      */
116     protected final Object _valueToUpdate;
117 
118     /**
119      * When using data format that uses a schema, schema is passed
120      * to parser.
121      */
122     protected final FormatSchema _schema;
123 
124     /**
125      * Values that can be injected during deserialization, if any.
126      */
127     protected final InjectableValues _injectableValues;
128 
129     /**
130      * Optional detector used for auto-detecting data format that byte-based
131      * input uses.
132      *<p>
133      * NOTE: If defined non-null, <code>readValue()</code> methods that take
134      * {@link Reader} or {@link String} input <b>will fail with exception</b>,
135      * because format-detection only works on byte-sources. Also, if format
136      * cannot be detect reliably (as per detector settings),
137      * a {@link JsonParseException} will be thrown).
138      *
139      * @since 2.1
140      */
141     protected final DataFormatReaders _dataFormatReaders;
142 
143     /*
144     /**********************************************************
145     /* Caching
146     /**********************************************************
147      */
148 
149     /**
150      * Root-level cached deserializers.
151      * Passed by {@link ObjectMapper}, shared with it.
152      */
153     final protected ConcurrentHashMap<JavaType, JsonDeserializer<Object>> _rootDeserializers;
154 
155     /**
156      * Lazily resolved {@link JavaType} for {@link JsonNode}
157      */
158     protected transient JavaType _jsonNodeType;
159 
160     /*
161     /**********************************************************
162     /* Life-cycle, construction
163     /**********************************************************
164      */
165 
166     /**
167      * Constructor used by {@link ObjectMapper} for initial instantiation
168      */
ObjectReader(ObjectMapper mapper, DeserializationConfig config)169     protected ObjectReader(ObjectMapper mapper, DeserializationConfig config) {
170         this(mapper, config, null, null, null, null);
171     }
172 
173     /**
174      * Constructor called when a root deserializer should be fetched based
175      * on other configuration.
176      */
ObjectReader(ObjectMapper mapper, DeserializationConfig config, JavaType valueType, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues)177     protected ObjectReader(ObjectMapper mapper, DeserializationConfig config,
178             JavaType valueType, Object valueToUpdate,
179             FormatSchema schema, InjectableValues injectableValues)
180     {
181         _config = config;
182         _context = mapper._deserializationContext;
183         _rootDeserializers = mapper._rootDeserializers;
184         _parserFactory = mapper._jsonFactory;
185         _valueType = valueType;
186         _valueToUpdate = valueToUpdate;
187         _schema = schema;
188         _injectableValues = injectableValues;
189         _unwrapRoot = config.useRootWrapping();
190 
191         _rootDeserializer = _prefetchRootDeserializer(valueType);
192         _dataFormatReaders = null;
193         _filter = null;
194     }
195 
196     /**
197      * Copy constructor used for building variations.
198      */
ObjectReader(ObjectReader base, DeserializationConfig config, JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues, DataFormatReaders dataFormatReaders)199     protected ObjectReader(ObjectReader base, DeserializationConfig config,
200             JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate,
201             FormatSchema schema, InjectableValues injectableValues,
202             DataFormatReaders dataFormatReaders)
203     {
204         _config = config;
205         _context = base._context;
206 
207         _rootDeserializers = base._rootDeserializers;
208         _parserFactory = base._parserFactory;
209 
210         _valueType = valueType;
211         _rootDeserializer = rootDeser;
212         _valueToUpdate = valueToUpdate;
213         _schema = schema;
214         _injectableValues = injectableValues;
215         _unwrapRoot = config.useRootWrapping();
216         _dataFormatReaders = dataFormatReaders;
217         _filter = base._filter;
218     }
219 
220     /**
221      * Copy constructor used when modifying simple feature flags
222      */
ObjectReader(ObjectReader base, DeserializationConfig config)223     protected ObjectReader(ObjectReader base, DeserializationConfig config)
224     {
225         _config = config;
226         _context = base._context;
227 
228         _rootDeserializers = base._rootDeserializers;
229         _parserFactory = base._parserFactory;
230 
231         _valueType = base._valueType;
232         _rootDeserializer = base._rootDeserializer;
233         _valueToUpdate = base._valueToUpdate;
234         _schema = base._schema;
235         _injectableValues = base._injectableValues;
236         _unwrapRoot = config.useRootWrapping();
237         _dataFormatReaders = base._dataFormatReaders;
238         _filter = base._filter;
239     }
240 
ObjectReader(ObjectReader base, JsonFactory f)241     protected ObjectReader(ObjectReader base, JsonFactory f)
242     {
243         // may need to override ordering, based on data format capabilities
244         _config = base._config
245             .with(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, f.requiresPropertyOrdering());
246         _context = base._context;
247 
248         _rootDeserializers = base._rootDeserializers;
249         _parserFactory = f;
250 
251         _valueType = base._valueType;
252         _rootDeserializer = base._rootDeserializer;
253         _valueToUpdate = base._valueToUpdate;
254         _schema = base._schema;
255         _injectableValues = base._injectableValues;
256         _unwrapRoot = base._unwrapRoot;
257         _dataFormatReaders = base._dataFormatReaders;
258         _filter = base._filter;
259     }
260 
ObjectReader(ObjectReader base, TokenFilter filter)261     protected ObjectReader(ObjectReader base, TokenFilter filter) {
262         _config = base._config;
263         _context = base._context;
264         _rootDeserializers = base._rootDeserializers;
265         _parserFactory = base._parserFactory;
266         _valueType = base._valueType;
267         _rootDeserializer = base._rootDeserializer;
268         _valueToUpdate = base._valueToUpdate;
269         _schema = base._schema;
270         _injectableValues = base._injectableValues;
271         _unwrapRoot = base._unwrapRoot;
272         _dataFormatReaders = base._dataFormatReaders;
273         _filter = filter;
274     }
275 
276     /**
277      * Method that will return version information stored in and read from jar
278      * that contains this class.
279      */
280     @Override
version()281     public Version version() {
282         return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
283     }
284 
285     /*
286     /**********************************************************
287     /* Helper methods used internally for invoking constructors
288     /* Need to be overridden if sub-classing (not recommended)
289     /* is used.
290     /**********************************************************
291      */
292 
293     /**
294      * Overridable factory method called by various "withXxx()" methods
295      *
296      * @since 2.5
297      */
_new(ObjectReader base, JsonFactory f)298     protected ObjectReader _new(ObjectReader base, JsonFactory f) {
299         return new ObjectReader(base, f);
300     }
301 
302     /**
303      * Overridable factory method called by various "withXxx()" methods
304      *
305      * @since 2.5
306      */
_new(ObjectReader base, DeserializationConfig config)307     protected ObjectReader _new(ObjectReader base, DeserializationConfig config) {
308         return new ObjectReader(base, config);
309     }
310 
311     /**
312      * Overridable factory method called by various "withXxx()" methods
313      *
314      * @since 2.5
315      */
_new(ObjectReader base, DeserializationConfig config, JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues, DataFormatReaders dataFormatReaders)316     protected ObjectReader _new(ObjectReader base, DeserializationConfig config,
317             JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate,
318             FormatSchema schema, InjectableValues injectableValues,
319             DataFormatReaders dataFormatReaders) {
320         return new ObjectReader(base, config, valueType, rootDeser,  valueToUpdate,
321                  schema,  injectableValues, dataFormatReaders);
322     }
323 
324     /**
325      * Factory method used to create {@link MappingIterator} instances;
326      * either default, or custom subtype.
327      *
328      * @since 2.5
329      */
_newIterator(JsonParser p, DeserializationContext ctxt, JsonDeserializer<?> deser, boolean parserManaged)330     protected <T> MappingIterator<T> _newIterator(JsonParser p, DeserializationContext ctxt,
331             JsonDeserializer<?> deser, boolean parserManaged)
332     {
333         return new MappingIterator<T>(_valueType, p, ctxt,
334                 deser, parserManaged, _valueToUpdate);
335     }
336 
337     /*
338     /**********************************************************
339     /* Methods for initializing parser instance to use
340     /**********************************************************
341      */
342 
_initForReading(DeserializationContext ctxt, JsonParser p)343     protected JsonToken _initForReading(DeserializationContext ctxt, JsonParser p)
344         throws IOException
345     {
346         _config.initialize(p, _schema);
347 
348         /* First: must point to a token; if not pointing to one, advance.
349          * This occurs before first read from JsonParser, as well as
350          * after clearing of current token.
351          */
352         JsonToken t = p.currentToken();
353         if (t == null) { // and then we must get something...
354             t = p.nextToken();
355             if (t == null) {
356                 // Throw mapping exception, since it's failure to map, not an actual parsing problem
357                 ctxt.reportInputMismatch(_valueType,
358                         "No content to map due to end-of-input");
359             }
360         }
361         return t;
362     }
363 
364     /**
365      * Alternative to {@link #_initForReading} used in cases where reading
366      * of multiple values means that we may or may not want to advance the stream,
367      * but need to do other initialization.
368      *<p>
369      * Base implementation only sets configured {@link FormatSchema}, if any, on parser.
370      *
371      * @since 2.8
372      */
_initForMultiRead(DeserializationContext ctxt, JsonParser p)373     protected void _initForMultiRead(DeserializationContext ctxt, JsonParser p)
374         throws IOException
375     {
376         _config.initialize(p, _schema);
377     }
378 
379     /*
380     /**********************************************************
381     /* Life-cycle, fluent factory methods for DeserializationFeatures
382     /**********************************************************
383      */
384 
385     /**
386      * Method for constructing a new reader instance that is configured
387      * with specified feature enabled.
388      */
with(DeserializationFeature feature)389     public ObjectReader with(DeserializationFeature feature) {
390         return _with(_config.with(feature));
391     }
392 
393     /**
394      * Method for constructing a new reader instance that is configured
395      * with specified features enabled.
396      */
with(DeserializationFeature first, DeserializationFeature... other)397     public ObjectReader with(DeserializationFeature first,
398             DeserializationFeature... other)
399     {
400         return _with(_config.with(first, other));
401     }
402 
403     /**
404      * Method for constructing a new reader instance that is configured
405      * with specified features enabled.
406      */
withFeatures(DeserializationFeature... features)407     public ObjectReader withFeatures(DeserializationFeature... features) {
408         return _with(_config.withFeatures(features));
409     }
410 
411     /**
412      * Method for constructing a new reader instance that is configured
413      * with specified feature disabled.
414      */
without(DeserializationFeature feature)415     public ObjectReader without(DeserializationFeature feature) {
416         return _with(_config.without(feature));
417     }
418 
419     /**
420      * Method for constructing a new reader instance that is configured
421      * with specified features disabled.
422      */
without(DeserializationFeature first, DeserializationFeature... other)423     public ObjectReader without(DeserializationFeature first,
424             DeserializationFeature... other) {
425         return _with(_config.without(first, other));
426     }
427 
428     /**
429      * Method for constructing a new reader instance that is configured
430      * with specified features disabled.
431      */
withoutFeatures(DeserializationFeature... features)432     public ObjectReader withoutFeatures(DeserializationFeature... features) {
433         return _with(_config.withoutFeatures(features));
434     }
435 
436     /*
437     /**********************************************************
438     /* Life-cycle, fluent factory methods for JsonParser.Features
439     /* (to be deprecated in 2.12?)
440     /**********************************************************
441      */
442 
443     /**
444      * Method for constructing a new reader instance that is configured
445      * with specified feature enabled.
446      *
447      * @param feature Feature to enable
448      *
449      * @return Reader instance with specified feature enabled
450      */
with(JsonParser.Feature feature)451     public ObjectReader with(JsonParser.Feature feature) {
452         return _with(_config.with(feature));
453     }
454 
455     /**
456      * Method for constructing a new reader instance that is configured
457      * with specified features enabled.
458      *
459      * @param features Features to enable
460      *
461      * @return Reader instance with specified features enabled
462      */
withFeatures(JsonParser.Feature... features)463     public ObjectReader withFeatures(JsonParser.Feature... features) {
464         return _with(_config.withFeatures(features));
465     }
466 
467     /**
468      * Method for constructing a new reader instance that is configured
469      * with specified feature disabled.
470      *
471      * @param feature Feature to disable
472      *
473      * @return Reader instance with specified feature disabled
474      */
without(JsonParser.Feature feature)475     public ObjectReader without(JsonParser.Feature feature) {
476         return _with(_config.without(feature));
477     }
478 
479     /**
480      * Method for constructing a new reader instance that is configured
481      * with specified features disabled.
482      *
483      * @param features Features to disable
484      *
485      * @return Reader instance with specified features disabled
486      */
withoutFeatures(JsonParser.Feature... features)487     public ObjectReader withoutFeatures(JsonParser.Feature... features) {
488         return _with(_config.withoutFeatures(features));
489     }
490 
491     /*
492     /**********************************************************************
493     /* Life-cycle, fluent factory methods for StreamReadFeatures (added in 2.11)
494     /**********************************************************************
495      */
496 
497     /**
498      * Method for constructing a new reader instance that is configured
499      * with specified feature enabled.
500      *
501      * @return Reader instance with specified feature enabled
502      *
503      * @since 2.11
504      */
with(StreamReadFeature feature)505     public ObjectReader with(StreamReadFeature feature) {
506         return _with(_config.with(feature.mappedFeature()));
507     }
508 
509     /**
510      * Method for constructing a new reader instance that is configured
511      * with specified feature disabled.
512      *
513      * @return Reader instance with specified feature enabled
514      *
515      * @since 2.11
516      */
without(StreamReadFeature feature)517     public ObjectReader without(StreamReadFeature feature) {
518         return _with(_config.without(feature.mappedFeature()));
519     }
520 
521     /*
522     /**********************************************************
523     /* Life-cycle, fluent factory methods for FormatFeature (2.7)
524     /**********************************************************
525      */
526 
527     /**
528      * Method for constructing a new reader instance that is configured
529      * with specified feature enabled.
530      *
531      * @since 2.7
532      */
with(FormatFeature feature)533     public ObjectReader with(FormatFeature feature) {
534         return _with(_config.with(feature));
535     }
536 
537     /**
538      * Method for constructing a new reader instance that is configured
539      * with specified features enabled.
540      *
541      * @since 2.7
542      */
withFeatures(FormatFeature... features)543     public ObjectReader withFeatures(FormatFeature... features) {
544         return _with(_config.withFeatures(features));
545     }
546 
547     /**
548      * Method for constructing a new reader instance that is configured
549      * with specified feature disabled.
550      *
551      * @since 2.7
552      */
without(FormatFeature feature)553     public ObjectReader without(FormatFeature feature) {
554         return _with(_config.without(feature));
555     }
556 
557     /**
558      * Method for constructing a new reader instance that is configured
559      * with specified features disabled.
560      *
561      * @since 2.7
562      */
withoutFeatures(FormatFeature... features)563     public ObjectReader withoutFeatures(FormatFeature... features) {
564         return _with(_config.withoutFeatures(features));
565     }
566 
567     /*
568     /**********************************************************
569     /* Life-cycle, fluent factory methods, other
570     /**********************************************************
571      */
572 
573     /**
574      * Convenience method to bind from {@link JsonPointer}.
575      * {@link JsonPointerBasedFilter} is registered and will be used for parsing later.
576      * @since 2.6
577      */
at(final String pointerExpr)578     public ObjectReader at(final String pointerExpr) {
579         _assertNotNull("pointerExpr", pointerExpr);
580         return new ObjectReader(this, new JsonPointerBasedFilter(pointerExpr));
581     }
582 
583     /**
584      * Convenience method to bind from {@link JsonPointer}
585       * {@link JsonPointerBasedFilter} is registered and will be used for parsing later.
586      * @since 2.6
587      */
at(final JsonPointer pointer)588     public ObjectReader at(final JsonPointer pointer) {
589         _assertNotNull("pointer", pointer);
590         return new ObjectReader(this, new JsonPointerBasedFilter(pointer));
591     }
592 
593     /**
594      * Mutant factory method that will construct a new instance that has
595      * specified underlying {@link DeserializationConfig}.
596      *<p>
597      * NOTE: use of this method is not recommended, as there are many other
598      * re-configuration methods available.
599      */
with(DeserializationConfig config)600     public ObjectReader with(DeserializationConfig config) {
601         return _with(config);
602     }
603 
604     /**
605      * Method for constructing a new instance with configuration that uses
606      * passed {@link InjectableValues} to provide injectable values.
607      *<p>
608      * Note that the method does NOT change state of this reader, but
609      * rather construct and returns a newly configured instance.
610      */
with(InjectableValues injectableValues)611     public ObjectReader with(InjectableValues injectableValues)
612     {
613         if (_injectableValues == injectableValues) {
614             return this;
615         }
616         return _new(this, _config,
617                 _valueType, _rootDeserializer, _valueToUpdate,
618                 _schema, injectableValues, _dataFormatReaders);
619     }
620 
621     /**
622      * Method for constructing a new reader instance with configuration that uses
623      * passed {@link JsonNodeFactory} for constructing {@link JsonNode}
624      * instances.
625      *<p>
626      * Note that the method does NOT change state of this reader, but
627      * rather construct and returns a newly configured instance.
628      */
with(JsonNodeFactory f)629     public ObjectReader with(JsonNodeFactory f) {
630         return _with(_config.with(f));
631     }
632 
633     /**
634      * Method for constructing a new reader instance with configuration that uses
635      * passed {@link JsonFactory} for constructing underlying Readers.
636      *<p>
637      * NOTE: only factories that <b>DO NOT REQUIRE SPECIAL MAPPERS</b>
638      * (that is, ones that return <code>false</code> for
639      * {@link JsonFactory#requiresCustomCodec()}) can be used: trying
640      * to use one that requires custom codec will throw exception
641      *
642      * @since 2.1
643      */
with(JsonFactory f)644     public ObjectReader with(JsonFactory f) {
645         if (f == _parserFactory) {
646             return this;
647         }
648         ObjectReader r = _new(this, f);
649         // Also, try re-linking, if possible...
650         if (f.getCodec() == null) {
651             f.setCodec(r);
652         }
653         return r;
654     }
655 
656     /**
657      * Method for constructing a new instance with configuration that
658      * specifies what root name to expect for "root name unwrapping".
659      * See {@link DeserializationConfig#withRootName(String)} for
660      * details.
661      *<p>
662      * Note that the method does NOT change state of this reader, but
663      * rather construct and returns a newly configured instance.
664      */
withRootName(String rootName)665     public ObjectReader withRootName(String rootName) {
666         return _with(_config.withRootName(rootName));
667     }
668 
669     /**
670      * @since 2.6
671      */
withRootName(PropertyName rootName)672     public ObjectReader withRootName(PropertyName rootName) {
673         return _with(_config.withRootName(rootName));
674     }
675 
676     /**
677      * Convenience method that is same as calling:
678      *<code>
679      *   withRootName("")
680      *</code>
681      * which will forcibly prevent use of root name wrapping when writing
682      * values with this {@link ObjectReader}.
683      *
684      * @since 2.6
685      */
withoutRootName()686     public ObjectReader withoutRootName() {
687         return _with(_config.withRootName(PropertyName.NO_NAME));
688     }
689 
690     /**
691      * Method for constructing a new instance with configuration that
692      * passes specified {@link FormatSchema} to {@link JsonParser} that
693      * is constructed for parsing content.
694      *<p>
695      * Note that the method does NOT change state of this reader, but
696      * rather construct and returns a newly configured instance.
697      */
with(FormatSchema schema)698     public ObjectReader with(FormatSchema schema)
699     {
700         if (_schema == schema) {
701             return this;
702         }
703         _verifySchemaType(schema);
704         return _new(this, _config, _valueType, _rootDeserializer, _valueToUpdate,
705                 schema, _injectableValues, _dataFormatReaders);
706     }
707 
708     /**
709      * Method for constructing a new reader instance that is configured
710      * to data bind into specified type.
711      *<p>
712      * Note that the method does NOT change state of this reader, but
713      * rather construct and returns a newly configured instance.
714      *
715      * @since 2.5
716      */
forType(JavaType valueType)717     public ObjectReader forType(JavaType valueType)
718     {
719         if (valueType != null && valueType.equals(_valueType)) {
720             return this;
721         }
722         JsonDeserializer<Object> rootDeser = _prefetchRootDeserializer(valueType);
723         // type is stored here, no need to make a copy of config
724         DataFormatReaders det = _dataFormatReaders;
725         if (det != null) {
726             det = det.withType(valueType);
727         }
728         return _new(this, _config, valueType, rootDeser,
729                 _valueToUpdate, _schema, _injectableValues, det);
730     }
731 
732     /**
733      * Method for constructing a new reader instance that is configured
734      * to data bind into specified type.
735      *<p>
736      * Note that the method does NOT change state of this reader, but
737      * rather construct and returns a newly configured instance.
738      *
739      * @since 2.5
740      */
forType(Class<?> valueType)741     public ObjectReader forType(Class<?> valueType) {
742         return forType(_config.constructType(valueType));
743     }
744 
745     /**
746      * Method for constructing a new reader instance that is configured
747      * to data bind into specified type.
748      *<p>
749      * Note that the method does NOT change state of this reader, but
750      * rather construct and returns a newly configured instance.
751      *
752      * @since 2.5
753      */
forType(TypeReference<?> valueTypeRef)754     public ObjectReader forType(TypeReference<?> valueTypeRef) {
755         return forType(_config.getTypeFactory().constructType(valueTypeRef.getType()));
756     }
757 
758     /**
759      * @deprecated since 2.5 Use {@link #forType(JavaType)} instead
760      */
761     @Deprecated
withType(JavaType valueType)762     public ObjectReader withType(JavaType valueType) {
763         return forType(valueType);
764     }
765 
766     /**
767      * @deprecated since 2.5 Use {@link #forType(Class)} instead
768      */
769     @Deprecated
withType(Class<?> valueType)770     public ObjectReader withType(Class<?> valueType) {
771         return forType(_config.constructType(valueType));
772     }
773 
774     /**
775      * @deprecated since 2.5 Use {@link #forType(Class)} instead
776      */
777     @Deprecated
withType(java.lang.reflect.Type valueType)778     public ObjectReader withType(java.lang.reflect.Type valueType) {
779         return forType(_config.getTypeFactory().constructType(valueType));
780     }
781 
782     /**
783      * @deprecated since 2.5 Use {@link #forType(TypeReference)} instead
784      */
785     @Deprecated
withType(TypeReference<?> valueTypeRef)786     public ObjectReader withType(TypeReference<?> valueTypeRef) {
787         return forType(_config.getTypeFactory().constructType(valueTypeRef.getType()));
788     }
789 
790     /**
791      * Method for constructing a new instance with configuration that
792      * updates passed Object (as root value), instead of constructing
793      * a new value.
794      *<p>
795      * Note that the method does NOT change state of this reader, but
796      * rather construct and returns a newly configured instance.
797      */
withValueToUpdate(Object value)798     public ObjectReader withValueToUpdate(Object value)
799     {
800         if (value == _valueToUpdate) return this;
801         if (value == null) {
802             // 18-Oct-2016, tatu: Actually, should be allowed, to remove value
803             //   to update, if any
804             return _new(this, _config, _valueType, _rootDeserializer, null,
805                     _schema, _injectableValues, _dataFormatReaders);
806         }
807         JavaType t;
808 
809         /* no real benefit from pre-fetching, as updating readers are much
810          * less likely to be reused, and value type may also be forced
811          * with a later chained call...
812          */
813         if (_valueType == null) {
814             t = _config.constructType(value.getClass());
815         } else {
816             t = _valueType;
817         }
818         return _new(this, _config, t, _rootDeserializer, value,
819                 _schema, _injectableValues, _dataFormatReaders);
820     }
821 
822     /**
823      * Method for constructing a new instance with configuration that
824      * uses specified View for filtering.
825      *<p>
826      * Note that the method does NOT change state of this reader, but
827      * rather construct and returns a newly configured instance.
828      */
withView(Class<?> activeView)829     public ObjectReader withView(Class<?> activeView) {
830         return _with(_config.withView(activeView));
831     }
832 
with(Locale l)833     public ObjectReader with(Locale l) {
834         return _with(_config.with(l));
835     }
836 
with(TimeZone tz)837     public ObjectReader with(TimeZone tz) {
838         return _with(_config.with(tz));
839     }
840 
withHandler(DeserializationProblemHandler h)841     public ObjectReader withHandler(DeserializationProblemHandler h) {
842         return _with(_config.withHandler(h));
843     }
844 
with(Base64Variant defaultBase64)845     public ObjectReader with(Base64Variant defaultBase64) {
846         return _with(_config.with(defaultBase64));
847     }
848 
849     /**
850      * Fluent factory method for constructing a reader that will try to
851      * auto-detect underlying data format, using specified list of
852      * {@link JsonFactory} instances, and default {@link DataFormatReaders} settings
853      * (for customized {@link DataFormatReaders}, you can construct instance yourself).
854      * to construct appropriate {@link JsonParser} for actual parsing.
855      *<p>
856      * Note: since format detection only works with byte sources, it is possible to
857      * get a failure from some 'readValue()' methods. Also, if input cannot be reliably
858      * (enough) detected as one of specified types, an exception will be thrown.
859      *<p>
860      * Note: not all {@link JsonFactory} types can be passed: specifically, ones that
861      * require "custom codec" (like XML factory) will not work. Instead, use
862      * method that takes {@link ObjectReader} instances instead of factories.
863      *
864      * @param readers Data formats accepted, in decreasing order of priority (that is,
865      *   matches checked in listed order, first match wins)
866      *
867      * @return Newly configured writer instance
868      *
869      * @since 2.1
870      */
withFormatDetection(ObjectReader... readers)871     public ObjectReader withFormatDetection(ObjectReader... readers) {
872         return withFormatDetection(new DataFormatReaders(readers));
873     }
874 
875     /**
876      * Fluent factory method for constructing a reader that will try to
877      * auto-detect underlying data format, using specified
878      * {@link DataFormatReaders}.
879      *<p>
880      * NOTE: since format detection only works with byte sources, it is possible to
881      * get a failure from some 'readValue()' methods. Also, if input cannot be reliably
882      * (enough) detected as one of specified types, an exception will be thrown.
883      *
884      * @param readers DataFormatReaders to use for detecting underlying format.
885      *
886      * @return Newly configured writer instance
887      *
888      * @since 2.1
889      */
withFormatDetection(DataFormatReaders readers)890     public ObjectReader withFormatDetection(DataFormatReaders readers) {
891         return _new(this, _config, _valueType, _rootDeserializer, _valueToUpdate,
892                 _schema, _injectableValues, readers);
893     }
894 
895     /**
896      * @since 2.3
897      */
with(ContextAttributes attrs)898     public ObjectReader with(ContextAttributes attrs) {
899         return _with(_config.with(attrs));
900     }
901 
902     /**
903      * @since 2.3
904      */
withAttributes(Map<?,?> attrs)905     public ObjectReader withAttributes(Map<?,?> attrs) {
906         return _with(_config.withAttributes(attrs));
907     }
908 
909     /**
910      * @since 2.3
911      */
withAttribute(Object key, Object value)912     public ObjectReader withAttribute(Object key, Object value) {
913         return _with( _config.withAttribute(key, value));
914     }
915 
916     /**
917      * @since 2.3
918      */
withoutAttribute(Object key)919     public ObjectReader withoutAttribute(Object key) {
920         return _with(_config.withoutAttribute(key));
921     }
922 
923     /*
924     /**********************************************************
925     /* Overridable factory methods may override
926     /**********************************************************
927      */
928 
_with(DeserializationConfig newConfig)929     protected ObjectReader _with(DeserializationConfig newConfig) {
930         if (newConfig == _config) {
931             return this;
932         }
933         ObjectReader r = _new(this, newConfig);
934         if (_dataFormatReaders != null) {
935             r  = r.withFormatDetection(_dataFormatReaders.with(newConfig));
936         }
937         return r;
938     }
939 
940     /*
941     /**********************************************************
942     /* Simple accessors
943     /**********************************************************
944      */
945 
isEnabled(DeserializationFeature f)946     public boolean isEnabled(DeserializationFeature f) {
947         return _config.isEnabled(f);
948     }
949 
isEnabled(MapperFeature f)950     public boolean isEnabled(MapperFeature f) {
951         return _config.isEnabled(f);
952     }
953 
isEnabled(JsonParser.Feature f)954     public boolean isEnabled(JsonParser.Feature f) {
955         return _config.isEnabled(f, _parserFactory);
956     }
957 
958     /**
959      * @since 2.11
960      */
isEnabled(StreamReadFeature f)961     public boolean isEnabled(StreamReadFeature f) {
962         return _config.isEnabled(f.mappedFeature(), _parserFactory);
963     }
964 
965     /**
966      * @since 2.2
967      */
getConfig()968     public DeserializationConfig getConfig() {
969         return _config;
970     }
971 
972     /**
973      * @since 2.1
974      */
975     @Override
getFactory()976     public JsonFactory getFactory() {
977         return _parserFactory;
978     }
979 
getTypeFactory()980     public TypeFactory getTypeFactory() {
981         return _config.getTypeFactory();
982     }
983 
984     /**
985      * @since 2.3
986      */
getAttributes()987     public ContextAttributes getAttributes() {
988         return _config.getAttributes();
989     }
990 
991     /**
992      * @since 2.6
993      */
getInjectableValues()994     public InjectableValues getInjectableValues() {
995         return _injectableValues;
996     }
997 
998     /**
999      * @since 2.10
1000      */
getValueType()1001     public JavaType getValueType() {
1002         return _valueType;
1003     }
1004 
1005     /*
1006     /**********************************************************
1007     /* Factory methods for creating JsonParsers (added in 2.11)
1008     /**********************************************************
1009      */
1010 
1011     /**
1012      * Factory method for constructing properly initialized {@link JsonParser}
1013      * to read content from specified {@link File}.
1014      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1015      * for properly closing it once content reading is complete.
1016      *
1017      * @since 2.11
1018      */
createParser(File src)1019     public JsonParser createParser(File src) throws IOException {
1020         _assertNotNull("src", src);
1021         return _config.initialize(_parserFactory.createParser(src), _schema);
1022     }
1023 
1024     /**
1025      * Factory method for constructing properly initialized {@link JsonParser}
1026      * to read content from specified {@link File}.
1027      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1028      * for properly closing it once content reading is complete.
1029      *
1030      * @since 2.11
1031      */
createParser(URL src)1032     public JsonParser createParser(URL src) throws IOException {
1033         _assertNotNull("src", src);
1034         return _config.initialize(_parserFactory.createParser(src), _schema);
1035     }
1036 
1037     /**
1038      * Factory method for constructing properly initialized {@link JsonParser}
1039      * to read content using specified {@link InputStream}.
1040      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1041      * for properly closing it once content reading is complete.
1042      *
1043      * @since 2.11
1044      */
createParser(InputStream in)1045     public JsonParser createParser(InputStream in) throws IOException {
1046         _assertNotNull("in", in);
1047         return _config.initialize(_parserFactory.createParser(in), _schema);
1048     }
1049 
1050     /**
1051      * Factory method for constructing properly initialized {@link JsonParser}
1052      * to read content using specified {@link Reader}.
1053      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1054      * for properly closing it once content reading is complete.
1055      *
1056      * @since 2.11
1057      */
createParser(Reader r)1058     public JsonParser createParser(Reader r) throws IOException {
1059         _assertNotNull("r", r);
1060         return _config.initialize(_parserFactory.createParser(r), _schema);
1061     }
1062 
1063     /**
1064      * Factory method for constructing properly initialized {@link JsonParser}
1065      * to read content from specified byte array.
1066      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1067      * for properly closing it once content reading is complete.
1068      *
1069      * @since 2.11
1070      */
createParser(byte[] content)1071     public JsonParser createParser(byte[] content) throws IOException {
1072         _assertNotNull("content", content);
1073         return _config.initialize(_parserFactory.createParser(content), _schema);
1074     }
1075 
1076     /**
1077      * Factory method for constructing properly initialized {@link JsonParser}
1078      * to read content from specified byte array.
1079      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1080      * for properly closing it once content reading is complete.
1081      *
1082      * @since 2.11
1083      */
createParser(byte[] content, int offset, int len)1084     public JsonParser createParser(byte[] content, int offset, int len) throws IOException {
1085         _assertNotNull("content", content);
1086         return _config.initialize(_parserFactory.createParser(content, offset, len), _schema);
1087     }
1088 
1089     /**
1090      * Factory method for constructing properly initialized {@link JsonParser}
1091      * to read content from specified String.
1092      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1093      * for properly closing it once content reading is complete.
1094      *
1095      * @since 2.11
1096      */
createParser(String content)1097     public JsonParser createParser(String content) throws IOException {
1098         _assertNotNull("content", content);
1099         return _config.initialize(_parserFactory.createParser(content), _schema);
1100     }
1101 
1102     /**
1103      * Factory method for constructing properly initialized {@link JsonParser}
1104      * to read content from specified character array
1105      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1106      * for properly closing it once content reading is complete.
1107      *
1108      * @since 2.11
1109      */
createParser(char[] content)1110     public JsonParser createParser(char[] content) throws IOException {
1111         _assertNotNull("content", content);
1112         return _config.initialize(_parserFactory.createParser(content), _schema);
1113     }
1114 
1115     /**
1116      * Factory method for constructing properly initialized {@link JsonParser}
1117      * to read content from specified character array.
1118      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1119      * for properly closing it once content reading is complete.
1120      *
1121      * @since 2.11
1122      */
createParser(char[] content, int offset, int len)1123     public JsonParser createParser(char[] content, int offset, int len) throws IOException {
1124         _assertNotNull("content", content);
1125         return _config.initialize(_parserFactory.createParser(content, offset, len), _schema);
1126     }
1127 
1128     /**
1129      * Factory method for constructing properly initialized {@link JsonParser}
1130      * to read content using specified {@link DataInput}.
1131      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1132      * for properly closing it once content reading is complete.
1133      *
1134      * @since 2.11
1135      */
createParser(DataInput content)1136     public JsonParser createParser(DataInput content) throws IOException {
1137         _assertNotNull("content", content);
1138         return _config.initialize(_parserFactory.createParser(content), _schema);
1139     }
1140 
1141     /**
1142      * Factory method for constructing properly initialized {@link JsonParser}
1143      * to read content using non-blocking (asynchronous) mode.
1144      * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1145      * for properly closing it once content reading is complete.
1146      *
1147      * @since 2.11
1148      */
createNonBlockingByteArrayParser()1149     public JsonParser createNonBlockingByteArrayParser() throws IOException {
1150         return _config.initialize(_parserFactory.createNonBlockingByteArrayParser(), _schema);
1151     }
1152 
1153     /*
1154     /**********************************************************
1155     /* Deserialization methods; basic ones to support ObjectCodec first
1156     /* (ones that take JsonParser)
1157     /**********************************************************
1158      */
1159 
1160     /**
1161      * Method that binds content read using given parser, using
1162      * configuration of this reader, including expected result type.
1163      * Value return is either newly constructed, or root value that
1164      * was specified with {@link #withValueToUpdate(Object)}.
1165      *<p>
1166      * NOTE: this method never tries to auto-detect format, since actual
1167      * (data-format specific) parser is given.
1168      */
1169     @SuppressWarnings("unchecked")
readValue(JsonParser p)1170     public <T> T readValue(JsonParser p) throws IOException
1171     {
1172         _assertNotNull("p", p);
1173         return (T) _bind(p, _valueToUpdate);
1174     }
1175 
1176     /**
1177      * Convenience method that binds content read using given parser, using
1178      * configuration of this reader, except that expected value type
1179      * is specified with the call (instead of currently configured root type).
1180      * Value return is either newly constructed, or root value that
1181      * was specified with {@link #withValueToUpdate(Object)}.
1182      *<p>
1183      * NOTE: this method never tries to auto-detect format, since actual
1184      * (data-format specific) parser is given.
1185      */
1186     @SuppressWarnings("unchecked")
1187     @Override
readValue(JsonParser p, Class<T> valueType)1188     public <T> T readValue(JsonParser p, Class<T> valueType) throws IOException
1189     {
1190         _assertNotNull("p", p);
1191         return (T) forType(valueType).readValue(p);
1192     }
1193 
1194     /**
1195      * Convenience method that binds content read using given parser, using
1196      * configuration of this reader, except that expected value type
1197      * is specified with the call (instead of currently configured root type).
1198      * Value return is either newly constructed, or root value that
1199      * was specified with {@link #withValueToUpdate(Object)}.
1200      *<p>
1201      * NOTE: this method never tries to auto-detect format, since actual
1202      * (data-format specific) parser is given.
1203      */
1204     @SuppressWarnings("unchecked")
1205     @Override
readValue(JsonParser p, TypeReference<T> valueTypeRef)1206     public <T> T readValue(JsonParser p, TypeReference<T> valueTypeRef) throws IOException
1207     {
1208         _assertNotNull("p", p);
1209         return (T) forType(valueTypeRef).readValue(p);
1210     }
1211 
1212     /**
1213      * Convenience method that binds content read using given parser, using
1214      * configuration of this reader, except that expected value type
1215      * is specified with the call (instead of currently configured root type).
1216      * Value return is either newly constructed, or root value that
1217      * was specified with {@link #withValueToUpdate(Object)}.
1218      *<p>
1219      * NOTE: this method never tries to auto-detect format, since actual
1220      * (data-format specific) parser is given.
1221      */
1222     @Override
1223     @SuppressWarnings("unchecked")
readValue(JsonParser p, ResolvedType valueType)1224     public <T> T readValue(JsonParser p, ResolvedType valueType) throws IOException {
1225         _assertNotNull("p", p);
1226         return (T) forType((JavaType)valueType).readValue(p);
1227     }
1228 
1229     /**
1230      * Type-safe overloaded method, basically alias for {@link #readValue(JsonParser, ResolvedType)}.
1231      *<p>
1232      * NOTE: this method never tries to auto-detect format, since actual
1233      * (data-format specific) parser is given.
1234      */
1235     @SuppressWarnings("unchecked")
readValue(JsonParser p, JavaType valueType)1236     public <T> T readValue(JsonParser p, JavaType valueType) throws IOException {
1237         _assertNotNull("p", p);
1238         return (T) forType(valueType).readValue(p);
1239     }
1240 
1241     /**
1242      * Convenience method that is equivalent to:
1243      *<pre>
1244      *   withType(valueType).readValues(p);
1245      *</pre>
1246      *<p>
1247      * Method reads a sequence of Objects from parser stream.
1248      * Sequence can be either root-level "unwrapped" sequence (without surrounding
1249      * JSON array), or a sequence contained in a JSON Array.
1250      * In either case {@link JsonParser} <b>MUST</b> point to the first token of
1251      * the first element, OR not point to any token (in which case it is advanced
1252      * to the next token). This means, specifically, that for wrapped sequences,
1253      * parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
1254      * contains values to read) but rather to the token following it which is the first
1255      * token of the first value to read.
1256      *<p>
1257      * NOTE: this method never tries to auto-detect format, since actual
1258      * (data-format specific) parser is given.
1259      */
1260     @Override
readValues(JsonParser p, Class<T> valueType)1261     public <T> Iterator<T> readValues(JsonParser p, Class<T> valueType) throws IOException {
1262         _assertNotNull("p", p);
1263         return forType(valueType).readValues(p);
1264     }
1265 
1266     /**
1267      * Convenience method that is equivalent to:
1268      *<pre>
1269      *   withType(valueTypeRef).readValues(p);
1270      *</pre>
1271      *<p>
1272      * Method reads a sequence of Objects from parser stream.
1273      * Sequence can be either root-level "unwrapped" sequence (without surrounding
1274      * JSON array), or a sequence contained in a JSON Array.
1275      * In either case {@link JsonParser} <b>MUST</b> point to the first token of
1276      * the first element, OR not point to any token (in which case it is advanced
1277      * to the next token). This means, specifically, that for wrapped sequences,
1278      * parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
1279      * contains values to read) but rather to the token following it which is the first
1280      * token of the first value to read.
1281      *<p>
1282      * NOTE: this method never tries to auto-detect format, since actual
1283      * (data-format specific) parser is given.
1284      */
1285     @Override
readValues(JsonParser p, TypeReference<T> valueTypeRef)1286     public <T> Iterator<T> readValues(JsonParser p, TypeReference<T> valueTypeRef) throws IOException {
1287         _assertNotNull("p", p);
1288         return forType(valueTypeRef).readValues(p);
1289     }
1290 
1291     /**
1292      * Convenience method that is equivalent to:
1293      *<pre>
1294      *   withType(valueType).readValues(p);
1295      *</pre>
1296      *<p>
1297      * Method reads a sequence of Objects from parser stream.
1298      * Sequence can be either root-level "unwrapped" sequence (without surrounding
1299      * JSON array), or a sequence contained in a JSON Array.
1300      * In either case {@link JsonParser} <b>MUST</b> point to the first token of
1301      * the first element, OR not point to any token (in which case it is advanced
1302      * to the next token). This means, specifically, that for wrapped sequences,
1303      * parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
1304      * contains values to read) but rather to the token following it which is the first
1305      * token of the first value to read.
1306      *<p>
1307      * NOTE: this method never tries to auto-detect format, since actual
1308      * (data-format specific) parser is given.
1309      */
1310     @Override
readValues(JsonParser p, ResolvedType valueType)1311     public <T> Iterator<T> readValues(JsonParser p, ResolvedType valueType) throws IOException {
1312         _assertNotNull("p", p);
1313         return readValues(p, (JavaType) valueType);
1314     }
1315 
1316     /**
1317      * Convenience method that is equivalent to:
1318      *<pre>
1319      *   withType(valueType).readValues(p);
1320      *</pre>
1321      *<p>
1322      * Method reads a sequence of Objects from parser stream.
1323      * Sequence can be either root-level "unwrapped" sequence (without surrounding
1324      * JSON array), or a sequence contained in a JSON Array.
1325      * In either case {@link JsonParser} <b>MUST</b> point to the first token of
1326      * the first element, OR not point to any token (in which case it is advanced
1327      * to the next token). This means, specifically, that for wrapped sequences,
1328      * parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
1329      * contains values to read) but rather to the token following it which is the first
1330      * token of the first value to read.
1331      *<p>
1332      * NOTE: this method never tries to auto-detect format, since actual
1333      * (data-format specific) parser is given.
1334      */
readValues(JsonParser p, JavaType valueType)1335     public <T> Iterator<T> readValues(JsonParser p, JavaType valueType) throws IOException {
1336         _assertNotNull("p", p);
1337         return forType(valueType).readValues(p);
1338     }
1339 
1340     /*
1341     /**********************************************************
1342     /* TreeCodec impl
1343     /**********************************************************
1344      */
1345 
1346     @Override
createArrayNode()1347     public JsonNode createArrayNode() {
1348         return _config.getNodeFactory().arrayNode();
1349     }
1350 
1351     @Override
createObjectNode()1352     public JsonNode createObjectNode() {
1353         return _config.getNodeFactory().objectNode();
1354     }
1355 
1356     @Override // since 2.10
missingNode()1357     public JsonNode missingNode() {
1358         return _config.getNodeFactory().missingNode();
1359     }
1360 
1361     @Override // since 2.10
nullNode()1362     public JsonNode nullNode() {
1363         return _config.getNodeFactory().nullNode();
1364     }
1365 
1366     @Override
treeAsTokens(TreeNode n)1367     public JsonParser treeAsTokens(TreeNode n) {
1368         _assertNotNull("n", n);
1369         // 05-Dec-2017, tatu: Important! Must clear "valueToUpdate" since we do not
1370         //    want update to be applied here, as a side effect
1371         ObjectReader codec = withValueToUpdate(null);
1372         return new TreeTraversingParser((JsonNode) n, codec);
1373     }
1374 
1375     /**
1376      * Convenience method that binds content read using given parser, using
1377      * configuration of this reader, except that content is bound as
1378      * JSON tree instead of configured root value type.
1379      * Returns {@link JsonNode} that represents the root of the resulting tree, if there
1380      * was content to read, or {@code null} if no more content is accessible
1381      * via passed {@link JsonParser}.
1382      *<p>
1383      * NOTE! Behavior with end-of-input (no more content) differs between this
1384      * {@code readTree} method, and all other methods that take input source: latter
1385      * will return "missing node", NOT {@code null}
1386      *<p>
1387      * Note: if an object was specified with {@link #withValueToUpdate}, it
1388      * will be ignored.
1389      *<p>
1390      * NOTE: this method never tries to auto-detect format, since actual
1391      * (data-format specific) parser is given.
1392      */
1393     @SuppressWarnings("unchecked")
1394     @Override
readTree(JsonParser p)1395     public <T extends TreeNode> T readTree(JsonParser p) throws IOException {
1396         _assertNotNull("p", p);
1397         return (T) _bindAsTreeOrNull(p);
1398     }
1399 
1400     @Override
writeTree(JsonGenerator g, TreeNode rootNode)1401     public void writeTree(JsonGenerator g, TreeNode rootNode) {
1402         throw new UnsupportedOperationException();
1403     }
1404 
1405     /*
1406     /**********************************************************
1407     /* Deserialization methods; others similar to what ObjectMapper has
1408     /**********************************************************
1409      */
1410 
1411     /**
1412      * Method that binds content read from given input source,
1413      * using configuration of this reader.
1414      * Value return is either newly constructed, or root value that
1415      * was specified with {@link #withValueToUpdate(Object)}.
1416      *
1417      * @param src Source to read content from
1418      */
1419     @SuppressWarnings("unchecked")
readValue(InputStream src)1420     public <T> T readValue(InputStream src) throws IOException
1421     {
1422         if (_dataFormatReaders != null) {
1423             return (T) _detectBindAndClose(_dataFormatReaders.findFormat(src), false);
1424         }
1425         return (T) _bindAndClose(_considerFilter(createParser(src), false));
1426     }
1427 
1428     /**
1429      * Same as {@link #readValue(InputStream)} except that target value type
1430      * overridden as {@code valueType}
1431      *
1432      * @param src Source to read content from
1433      * @param valueType Target type to bind content to
1434      *
1435      * @since 2.11
1436      */
1437     @SuppressWarnings("unchecked")
readValue(InputStream src, Class<T> valueType)1438     public <T> T readValue(InputStream src, Class<T> valueType) throws IOException
1439     {
1440         return (T) forType(valueType).readValue(src);
1441     }
1442 
1443     /**
1444      * Method that binds content read from given input source,
1445      * using configuration of this reader.
1446      * Value return is either newly constructed, or root value that
1447      * was specified with {@link #withValueToUpdate(Object)}.
1448      *
1449      * @param src Source to read content from
1450      */
1451     @SuppressWarnings("unchecked")
readValue(Reader src)1452     public <T> T readValue(Reader src) throws IOException
1453     {
1454         if (_dataFormatReaders != null) {
1455             _reportUndetectableSource(src);
1456         }
1457         return (T) _bindAndClose(_considerFilter(createParser(src), false));
1458     }
1459 
1460     /**
1461      * Same as {@link #readValue(Reader)} except that target value type
1462      * overridden as {@code valueType}
1463      *
1464      * @param src Source to read content from
1465      * @param valueType Target type to bind content to
1466      *
1467      * @since 2.11
1468      */
1469     @SuppressWarnings("unchecked")
readValue(Reader src, Class<T> valueType)1470     public <T> T readValue(Reader src, Class<T> valueType) throws IOException
1471     {
1472         return (T) forType(valueType).readValue(src);
1473     }
1474 
1475     /**
1476      * Method that binds content read from given JSON string,
1477      * using configuration of this reader.
1478      * Value return is either newly constructed, or root value that
1479      * was specified with {@link #withValueToUpdate(Object)}.
1480      *
1481      * @param src String that contains content to read
1482      */
1483     @SuppressWarnings("unchecked")
readValue(String src)1484     public <T> T readValue(String src) throws JsonProcessingException, JsonMappingException
1485     {
1486         if (_dataFormatReaders != null) {
1487             _reportUndetectableSource(src);
1488         }
1489         try { // since 2.10 remove "impossible" IOException as per [databind#1675]
1490             return (T) _bindAndClose(_considerFilter(createParser(src), false));
1491         } catch (JsonProcessingException e) {
1492             throw e;
1493         } catch (IOException e) { // shouldn't really happen but being declared need to
1494             throw JsonMappingException.fromUnexpectedIOE(e);
1495         }
1496     }
1497 
1498     /**
1499      * Same as {@link #readValue(String)} except that target value type
1500      * overridden as {@code valueType}
1501      *
1502      * @param src String that contains content to read
1503      * @param valueType Target type to bind content to
1504      *
1505      * @since 2.11
1506      */
1507     @SuppressWarnings("unchecked")
readValue(String src, Class<T> valueType)1508     public <T> T readValue(String src, Class<T> valueType) throws IOException
1509     {
1510         return (T) forType(valueType).readValue(src);
1511     }
1512 
1513     /**
1514      * Method that binds content read from given byte array,
1515      * using configuration of this reader.
1516      * Value return is either newly constructed, or root value that
1517      * was specified with {@link #withValueToUpdate(Object)}.
1518      *
1519      * @param content Byte array that contains encoded content to read
1520      */
1521     @SuppressWarnings("unchecked")
readValue(byte[] content)1522     public <T> T readValue(byte[] content) throws IOException
1523     {
1524         if (_dataFormatReaders != null) {
1525             return (T) _detectBindAndClose(content, 0, content.length);
1526         }
1527         return (T) _bindAndClose(_considerFilter(createParser(content), false));
1528     }
1529 
1530     /**
1531      * Same as {@link #readValue(byte[])} except that target value type
1532      * overridden as {@code valueType}
1533      *
1534      * @param content Byte array that contains encoded content to read
1535      * @param valueType Target type to bind content to
1536      *
1537      * @since 2.11
1538      */
1539     @SuppressWarnings("unchecked")
readValue(byte[] content, Class<T> valueType)1540     public <T> T readValue(byte[] content, Class<T> valueType) throws IOException
1541     {
1542         return (T) forType(valueType).readValue(content);
1543     }
1544 
1545     /**
1546      * Method that binds content read from given byte array,
1547      * using configuration of this reader.
1548      * Value return is either newly constructed, or root value that
1549      * was specified with {@link #withValueToUpdate(Object)}.
1550      *
1551      * @param buffer Byte array that contains encoded content to read
1552      * @param offset Offset of the first content byte in {@code buffer}
1553      * @param length Length of content in {@code buffer}, in bytes
1554      */
1555     @SuppressWarnings("unchecked")
readValue(byte[] buffer, int offset, int length)1556     public <T> T readValue(byte[] buffer, int offset, int length) throws IOException
1557     {
1558         if (_dataFormatReaders != null) {
1559             return (T) _detectBindAndClose(buffer, offset, length);
1560         }
1561         return (T) _bindAndClose(_considerFilter(createParser(buffer, offset, length),
1562                 false));
1563     }
1564 
1565     /**
1566      * Same as {@link #readValue(byte[],int,int)} except that target value type
1567      * overridden as {@code valueType}
1568      *
1569      * @param buffer Byte array that contains encoded content to read
1570      * @param offset Offset of the first content byte in {@code buffer}
1571      * @param length Length of content in {@code buffer}, in bytes
1572      * @param valueType Target type to bind content to
1573      *
1574      * @since 2.11
1575      */
1576     @SuppressWarnings("unchecked")
readValue(byte[] buffer, int offset, int length, Class<T> valueType)1577     public <T> T readValue(byte[] buffer, int offset, int length, Class<T> valueType) throws IOException
1578     {
1579         return (T) forType(valueType).readValue(buffer, offset, length);
1580     }
1581 
1582     /**
1583      * Method that binds content read from given {@link File}
1584      * using configuration of this reader.
1585      * Value return is either newly constructed, or root value that
1586      * was specified with {@link #withValueToUpdate(Object)}.
1587      *
1588      * @param src File that contains content to read
1589      */
1590     @SuppressWarnings("unchecked")
readValue(File src)1591     public <T> T readValue(File src) throws IOException
1592     {
1593         if (_dataFormatReaders != null) {
1594             return (T) _detectBindAndClose(_dataFormatReaders.findFormat(_inputStream(src)), true);
1595         }
1596 
1597         return (T) _bindAndClose(_considerFilter(createParser(src), false));
1598     }
1599 
1600     /**
1601      * Same as {@link #readValue(File)} except that target value type
1602      * overridden as {@code valueType}
1603      *
1604      * @param src File that contains content to read
1605      * @param valueType Target type to bind content to
1606      *
1607      * @since 2.11
1608      */
1609     @SuppressWarnings("unchecked")
readValue(File src, Class<T> valueType)1610     public <T> T readValue(File src, Class<T> valueType) throws IOException
1611     {
1612         return (T) forType(valueType).readValue(src);
1613     }
1614 
1615     /**
1616      * Method that binds content read from given input source,
1617      * using configuration of this reader.
1618      * Value return is either newly constructed, or root value that
1619      * was specified with {@link #withValueToUpdate(Object)}.
1620      *<p>
1621      *<p>
1622      * NOTE: handling of {@link java.net.URL} is delegated to
1623      * {@link JsonFactory#createParser(java.net.URL)} and usually simply
1624      * calls {@link java.net.URL#openStream()}, meaning no special handling
1625      * is done. If different HTTP connection options are needed you will need
1626      * to create {@link java.io.InputStream} separately.
1627      */
1628     @SuppressWarnings("unchecked")
readValue(URL src)1629     public <T> T readValue(URL src) throws IOException
1630     {
1631         if (_dataFormatReaders != null) {
1632             return (T) _detectBindAndClose(_dataFormatReaders.findFormat(_inputStream(src)), true);
1633         }
1634         return (T) _bindAndClose(_considerFilter(createParser(src), false));
1635     }
1636 
1637     /**
1638      * Same as {@link #readValue(URL)} except that target value type
1639      * overridden as {@code valueType}
1640      *
1641      * @param src URL pointing to resource that contains content to read
1642      * @param valueType Target type to bind content to
1643      *
1644      * @since 2.11
1645      */
1646     @SuppressWarnings("unchecked")
readValue(URL src, Class<T> valueType)1647     public <T> T readValue(URL src, Class<T> valueType) throws IOException
1648     {
1649         return (T) forType(valueType).readValue(src);
1650     }
1651 
1652     /**
1653      * Convenience method for converting results from given JSON tree into given
1654      * value type. Basically short-cut for:
1655      *<pre>
1656      *   objectReader.readValue(src.traverse())
1657      *</pre>
1658      *
1659      * @param content Tree that contains content to convert
1660      */
1661     @SuppressWarnings({ "unchecked" })
readValue(JsonNode content)1662     public <T> T readValue(JsonNode content) throws IOException
1663     {
1664         _assertNotNull("content", content);
1665         if (_dataFormatReaders != null) {
1666             _reportUndetectableSource(content);
1667         }
1668         return (T) _bindAndClose(_considerFilter(treeAsTokens(content), false));
1669     }
1670 
1671     /**
1672      * Same as {@link #readValue(JsonNode)} except that target value type
1673      * overridden as {@code valueType}
1674      *
1675      * @param content Tree that contains content to convert
1676      * @param valueType Target type to convert content to
1677      *
1678      * @since 2.11
1679      */
1680     @SuppressWarnings({ "unchecked" })
readValue(JsonNode content, Class<T> valueType)1681     public <T> T readValue(JsonNode content, Class<T> valueType) throws IOException
1682     {
1683         return (T) forType(valueType).readValue(content);
1684     }
1685 
1686     @SuppressWarnings("unchecked")
readValue(DataInput src)1687     public <T> T readValue(DataInput src) throws IOException
1688     {
1689         if (_dataFormatReaders != null) {
1690             _reportUndetectableSource(src);
1691         }
1692         return (T) _bindAndClose(_considerFilter(createParser(src), false));
1693     }
1694 
1695     /**
1696      * Same as {@link #readValue(DataInput)} except that target value type
1697      * overridden as {@code valueType}
1698      *
1699      * @param content DataInput that contains content to read
1700      * @param valueType Target type to bind content to
1701      *
1702      * @since 2.11
1703      */
1704     @SuppressWarnings("unchecked")
readValue(DataInput content, Class<T> valueType)1705     public <T> T readValue(DataInput content, Class<T> valueType) throws IOException
1706     {
1707         return (T) forType(valueType).readValue(content);
1708     }
1709 
1710     /*
1711     /**********************************************************
1712     /* Deserialization methods; JsonNode ("tree")
1713     /**********************************************************
1714      */
1715 
1716     /**
1717      * Method that reads content from given input source,
1718      * using configuration of this reader, and binds it as JSON Tree.
1719      * Returns {@link JsonNode} that represents the root of the resulting tree, if there
1720      * was content to read, or "missing node" (instance of {@link JsonNode} for which
1721      * {@link JsonNode#isMissingNode()} returns true, and behaves otherwise similar to
1722      * "null node") if no more content is accessible through passed-in input source.
1723      *<p>
1724      * NOTE! Behavior with end-of-input (no more content) differs between this
1725      * {@code readTree} method, and {@link #readTree(JsonParser)} -- latter returns
1726      * {@code null} for "no content" case.
1727      *<p>
1728      * Note that if an object was specified with a call to
1729      * {@link #withValueToUpdate(Object)}
1730      * it will just be ignored; result is always a newly constructed
1731      * {@link JsonNode} instance.
1732      */
readTree(InputStream src)1733     public JsonNode readTree(InputStream src) throws IOException
1734     {
1735         if (_dataFormatReaders != null) {
1736             return _detectBindAndCloseAsTree(src);
1737         }
1738         return _bindAndCloseAsTree(_considerFilter(createParser(src), false));
1739     }
1740 
1741     /**
1742      * Same as {@link #readTree(InputStream)} except content accessed through
1743      * passed-in {@link Reader}
1744      */
readTree(Reader src)1745     public JsonNode readTree(Reader src) throws IOException
1746     {
1747         if (_dataFormatReaders != null) {
1748             _reportUndetectableSource(src);
1749         }
1750         return _bindAndCloseAsTree(_considerFilter(createParser(src), false));
1751     }
1752 
1753     /**
1754      * Same as {@link #readTree(InputStream)} except content read from
1755      * passed-in {@link String}
1756      */
readTree(String json)1757     public JsonNode readTree(String json) throws JsonProcessingException, JsonMappingException
1758     {
1759         if (_dataFormatReaders != null) {
1760             _reportUndetectableSource(json);
1761         }
1762         try { // since 2.10 remove "impossible" IOException as per [databind#1675]
1763             return _bindAndCloseAsTree(_considerFilter(createParser(json), false));
1764         } catch (JsonProcessingException e) {
1765             throw e;
1766         } catch (IOException e) { // shouldn't really happen but being declared need to
1767             throw JsonMappingException.fromUnexpectedIOE(e);
1768         }
1769     }
1770 
1771     /**
1772      * Same as {@link #readTree(InputStream)} except content read from
1773      * passed-in byte array.
1774      */
readTree(byte[] json)1775     public JsonNode readTree(byte[] json) throws IOException
1776     {
1777         _assertNotNull("json", json);
1778         if (_dataFormatReaders != null) {
1779             _reportUndetectableSource(json);
1780         }
1781         return _bindAndCloseAsTree(_considerFilter(createParser(json), false));
1782     }
1783 
1784     /**
1785      * Same as {@link #readTree(InputStream)} except content read from
1786      * passed-in byte array.
1787      */
readTree(byte[] json, int offset, int len)1788     public JsonNode readTree(byte[] json, int offset, int len) throws IOException
1789     {
1790         if (_dataFormatReaders != null) {
1791             _reportUndetectableSource(json);
1792         }
1793         return _bindAndCloseAsTree(_considerFilter(createParser(json, offset, len), false));
1794     }
1795 
1796     /**
1797      * Same as {@link #readTree(InputStream)} except content read using
1798      * passed-in {@link DataInput}.
1799      */
readTree(DataInput src)1800     public JsonNode readTree(DataInput src) throws IOException
1801     {
1802         if (_dataFormatReaders != null) {
1803             _reportUndetectableSource(src);
1804         }
1805         return _bindAndCloseAsTree(_considerFilter(createParser(src), false));
1806     }
1807 
1808     /*
1809     /**********************************************************
1810     /* Deserialization methods; reading sequence of values
1811     /**********************************************************
1812      */
1813 
1814     /**
1815      * Method for reading sequence of Objects from parser stream.
1816      *<p>
1817      * Sequence can be either root-level "unwrapped" sequence (without surrounding
1818      * JSON array), or a sequence contained in a JSON Array.
1819      * In either case {@link JsonParser} must point to the first token of
1820      * the first element, OR not point to any token (in which case it is advanced
1821      * to the next token). This means, specifically, that for wrapped sequences,
1822      * parser MUST NOT point to the surrounding <code>START_ARRAY</code> but rather
1823      * to the token following it.
1824      */
readValues(JsonParser p)1825     public <T> MappingIterator<T> readValues(JsonParser p) throws IOException
1826     {
1827         _assertNotNull("p", p);
1828         DeserializationContext ctxt = createDeserializationContext(p);
1829         // false -> do not close as caller gave parser instance
1830         return _newIterator(p, ctxt, _findRootDeserializer(ctxt), false);
1831     }
1832 
1833     /**
1834      * Method for reading sequence of Objects from parser stream.
1835      *<p>
1836      * Sequence can be either wrapped or unwrapped root-level sequence:
1837      * wrapped means that the elements are enclosed in JSON Array;
1838      * and unwrapped that elements are directly accessed at main level.
1839      * Assumption is that iff the first token of the document is
1840      * <code>START_ARRAY</code>, we have a wrapped sequence; otherwise
1841      * unwrapped. For wrapped sequences, leading <code>START_ARRAY</code>
1842      * is skipped, so that for both cases, underlying {@link JsonParser}
1843      * will point to what is expected to be the first token of the first
1844      * element.
1845      *<p>
1846      * Note that the wrapped vs unwrapped logic means that it is NOT
1847      * possible to use this method for reading an unwrapped sequence
1848      * of elements written as JSON Arrays: to read such sequences, one
1849      * has to use {@link #readValues(JsonParser)}, making sure parser
1850      * points to the first token of the first element (i.e. the second
1851      * <code>START_ARRAY</code> which is part of the first element).
1852      */
readValues(InputStream src)1853     public <T> MappingIterator<T> readValues(InputStream src) throws IOException
1854     {
1855         if (_dataFormatReaders != null) {
1856             return _detectBindAndReadValues(_dataFormatReaders.findFormat(src), false);
1857         }
1858 
1859         return _bindAndReadValues(_considerFilter(createParser(src), true));
1860     }
1861 
1862     /**
1863      * Overloaded version of {@link #readValue(InputStream)}.
1864      */
1865     @SuppressWarnings("resource")
readValues(Reader src)1866     public <T> MappingIterator<T> readValues(Reader src) throws IOException
1867     {
1868         if (_dataFormatReaders != null) {
1869             _reportUndetectableSource(src);
1870         }
1871         JsonParser p = _considerFilter(createParser(src), true);
1872         DeserializationContext ctxt = createDeserializationContext(p);
1873         _initForMultiRead(ctxt, p);
1874         p.nextToken();
1875         return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true);
1876     }
1877 
1878     /**
1879      * Overloaded version of {@link #readValue(InputStream)}.
1880      *
1881      * @param json String that contains JSON content to parse
1882      */
1883     @SuppressWarnings("resource")
readValues(String json)1884     public <T> MappingIterator<T> readValues(String json) throws IOException
1885     {
1886         if (_dataFormatReaders != null) {
1887             _reportUndetectableSource(json);
1888         }
1889         JsonParser p = _considerFilter(createParser(json), true);
1890         DeserializationContext ctxt = createDeserializationContext(p);
1891         _initForMultiRead(ctxt, p);
1892         p.nextToken();
1893         return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true);
1894     }
1895 
1896     /**
1897      * Overloaded version of {@link #readValue(InputStream)}.
1898      */
readValues(byte[] src, int offset, int length)1899     public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException
1900     {
1901         if (_dataFormatReaders != null) {
1902             return _detectBindAndReadValues(_dataFormatReaders.findFormat(src, offset, length), false);
1903         }
1904         return _bindAndReadValues(_considerFilter(createParser(src, offset, length),
1905                 true));
1906     }
1907 
1908     /**
1909      * Overloaded version of {@link #readValue(InputStream)}.
1910      */
readValues(byte[] src)1911     public final <T> MappingIterator<T> readValues(byte[] src) throws IOException {
1912         _assertNotNull("src", src);
1913         return readValues(src, 0, src.length);
1914     }
1915 
1916     /**
1917      * Overloaded version of {@link #readValue(InputStream)}.
1918      */
readValues(File src)1919     public <T> MappingIterator<T> readValues(File src) throws IOException
1920     {
1921         if (_dataFormatReaders != null) {
1922             return _detectBindAndReadValues(
1923                     _dataFormatReaders.findFormat(_inputStream(src)), false);
1924         }
1925         return _bindAndReadValues(_considerFilter(createParser(src), true));
1926     }
1927 
1928     /**
1929      * Overloaded version of {@link #readValue(InputStream)}.
1930      *<p>
1931      * NOTE: handling of {@link java.net.URL} is delegated to
1932      * {@link JsonFactory#createParser(java.net.URL)} and usually simply
1933      * calls {@link java.net.URL#openStream()}, meaning no special handling
1934      * is done. If different HTTP connection options are needed you will need
1935      * to create {@link java.io.InputStream} separately.
1936      *
1937      * @param src URL to read to access JSON content to parse.
1938      */
readValues(URL src)1939     public <T> MappingIterator<T> readValues(URL src) throws IOException
1940     {
1941         if (_dataFormatReaders != null) {
1942             return _detectBindAndReadValues(
1943                     _dataFormatReaders.findFormat(_inputStream(src)), true);
1944         }
1945         return _bindAndReadValues(_considerFilter(createParser(src), true));
1946     }
1947 
1948     /**
1949      * @since 2.8
1950      */
readValues(DataInput src)1951     public <T> MappingIterator<T> readValues(DataInput src) throws IOException
1952     {
1953         if (_dataFormatReaders != null) {
1954             _reportUndetectableSource(src);
1955         }
1956         return _bindAndReadValues(_considerFilter(createParser(src), true));
1957     }
1958 
1959     /*
1960     /**********************************************************
1961     /* Implementation of rest of ObjectCodec methods
1962     /**********************************************************
1963      */
1964 
1965     @Override
treeToValue(TreeNode n, Class<T> valueType)1966     public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException
1967     {
1968         _assertNotNull("n", n);
1969         try {
1970             return readValue(treeAsTokens(n), valueType);
1971         } catch (JsonProcessingException e) {
1972             throw e;
1973         } catch (IOException e) { // should not occur, no real i/o...
1974             throw JsonMappingException.fromUnexpectedIOE(e);
1975         }
1976     }
1977 
1978     @Override
writeValue(JsonGenerator gen, Object value)1979     public void writeValue(JsonGenerator gen, Object value) throws IOException {
1980         throw new UnsupportedOperationException("Not implemented for ObjectReader");
1981     }
1982 
1983     /*
1984     /**********************************************************
1985     /* Helper methods, data-binding
1986     /**********************************************************
1987      */
1988 
1989     /**
1990      * Actual implementation of value reading+binding operation.
1991      */
_bind(JsonParser p, Object valueToUpdate)1992     protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException
1993     {
1994         // First: may need to read the next token, to initialize state (either
1995         // before first read from parser, or after previous token has been cleared)
1996         Object result;
1997         final DefaultDeserializationContext ctxt = createDeserializationContext(p);
1998         JsonToken t = _initForReading(ctxt, p);
1999         if (t == JsonToken.VALUE_NULL) {
2000             if (valueToUpdate == null) {
2001                 result = _findRootDeserializer(ctxt).getNullValue(ctxt);
2002             } else {
2003                 result = valueToUpdate;
2004             }
2005         } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
2006             result = valueToUpdate;
2007         } else { // pointing to event other than null
2008             result = ctxt.readRootValue(p, _valueType, _findRootDeserializer(ctxt), _valueToUpdate);
2009         }
2010         // Need to consume the token too
2011         p.clearCurrentToken();
2012         if (_config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
2013             _verifyNoTrailingTokens(p, ctxt, _valueType);
2014         }
2015         return result;
2016     }
2017 
_bindAndClose(JsonParser p0)2018     protected Object _bindAndClose(JsonParser p0) throws IOException
2019     {
2020         try (JsonParser p = p0) {
2021             Object result;
2022 
2023             final DefaultDeserializationContext ctxt = createDeserializationContext(p);
2024             JsonToken t = _initForReading(ctxt, p);
2025             if (t == JsonToken.VALUE_NULL) {
2026                 if (_valueToUpdate == null) {
2027                     result = _findRootDeserializer(ctxt).getNullValue(ctxt);
2028                 } else {
2029                     result = _valueToUpdate;
2030                 }
2031             } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
2032                 result = _valueToUpdate;
2033             } else {
2034                 result = ctxt.readRootValue(p, _valueType, _findRootDeserializer(ctxt), _valueToUpdate);
2035             }
2036             if (_config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
2037                 _verifyNoTrailingTokens(p, ctxt, _valueType);
2038             }
2039             return result;
2040         }
2041     }
2042 
_bindAndCloseAsTree(JsonParser p0)2043     protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException {
2044         try (JsonParser p = p0) {
2045             return _bindAsTree(p);
2046         }
2047     }
2048 
_bindAsTree(JsonParser p)2049     protected final JsonNode _bindAsTree(JsonParser p) throws IOException
2050     {
2051         // Need to inline `_initForReading()` due to tree reading handling end-of-input specially
2052         _config.initialize(p);
2053         if (_schema != null) {
2054             p.setSchema(_schema);
2055         }
2056 
2057         JsonToken t = p.currentToken();
2058         if (t == null) {
2059             t = p.nextToken();
2060             if (t == null) {
2061                 return _config.getNodeFactory().missingNode();
2062             }
2063         }
2064         final DefaultDeserializationContext ctxt = createDeserializationContext(p);
2065         final JsonNode resultNode;
2066 
2067         if (t == JsonToken.VALUE_NULL) {
2068             resultNode = _config.getNodeFactory().nullNode();
2069         } else {
2070             // Will not be called for merge (need not pass _valueToUpdate)
2071             resultNode = (JsonNode) ctxt.readRootValue(p, _jsonNodeType(), _findTreeDeserializer(ctxt), null);
2072         }
2073         if (_config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
2074             _verifyNoTrailingTokens(p, ctxt, _jsonNodeType());
2075         }
2076         return resultNode;
2077     }
2078 
2079     /**
2080      * Same as {@link #_bindAsTree} except end-of-input is reported by returning
2081      * {@code null}, not "missing node"
2082      */
_bindAsTreeOrNull(JsonParser p)2083     protected final JsonNode _bindAsTreeOrNull(JsonParser p) throws IOException
2084     {
2085         _config.initialize(p);
2086         if (_schema != null) {
2087             p.setSchema(_schema);
2088         }
2089         JsonToken t = p.currentToken();
2090         if (t == null) {
2091             t = p.nextToken();
2092             if (t == null) {
2093                 return null;
2094             }
2095         }
2096         final DefaultDeserializationContext ctxt = createDeserializationContext(p);
2097         final JsonNode resultNode;
2098         if (t == JsonToken.VALUE_NULL) {
2099             resultNode = _config.getNodeFactory().nullNode();
2100         } else {
2101             // Will not be called for merge (need not pass _valueToUpdate)
2102             resultNode = (JsonNode) ctxt.readRootValue(p, _jsonNodeType(), _findTreeDeserializer(ctxt), null);
2103         }
2104         if (_config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
2105             _verifyNoTrailingTokens(p, ctxt, _jsonNodeType());
2106         }
2107         return resultNode;
2108     }
2109 
2110     /**
2111      * @since 2.1
2112      */
_bindAndReadValues(JsonParser p)2113     protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException
2114     {
2115         DeserializationContext ctxt = createDeserializationContext(p);
2116         _initForMultiRead(ctxt, p);
2117         p.nextToken();
2118         return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true);
2119     }
2120 
2121     /**
2122      * Consider filter when creating JsonParser.
2123      */
_considerFilter(final JsonParser p, boolean multiValue)2124     protected JsonParser _considerFilter(final JsonParser p, boolean multiValue) {
2125         // 26-Mar-2016, tatu: Need to allow multiple-matches at least if we have
2126         //    have a multiple-value read (that is, "readValues()").
2127         return ((_filter == null) || FilteringParserDelegate.class.isInstance(p))
2128                 ? p : new FilteringParserDelegate(p, _filter, false, multiValue);
2129     }
2130 
2131     /**
2132      * @since 2.9
2133      */
_verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType)2134     protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt,
2135             JavaType bindType)
2136         throws IOException
2137     {
2138         JsonToken t = p.nextToken();
2139         if (t != null) {
2140             Class<?> bt = ClassUtil.rawClass(bindType);
2141             if (bt == null) {
2142                 if (_valueToUpdate != null) {
2143                     bt = _valueToUpdate.getClass();
2144                 }
2145             }
2146             ctxt.reportTrailingTokens(bt, p, t);
2147         }
2148     }
2149 
2150     /*
2151     /**********************************************************
2152     /* Internal methods, format auto-detection
2153     /**********************************************************
2154      */
2155 
2156     @SuppressWarnings("resource")
_detectBindAndClose(byte[] src, int offset, int length)2157     protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException
2158     {
2159         DataFormatReaders.Match match = _dataFormatReaders.findFormat(src, offset, length);
2160         if (!match.hasMatch()) {
2161             _reportUnkownFormat(_dataFormatReaders, match);
2162         }
2163         JsonParser p = match.createParserWithMatch();
2164         return match.getReader()._bindAndClose(p);
2165     }
2166 
2167     @SuppressWarnings({ "resource" })
_detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing)2168     protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing)
2169         throws IOException
2170     {
2171         if (!match.hasMatch()) {
2172             _reportUnkownFormat(_dataFormatReaders, match);
2173         }
2174         JsonParser p = match.createParserWithMatch();
2175         // One more thing: we Own the input stream now; and while it's
2176         // not super clean way to do it, we must ensure closure so:
2177         if (forceClosing) {
2178             p.enable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
2179         }
2180         // important: use matching ObjectReader (may not be 'this')
2181         return match.getReader()._bindAndClose(p);
2182     }
2183 
2184     @SuppressWarnings({ "resource" })
_detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing)2185     protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing)
2186         throws IOException
2187     {
2188         if (!match.hasMatch()) {
2189             _reportUnkownFormat(_dataFormatReaders, match);
2190         }
2191         JsonParser p = match.createParserWithMatch();
2192         // One more thing: we Own the input stream now; and while it's
2193         // not super clean way to do it, we must ensure closure so:
2194         if (forceClosing) {
2195             p.enable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
2196         }
2197         // important: use matching ObjectReader (may not be 'this')
2198         return match.getReader()._bindAndReadValues(p);
2199     }
2200 
2201     @SuppressWarnings({ "resource" })
_detectBindAndCloseAsTree(InputStream in)2202     protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException
2203     {
2204         DataFormatReaders.Match match = _dataFormatReaders.findFormat(in);
2205         if (!match.hasMatch()) {
2206             _reportUnkownFormat(_dataFormatReaders, match);
2207         }
2208         JsonParser p = match.createParserWithMatch();
2209         p.enable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
2210         return match.getReader()._bindAndCloseAsTree(p);
2211     }
2212 
2213     /**
2214      * Method called to indicate that format detection failed to detect format
2215      * of given input
2216      */
_reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match)2217     protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match)
2218         throws JsonProcessingException
2219     {
2220         // 17-Aug-2015, tatu: Unfortunately, no parser/generator available so:
2221         throw new JsonParseException(null, "Cannot detect format from input, does not look like any of detectable formats "
2222                 +detector.toString());
2223     }
2224 
2225     /*
2226     /**********************************************************
2227     /* Internal methods, other
2228     /**********************************************************
2229      */
2230 
2231     /**
2232      * @since 2.2
2233      */
_verifySchemaType(FormatSchema schema)2234     protected void _verifySchemaType(FormatSchema schema)
2235     {
2236         if (schema != null) {
2237             if (!_parserFactory.canUseSchema(schema)) {
2238                     throw new IllegalArgumentException("Cannot use FormatSchema of type "+schema.getClass().getName()
2239                             +" for format "+_parserFactory.getFormatName());
2240             }
2241         }
2242     }
2243 
2244     /**
2245      * Internal helper method called to create an instance of {@link DeserializationContext}
2246      * for deserializing a single root value.
2247      * Can be overridden if a custom context is needed.
2248      */
createDeserializationContext(JsonParser p)2249     protected DefaultDeserializationContext createDeserializationContext(JsonParser p) {
2250         return _context.createInstance(_config, p, _injectableValues);
2251     }
2252 
2253     // @since 2.12 -- needed for Deserializer pre-fetch
createDummyDeserializationContext()2254     protected DefaultDeserializationContext createDummyDeserializationContext() {
2255         return _context.createDummyInstance(_config);
2256     }
2257 
_inputStream(URL src)2258     protected InputStream _inputStream(URL src) throws IOException {
2259         return src.openStream();
2260     }
2261 
_inputStream(File f)2262     protected InputStream _inputStream(File f) throws IOException {
2263         return new FileInputStream(f);
2264     }
2265 
_reportUndetectableSource(Object src)2266     protected void _reportUndetectableSource(Object src) throws JsonParseException
2267     {
2268         // 17-Aug-2015, tatu: Unfortunately, no parser/generator available so:
2269         throw new JsonParseException(null, "Cannot use source of type "
2270                 +src.getClass().getName()+" with format auto-detection: must be byte- not char-based");
2271     }
2272 
2273     /*
2274     /**********************************************************
2275     /* Helper methods, locating deserializers etc
2276     /**********************************************************
2277      */
2278 
2279     /**
2280      * Method called to locate deserializer for the passed root-level value.
2281      */
_findRootDeserializer(DeserializationContext ctxt)2282     protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt)
2283         throws JsonMappingException
2284     {
2285         if (_rootDeserializer != null) {
2286             return _rootDeserializer;
2287         }
2288 
2289         // Sanity check: must have actual type...
2290         JavaType t = _valueType;
2291         if (t == null) {
2292             ctxt.reportBadDefinition((JavaType) null,
2293                     "No value type configured for ObjectReader");
2294         }
2295         // First: have we already seen it?
2296         JsonDeserializer<Object> deser = _rootDeserializers.get(t);
2297         if (deser != null) {
2298             return deser;
2299         }
2300         // Nope: need to ask provider to resolve it
2301         deser = ctxt.findRootValueDeserializer(t);
2302         if (deser == null) { // can this happen?
2303             ctxt.reportBadDefinition(t, "Cannot find a deserializer for type "+t);
2304         }
2305         _rootDeserializers.put(t, deser);
2306         return deser;
2307     }
2308 
2309     /**
2310      * @since 2.6
2311      */
_findTreeDeserializer(DeserializationContext ctxt)2312     protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt)
2313         throws JsonMappingException
2314     {
2315         final JavaType nodeType = _jsonNodeType();
2316         JsonDeserializer<Object> deser = _rootDeserializers.get(nodeType);
2317         if (deser == null) {
2318             // Nope: need to ask provider to resolve it
2319             deser = ctxt.findRootValueDeserializer(nodeType);
2320             if (deser == null) { // can this happen?
2321                 ctxt.reportBadDefinition(nodeType,
2322                         "Cannot find a deserializer for type "+nodeType);
2323             }
2324             _rootDeserializers.put(nodeType, deser);
2325         }
2326         return deser;
2327     }
2328 
2329     /**
2330      * Method called to locate deserializer ahead of time, if permitted
2331      * by configuration. Method also is NOT to throw an exception if
2332      * access fails.
2333      */
_prefetchRootDeserializer(JavaType valueType)2334     protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType)
2335     {
2336         if ((valueType == null) || !_config.isEnabled(DeserializationFeature.EAGER_DESERIALIZER_FETCH)) {
2337             return null;
2338         }
2339         // already cached?
2340         JsonDeserializer<Object> deser = _rootDeserializers.get(valueType);
2341         if (deser == null) {
2342             try {
2343                 // If not, need to resolve; for which we need a temporary context as well:
2344                 DeserializationContext ctxt = createDummyDeserializationContext();
2345                 deser = ctxt.findRootValueDeserializer(valueType);
2346                 if (deser != null) {
2347                     _rootDeserializers.put(valueType, deser);
2348                 }
2349                 return deser;
2350             } catch (JsonProcessingException e) {
2351                 // need to swallow?
2352             }
2353         }
2354         return deser;
2355     }
2356 
2357     /**
2358      * @since 2.10
2359      */
_jsonNodeType()2360     protected final JavaType _jsonNodeType() {
2361         JavaType t = _jsonNodeType;
2362         if (t == null) {
2363             t = getTypeFactory().constructType(JsonNode.class);
2364             _jsonNodeType = t;
2365         }
2366         return t;
2367     }
2368 
_assertNotNull(String paramName, Object src)2369     protected final void _assertNotNull(String paramName, Object src) {
2370         if (src == null) {
2371             throw new IllegalArgumentException(String.format("argument \"%s\" is null", paramName));
2372         }
2373     }
2374 }
2375