• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Jackson JSON-processor.
2  *
3  * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi
4  */
5 
6 package com.fasterxml.jackson.core;
7 
8 import java.io.*;
9 import java.math.BigDecimal;
10 import java.math.BigInteger;
11 import java.util.Iterator;
12 
13 import com.fasterxml.jackson.core.async.NonBlockingInputFeeder;
14 import com.fasterxml.jackson.core.exc.InputCoercionException;
15 import com.fasterxml.jackson.core.type.TypeReference;
16 import com.fasterxml.jackson.core.util.JacksonFeatureSet;
17 import com.fasterxml.jackson.core.util.RequestPayload;
18 
19 /**
20  * Base class that defines public API for reading JSON content.
21  * Instances are created using factory methods of
22  * a {@link JsonFactory} instance.
23  *
24  * @author Tatu Saloranta
25  */
26 public abstract class JsonParser
27     implements Closeable, Versioned
28 {
29     private final static int MIN_BYTE_I = (int) Byte.MIN_VALUE;
30     // as per [JACKSON-804], allow range up to and including 255
31     private final static int MAX_BYTE_I = (int) 255;
32 
33     private final static int MIN_SHORT_I = (int) Short.MIN_VALUE;
34     private final static int MAX_SHORT_I = (int) Short.MAX_VALUE;
35 
36     /**
37      * Enumeration of possible "native" (optimal) types that can be
38      * used for numbers.
39      */
40     public enum NumberType {
41         INT, LONG, BIG_INTEGER, FLOAT, DOUBLE, BIG_DECIMAL
42     };
43 
44     /**
45      * Default set of {@link StreamReadCapability}ies that may be used as
46      * basis for format-specific readers (or as bogus instance if non-null
47      * set needs to be passed).
48      *
49      * @since 2.12
50      */
51     protected final static JacksonFeatureSet<StreamReadCapability> DEFAULT_READ_CAPABILITIES
52         = JacksonFeatureSet.fromDefaults(StreamReadCapability.values());
53 
54     /**
55      * Enumeration that defines all on/off features for parsers.
56      */
57     public enum Feature {
58         // // // Low-level I/O handling features:
59 
60         /**
61          * Feature that determines whether parser will automatically
62          * close underlying input source that is NOT owned by the
63          * parser. If disabled, calling application has to separately
64          * close the underlying {@link InputStream} and {@link Reader}
65          * instances used to create the parser. If enabled, parser
66          * will handle closing, as long as parser itself gets closed:
67          * this happens when end-of-input is encountered, or parser
68          * is closed by a call to {@link JsonParser#close}.
69          *<p>
70          * Feature is enabled by default.
71          */
72         AUTO_CLOSE_SOURCE(true),
73 
74         // // // Support for non-standard data format constructs
75 
76         /**
77          * Feature that determines whether parser will allow use
78          * of Java/C++ style comments (both '/'+'*' and
79          * '//' varieties) within parsed content or not.
80          *<p>
81          * Since JSON specification does not mention comments as legal
82          * construct,
83          * this is a non-standard feature; however, in the wild
84          * this is extensively used. As such, feature is
85          * <b>disabled by default</b> for parsers and must be
86          * explicitly enabled.
87          *<p>
88          * NOTE: while not technically deprecated, since 2.10 recommended to use
89          * {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_JAVA_COMMENTS} instead.
90          */
91         ALLOW_COMMENTS(false),
92 
93         /**
94          * Feature that determines whether parser will allow use
95          * of YAML comments, ones starting with '#' and continuing
96          * until the end of the line. This commenting style is common
97          * with scripting languages as well.
98          *<p>
99          * Since JSON specification does not mention comments as legal
100          * construct,
101          * this is a non-standard feature. As such, feature is
102          * <b>disabled by default</b> for parsers and must be
103          * explicitly enabled.
104          *<p>
105          * NOTE: while not technically deprecated, since 2.10 recommended to use
106          * {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_YAML_COMMENTS} instead.
107          */
108         ALLOW_YAML_COMMENTS(false),
109 
110         /**
111          * Feature that determines whether parser will allow use
112          * of unquoted field names (which is allowed by Javascript,
113          * but not by JSON specification).
114          *<p>
115          * Since JSON specification requires use of double quotes for
116          * field names,
117          * this is a non-standard feature, and as such disabled by default.
118          *<p>
119          * NOTE: while not technically deprecated, since 2.10 recommended to use
120          * {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_UNQUOTED_FIELD_NAMES} instead.
121          */
122         ALLOW_UNQUOTED_FIELD_NAMES(false),
123 
124         /**
125          * Feature that determines whether parser will allow use
126          * of single quotes (apostrophe, character '\'') for
127          * quoting Strings (names and String values). If so,
128          * this is in addition to other acceptable markers.
129          * but not by JSON specification).
130          *<p>
131          * Since JSON specification requires use of double quotes for
132          * field names,
133          * this is a non-standard feature, and as such disabled by default.
134          *<p>
135          * NOTE: while not technically deprecated, since 2.10 recommended to use
136          * {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_SINGLE_QUOTES} instead.
137          */
138         ALLOW_SINGLE_QUOTES(false),
139 
140         /**
141          * Feature that determines whether parser will allow
142          * JSON Strings to contain unquoted control characters
143          * (ASCII characters with value less than 32, including
144          * tab and line feed characters) or not.
145          * If feature is set false, an exception is thrown if such a
146          * character is encountered.
147          *<p>
148          * Since JSON specification requires quoting for all control characters,
149          * this is a non-standard feature, and as such disabled by default.
150          *
151          * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_UNESCAPED_CONTROL_CHARS} instead
152          */
153         @Deprecated
154         ALLOW_UNQUOTED_CONTROL_CHARS(false),
155 
156         /**
157          * Feature that can be enabled to accept quoting of all character
158          * using backslash quoting mechanism: if not enabled, only characters
159          * that are explicitly listed by JSON specification can be thus
160          * escaped (see JSON spec for small list of these characters)
161          *<p>
162          * Since JSON specification requires quoting for all control characters,
163          * this is a non-standard feature, and as such disabled by default.
164          *
165          * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER} instead
166          */
167         @Deprecated
168         ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER(false),
169 
170         /**
171          * Feature that determines whether parser will allow
172          * JSON integral numbers to start with additional (ignorable)
173          * zeroes (like: 000001). If enabled, no exception is thrown, and extra
174          * nulls are silently ignored (and not included in textual representation
175          * exposed via {@link JsonParser#getText}).
176          *<p>
177          * Since JSON specification does not allow leading zeroes,
178          * this is a non-standard feature, and as such disabled by default.
179          *
180          * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_LEADING_ZEROS_FOR_NUMBERS} instead
181          */
182          @Deprecated
183         ALLOW_NUMERIC_LEADING_ZEROS(false),
184 
185         /**
186          * @deprecated Use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS} instead
187          */
188         @Deprecated
189         ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS(false),
190 
191         /**
192          * Feature that allows parser to recognize set of
193          * "Not-a-Number" (NaN) tokens as legal floating number
194          * values (similar to how many other data formats and
195          * programming language source code allows it).
196          * Specific subset contains values that
197          * <a href="http://www.w3.org/TR/xmlschema-2/">XML Schema</a>
198          * (see section 3.2.4.1, Lexical Representation)
199          * allows (tokens are quoted contents, not including quotes):
200          *<ul>
201          *  <li>"INF" (for positive infinity), as well as alias of "Infinity"
202          *  <li>"-INF" (for negative infinity), alias "-Infinity"
203          *  <li>"NaN" (for other not-a-numbers, like result of division by zero)
204          *</ul>
205          *<p>
206          * Since JSON specification does not allow use of such values,
207          * this is a non-standard feature, and as such disabled by default.
208           *
209           * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_NON_NUMERIC_NUMBERS} instead
210           */
211          @Deprecated
212          ALLOW_NON_NUMERIC_NUMBERS(false),
213 
214          /**
215           * Feature allows the support for "missing" values in a JSON array: missing
216           * value meaning sequence of two commas, without value in-between but only
217           * optional white space.
218           * Enabling this feature will expose "missing" values as {@link JsonToken#VALUE_NULL}
219           * tokens, which typically become Java nulls in arrays and {@link java.util.Collection}
220           * in data-binding.
221           * <p>
222           * For example, enabling this feature will represent a JSON array <code>["value1",,"value3",]</code>
223           * as <code>["value1", null, "value3", null]</code>
224           * <p>
225           * Since the JSON specification does not allow missing values this is a non-compliant JSON
226           * feature and is disabled by default.
227           *
228           * @since 2.8
229           *
230           * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_MISSING_VALUES} instead
231           */
232          @Deprecated
233          ALLOW_MISSING_VALUES(false),
234 
235          /**
236           * Feature that determines whether {@link JsonParser} will allow for a single trailing
237           * comma following the final value (in an Array) or member (in an Object). These commas
238           * will simply be ignored.
239           * <p>
240           * For example, when this feature is enabled, <code>[true,true,]</code> is equivalent to
241           * <code>[true, true]</code> and <code>{"a": true,}</code> is equivalent to
242           * <code>{"a": true}</code>.
243           * <p>
244           * When combined with <code>ALLOW_MISSING_VALUES</code>, this feature takes priority, and
245           * the final trailing comma in an array declaration does not imply a missing
246           * (<code>null</code>) value. For example, when both <code>ALLOW_MISSING_VALUES</code>
247           * and <code>ALLOW_TRAILING_COMMA</code> are enabled, <code>[true,true,]</code> is
248           * equivalent to <code>[true, true]</code>, and <code>[true,true,,]</code> is equivalent to
249           * <code>[true, true, null]</code>.
250           * <p>
251           * Since the JSON specification does not permit trailing commas, this is a non-standard
252           * feature, and as such disabled by default.
253           *
254           * @since 2.9
255           *
256           * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_TRAILING_COMMA} instead
257           */
258          @Deprecated
259          ALLOW_TRAILING_COMMA(false),
260 
261          // // // Validity checks
262 
263          /**
264           * Feature that determines whether {@link JsonParser} will explicitly
265           * check that no duplicate JSON Object field names are encountered.
266           * If enabled, parser will check all names within context and report
267           * duplicates by throwing a {@link JsonParseException}; if disabled,
268           * parser will not do such checking. Assumption in latter case is
269           * that caller takes care of handling duplicates at a higher level:
270           * data-binding, for example, has features to specify detection to
271           * be done there.
272           *<p>
273           * Note that enabling this feature will incur performance overhead
274           * due to having to store and check additional information: this typically
275           * adds 20-30% to execution time for basic parsing.
276           *
277           * @since 2.3
278           */
279          STRICT_DUPLICATE_DETECTION(false),
280 
281          /**
282           * Feature that determines what to do if the underlying data format requires knowledge
283           * of all properties to decode (usually via a Schema), and if no definition is
284           * found for a property that input content contains.
285           * Typically most textual data formats do NOT require schema information (although
286           * some do, such as CSV), whereas many binary data formats do require definitions
287           * (such as Avro, protobuf), although not all (Smile, CBOR, BSON and MessagePack do not).
288           * Further note that some formats that do require schema information will not be able
289           * to ignore undefined properties: for example, Avro is fully positional and there is
290           * no possibility of undefined data. This leaves formats like Protobuf that have identifiers
291           * that may or may not map; and as such Protobuf format does make use of this feature.
292           *<p>
293           * Note that support for this feature is implemented by individual data format
294           * module, if (and only if) it makes sense for the format in question. For JSON,
295           * for example, this feature has no effect as properties need not be pre-defined.
296           *<p>
297           * Feature is disabled by default, meaning that if the underlying data format
298           * requires knowledge of all properties to output, attempts to read an unknown
299           * property will result in a {@link JsonProcessingException}
300           *
301           * @since 2.6
302           */
303          IGNORE_UNDEFINED(false),
304 
305          // // // Other
306 
307          /**
308           * Feature that determines whether {@link JsonLocation} instances should be constructed
309           * with reference to source or not. If source reference is included, its type and contents
310           * are included when `toString()` method is called (most notably when printing out parse
311           * exception with that location information). If feature is disabled, no source reference
312           * is passed and source is only indicated as "UNKNOWN".
313           *<p>
314           * Most common reason for disabling this feature is to avoid leaking information about
315           * internal information; this may be done for security reasons.
316           * Note that even if source reference is included, only parts of contents are usually
317           * printed, and not the whole contents. Further, many source reference types can not
318           * necessarily access contents (like streams), so only type is indicated, not contents.
319           *<p>
320           * Feature is enabled by default, meaning that "source reference" information is passed
321           * and some or all of the source content may be included in {@link JsonLocation} information
322           * constructed either when requested explicitly, or when needed for an exception.
323           *
324           * @since 2.9
325           */
326          INCLUDE_SOURCE_IN_LOCATION(true),
327 
328          ;
329 
330         /**
331          * Whether feature is enabled or disabled by default.
332          */
333         private final boolean _defaultState;
334 
335         private final int _mask;
336 
337         /**
338          * Method that calculates bit set (flags) of all features that
339          * are enabled by default.
340          */
collectDefaults()341         public static int collectDefaults()
342         {
343             int flags = 0;
344             for (Feature f : values()) {
345                 if (f.enabledByDefault()) {
346                     flags |= f.getMask();
347                 }
348             }
349             return flags;
350         }
351 
Feature(boolean defaultState)352         private Feature(boolean defaultState) {
353             _mask = (1 << ordinal());
354             _defaultState = defaultState;
355         }
356 
enabledByDefault()357         public boolean enabledByDefault() { return _defaultState; }
358 
359         /**
360          * @since 2.3
361          */
enabledIn(int flags)362         public boolean enabledIn(int flags) { return (flags & _mask) != 0; }
363 
getMask()364         public int getMask() { return _mask; }
365     }
366 
367     /*
368     /**********************************************************
369     /* Minimal configuration state
370     /**********************************************************
371      */
372 
373     /**
374      * Bit flag composed of bits that indicate which
375      * {@link com.fasterxml.jackson.core.JsonParser.Feature}s
376      * are enabled.
377      */
378     protected int _features;
379 
380     /**
381      * Optional container that holds the request payload which will be displayed on JSON parsing error.
382      *
383      * @since 2.8
384      */
385     protected transient RequestPayload _requestPayload;
386 
387     /*
388     /**********************************************************
389     /* Construction, configuration, initialization
390     /**********************************************************
391      */
392 
JsonParser()393     protected JsonParser() { }
JsonParser(int features)394     protected JsonParser(int features) { _features = features; }
395 
396     /**
397      * Accessor for {@link ObjectCodec} associated with this
398      * parser, if any. Codec is used by {@link #readValueAs(Class)}
399      * method (and its variants).
400      */
getCodec()401     public abstract ObjectCodec getCodec();
402 
403     /**
404      * Setter that allows defining {@link ObjectCodec} associated with this
405      * parser, if any. Codec is used by {@link #readValueAs(Class)}
406      * method (and its variants).
407      */
setCodec(ObjectCodec c)408     public abstract void setCodec(ObjectCodec c);
409 
410     /**
411      * Method that can be used to get access to object that is used
412      * to access input being parsed; this is usually either
413      * {@link InputStream} or {@link Reader}, depending on what
414      * parser was constructed with.
415      * Note that returned value may be null in some cases; including
416      * case where parser implementation does not want to exposed raw
417      * source to caller.
418      * In cases where input has been decorated, object returned here
419      * is the decorated version; this allows some level of interaction
420      * between users of parser and decorator object.
421      *<p>
422      * In general use of this accessor should be considered as
423      * "last effort", i.e. only used if no other mechanism is applicable.
424      */
getInputSource()425     public Object getInputSource() { return null; }
426 
427     /**
428      * Helper method, usually equivalent to:
429      *<code>
430      *   getParsingContext().getCurrentValue();
431      *</code>
432      *<p>
433      * Note that "current value" is NOT populated (or used) by Streaming parser;
434      * it is only used by higher-level data-binding functionality.
435      * The reason it is included here is that it can be stored and accessed hierarchically,
436      * and gets passed through data-binding.
437      *
438      * @since 2.5
439      */
getCurrentValue()440     public Object getCurrentValue() {
441         JsonStreamContext ctxt = getParsingContext();
442         return (ctxt == null) ? null : ctxt.getCurrentValue();
443     }
444 
445     /**
446      * Helper method, usually equivalent to:
447      *<code>
448      *   getParsingContext().setCurrentValue(v);
449      *</code>
450      *
451      * @since 2.5
452      */
setCurrentValue(Object v)453     public void setCurrentValue(Object v) {
454         JsonStreamContext ctxt = getParsingContext();
455         if (ctxt != null) {
456             ctxt.setCurrentValue(v);
457         }
458     }
459 
460     /**
461      * Sets the payload to be passed if {@link JsonParseException} is thrown.
462      *
463      * @since 2.8
464      */
setRequestPayloadOnError(RequestPayload payload)465     public void setRequestPayloadOnError(RequestPayload payload) {
466         _requestPayload = payload;
467     }
468 
469     /**
470      * Sets the byte[] request payload and the charset
471      *
472      * @since 2.8
473      */
setRequestPayloadOnError(byte[] payload, String charset)474      public void setRequestPayloadOnError(byte[] payload, String charset) {
475          _requestPayload = (payload == null) ? null : new RequestPayload(payload, charset);
476      }
477 
478      /**
479      * Sets the String request payload
480      *
481      * @since 2.8
482      */
setRequestPayloadOnError(String payload)483     public void setRequestPayloadOnError(String payload) {
484         _requestPayload = (payload == null) ? null : new RequestPayload(payload);
485     }
486 
487     /*
488     /**********************************************************
489     /* Format support
490     /**********************************************************
491      */
492 
493     /**
494      * Method to call to make this parser use specified schema. Method must
495      * be called before trying to parse any content, right after parser instance
496      * has been created.
497      * Note that not all parsers support schemas; and those that do usually only
498      * accept specific types of schemas: ones defined for data format parser can read.
499      *<p>
500      * If parser does not support specified schema, {@link UnsupportedOperationException}
501      * is thrown.
502      *
503      * @param schema Schema to use
504      *
505      * @throws UnsupportedOperationException if parser does not support schema
506      */
setSchema(FormatSchema schema)507     public void setSchema(FormatSchema schema) {
508         throw new UnsupportedOperationException("Parser of type "+getClass().getName()+" does not support schema of type '"
509                 +schema.getSchemaType()+"'");
510     }
511 
512     /**
513      * Method for accessing Schema that this parser uses, if any.
514      * Default implementation returns null.
515      *
516      * @since 2.1
517      */
getSchema()518     public FormatSchema getSchema() { return null; }
519 
520     /**
521      * Method that can be used to verify that given schema can be used with
522      * this parser (using {@link #setSchema}).
523      *
524      * @param schema Schema to check
525      *
526      * @return True if this parser can use given schema; false if not
527      */
canUseSchema(FormatSchema schema)528     public boolean canUseSchema(FormatSchema schema) { return false; }
529 
530     /*
531     /**********************************************************
532     /* Capability introspection
533     /**********************************************************
534      */
535 
536     /**
537      * Method that can be called to determine if a custom
538      * {@link ObjectCodec} is needed for binding data parsed
539      * using {@link JsonParser} constructed by this factory
540      * (which typically also implies the same for serialization
541      * with {@link JsonGenerator}).
542      *
543      * @return True if custom codec is needed with parsers and
544      *   generators created by this factory; false if a general
545      *   {@link ObjectCodec} is enough
546      *
547      * @since 2.1
548      */
requiresCustomCodec()549     public boolean requiresCustomCodec() { return false;}
550 
551     /**
552      * Method that can be called to determine if this parser instance
553      * uses non-blocking ("asynchronous") input access for decoding or not.
554      * Access mode is determined by earlier calls via {@link JsonFactory};
555      * it may not be changed after construction.
556      *<p>
557      * If non-blocking decoding is (@code true}, it is possible to call
558      * {@link #getNonBlockingInputFeeder()} to obtain object to use
559      * for feeding input; otherwise (<code>false</code> returned)
560      * input is read by blocking
561      *
562      * @since 2.9
563      */
canParseAsync()564     public boolean canParseAsync() { return false; }
565 
566     /**
567      * Method that will either return a feeder instance (if parser uses
568      * non-blocking, aka asynchronous access); or <code>null</code> for
569      * parsers that use blocking I/O.
570      *
571      * @since 2.9
572      */
getNonBlockingInputFeeder()573     public NonBlockingInputFeeder getNonBlockingInputFeeder() {
574         return null;
575     }
576 
577     /**
578      * Accessor for getting metadata on capabilities of this parser, based on
579      * underlying data format being read (directly or indirectly).
580      *
581      * @return Set of read capabilities for content to read via this parser
582      *
583      * @since 2.12
584      */
getReadCapabilities()585     public JacksonFeatureSet<StreamReadCapability> getReadCapabilities() {
586         return DEFAULT_READ_CAPABILITIES;
587     }
588 
589     /*
590     /**********************************************************
591     /* Versioned
592     /**********************************************************
593      */
594 
595     /**
596      * Accessor for getting version of the core package, given a parser instance.
597      * Left for sub-classes to implement.
598      */
599     @Override
version()600     public abstract Version version();
601 
602     /*
603     /**********************************************************
604     /* Closeable implementation
605     /**********************************************************
606      */
607 
608     /**
609      * Closes the parser so that no further iteration or data access
610      * can be made; will also close the underlying input source
611      * if parser either <b>owns</b> the input source, or feature
612      * {@link Feature#AUTO_CLOSE_SOURCE} is enabled.
613      * Whether parser owns the input source depends on factory
614      * method that was used to construct instance (so check
615      * {@link com.fasterxml.jackson.core.JsonFactory} for details,
616      * but the general
617      * idea is that if caller passes in closable resource (such
618      * as {@link InputStream} or {@link Reader}) parser does NOT
619      * own the source; but if it passes a reference (such as
620      * {@link java.io.File} or {@link java.net.URL} and creates
621      * stream or reader it does own them.
622      */
623     @Override
close()624     public abstract void close() throws IOException;
625 
626     /**
627      * Method that can be called to determine whether this parser
628      * is closed or not. If it is closed, no new tokens can be
629      * retrieved by calling {@link #nextToken} (and the underlying
630      * stream may be closed). Closing may be due to an explicit
631      * call to {@link #close} or because parser has encountered
632      * end of input.
633      */
isClosed()634     public abstract boolean isClosed();
635 
636     /*
637     /**********************************************************
638     /* Public API, simple location, context accessors
639     /**********************************************************
640      */
641 
642     /**
643      * Method that can be used to access current parsing context reader
644      * is in. There are 3 different types: root, array and object contexts,
645      * with slightly different available information. Contexts are
646      * hierarchically nested, and can be used for example for figuring
647      * out part of the input document that correspond to specific
648      * array or object (for highlighting purposes, or error reporting).
649      * Contexts can also be used for simple xpath-like matching of
650      * input, if so desired.
651      */
getParsingContext()652     public abstract JsonStreamContext getParsingContext();
653 
654     /**
655      * Method that return the <b>starting</b> location of the current
656      * token; that is, position of the first character from input
657      * that starts the current token.
658      */
getTokenLocation()659     public abstract JsonLocation getTokenLocation();
660 
661     /**
662      * Method that returns location of the last processed character;
663      * usually for error reporting purposes.
664      */
getCurrentLocation()665     public abstract JsonLocation getCurrentLocation();
666 
667     /*
668     /**********************************************************
669     /* Buffer handling
670     /**********************************************************
671      */
672 
673     /**
674      * Method that can be called to push back any content that
675      * has been read but not consumed by the parser. This is usually
676      * done after reading all content of interest using parser.
677      * Content is released by writing it to given stream if possible;
678      * if underlying input is byte-based it can released, if not (char-based)
679      * it can not.
680      *
681      * @return -1 if the underlying content source is not byte based
682      *    (that is, input can not be sent to {@link OutputStream};
683      *    otherwise number of bytes released (0 if there was nothing to release)
684      *
685      * @throws IOException if write to stream threw exception
686      */
releaseBuffered(OutputStream out)687     public int releaseBuffered(OutputStream out) throws IOException {
688         return -1;
689     }
690 
691     /**
692      * Method that can be called to push back any content that
693      * has been read but not consumed by the parser.
694      * This is usually
695      * done after reading all content of interest using parser.
696      * Content is released by writing it to given writer if possible;
697      * if underlying input is char-based it can released, if not (byte-based)
698      * it can not.
699      *
700      * @return -1 if the underlying content source is not char-based
701      *    (that is, input can not be sent to {@link Writer};
702      *    otherwise number of chars released (0 if there was nothing to release)
703      *
704      * @throws IOException if write using Writer threw exception
705      */
releaseBuffered(Writer w)706     public int releaseBuffered(Writer w) throws IOException { return -1; }
707 
708     /*
709     /***************************************************
710     /* Public API, configuration
711     /***************************************************
712      */
713 
714     /**
715      * Method for enabling specified parser feature
716      * (check {@link Feature} for list of features)
717      */
enable(Feature f)718     public JsonParser enable(Feature f) {
719         _features |= f.getMask();
720         return this;
721     }
722 
723     /**
724      * Method for disabling specified  feature
725      * (check {@link Feature} for list of features)
726      */
disable(Feature f)727     public JsonParser disable(Feature f) {
728         _features &= ~f.getMask();
729         return this;
730     }
731 
732     /**
733      * Method for enabling or disabling specified feature
734      * (check {@link Feature} for list of features)
735      */
configure(Feature f, boolean state)736     public JsonParser configure(Feature f, boolean state) {
737         if (state) enable(f); else disable(f);
738         return this;
739     }
740 
741     /**
742      * Method for checking whether specified {@link Feature} is enabled.
743      */
isEnabled(Feature f)744     public boolean isEnabled(Feature f) { return f.enabledIn(_features); }
745 
746     /**
747      * Method for checking whether specified {@link Feature} is enabled.
748      *
749      * @since 2.10
750      */
isEnabled(StreamReadFeature f)751     public boolean isEnabled(StreamReadFeature f) { return f.mappedFeature().enabledIn(_features); }
752 
753     /**
754      * Bulk access method for getting state of all standard {@link Feature}s.
755      *
756      * @return Bit mask that defines current states of all standard {@link Feature}s.
757      *
758      * @since 2.3
759      */
getFeatureMask()760     public int getFeatureMask() { return _features; }
761 
762     /**
763      * Bulk set method for (re)setting states of all standard {@link Feature}s
764      *
765      * @return This parser object, to allow chaining of calls
766      *
767      * @since 2.3
768      *
769      * @deprecated Since 2.7, use {@link #overrideStdFeatures(int, int)} instead
770      */
771     @Deprecated
setFeatureMask(int mask)772     public JsonParser setFeatureMask(int mask) {
773         _features = mask;
774         return this;
775     }
776 
777     /**
778      * Bulk set method for (re)setting states of features specified by <code>mask</code>.
779      * Functionally equivalent to
780      *<code>
781      *    int oldState = getFeatureMask();
782      *    int newState = (oldState &amp; ~mask) | (values &amp; mask);
783      *    setFeatureMask(newState);
784      *</code>
785      * but preferred as this lets caller more efficiently specify actual changes made.
786      *
787      * @param values Bit mask of set/clear state for features to change
788      * @param mask Bit mask of features to change
789      *
790      * @since 2.6
791      */
overrideStdFeatures(int values, int mask)792     public JsonParser overrideStdFeatures(int values, int mask) {
793         int newState = (_features & ~mask) | (values & mask);
794         return setFeatureMask(newState);
795     }
796 
797     /**
798      * Bulk access method for getting state of all {@link FormatFeature}s, format-specific
799      * on/off configuration settings.
800      *
801      * @return Bit mask that defines current states of all standard {@link FormatFeature}s.
802      *
803      * @since 2.6
804      */
getFormatFeatures()805     public int getFormatFeatures() {
806         return 0;
807     }
808 
809     /**
810      * Bulk set method for (re)setting states of {@link FormatFeature}s,
811      * by specifying values (set / clear) along with a mask, to determine
812      * which features to change, if any.
813      *<p>
814      * Default implementation will simply throw an exception to indicate that
815      * the generator implementation does not support any {@link FormatFeature}s.
816      *
817      * @param values Bit mask of set/clear state for features to change
818      * @param mask Bit mask of features to change
819      *
820      * @since 2.6
821      */
overrideFormatFeatures(int values, int mask)822     public JsonParser overrideFormatFeatures(int values, int mask) {
823         // 08-Oct-2018, tatu: For 2.10 we actually do get `JsonReadFeature`s, although they
824         //    are (for 2.x only, not for 3.x) mapper to legacy settings. So do not freak out:
825 //        throw new IllegalArgumentException("No FormatFeatures defined for parser of type "+getClass().getName());
826         return this;
827     }
828 
829     /*
830     /**********************************************************
831     /* Public API, traversal
832     /**********************************************************
833      */
834 
835     /**
836      * Main iteration method, which will advance stream enough
837      * to determine type of the next token, if any. If none
838      * remaining (stream has no content other than possible
839      * white space before ending), null will be returned.
840      *
841      * @return Next token from the stream, if any found, or null
842      *   to indicate end-of-input
843      */
nextToken()844     public abstract JsonToken nextToken() throws IOException;
845 
846     /**
847      * Iteration method that will advance stream enough
848      * to determine type of the next token that is a value type
849      * (including JSON Array and Object start/end markers).
850      * Or put another way, nextToken() will be called once,
851      * and if {@link JsonToken#FIELD_NAME} is returned, another
852      * time to get the value for the field.
853      * Method is most useful for iterating over value entries
854      * of JSON objects; field name will still be available
855      * by calling {@link #getCurrentName} when parser points to
856      * the value.
857      *
858      * @return Next non-field-name token from the stream, if any found,
859      *   or null to indicate end-of-input (or, for non-blocking
860      *   parsers, {@link JsonToken#NOT_AVAILABLE} if no tokens were
861      *   available yet)
862      */
nextValue()863     public abstract JsonToken nextValue() throws IOException;
864 
865     /**
866      * Method that fetches next token (as if calling {@link #nextToken}) and
867      * verifies whether it is {@link JsonToken#FIELD_NAME} with specified name
868      * and returns result of that comparison.
869      * It is functionally equivalent to:
870      *<pre>
871      *  return (nextToken() == JsonToken.FIELD_NAME) &amp;&amp; str.getValue().equals(getCurrentName());
872      *</pre>
873      * but may be faster for parser to verify, and can therefore be used if caller
874      * expects to get such a property name from input next.
875      *
876      * @param str Property name to compare next token to (if next token is
877      *   <code>JsonToken.FIELD_NAME</code>)
878      */
nextFieldName(SerializableString str)879     public boolean nextFieldName(SerializableString str) throws IOException {
880         return (nextToken() == JsonToken.FIELD_NAME) && str.getValue().equals(getCurrentName());
881     }
882 
883     /**
884      * Method that fetches next token (as if calling {@link #nextToken}) and
885      * verifies whether it is {@link JsonToken#FIELD_NAME}; if it is,
886      * returns same as {@link #getCurrentName()}, otherwise null.
887      *
888      * @since 2.5
889      */
nextFieldName()890     public String nextFieldName() throws IOException {
891         return (nextToken() == JsonToken.FIELD_NAME) ? getCurrentName() : null;
892     }
893 
894     /**
895      * Method that fetches next token (as if calling {@link #nextToken}) and
896      * if it is {@link JsonToken#VALUE_STRING} returns contained String value;
897      * otherwise returns null.
898      * It is functionally equivalent to:
899      *<pre>
900      *  return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null;
901      *</pre>
902      * but may be faster for parser to process, and can therefore be used if caller
903      * expects to get a String value next from input.
904      */
nextTextValue()905     public String nextTextValue() throws IOException {
906         return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null;
907     }
908 
909     /**
910      * Method that fetches next token (as if calling {@link #nextToken}) and
911      * if it is {@link JsonToken#VALUE_NUMBER_INT} returns 32-bit int value;
912      * otherwise returns specified default value
913      * It is functionally equivalent to:
914      *<pre>
915      *  return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue;
916      *</pre>
917      * but may be faster for parser to process, and can therefore be used if caller
918      * expects to get an int value next from input.
919      */
nextIntValue(int defaultValue)920     public int nextIntValue(int defaultValue) throws IOException {
921         return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue;
922     }
923 
924     /**
925      * Method that fetches next token (as if calling {@link #nextToken}) and
926      * if it is {@link JsonToken#VALUE_NUMBER_INT} returns 64-bit long value;
927      * otherwise returns specified default value
928      * It is functionally equivalent to:
929      *<pre>
930      *  return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue;
931      *</pre>
932      * but may be faster for parser to process, and can therefore be used if caller
933      * expects to get a long value next from input.
934      */
nextLongValue(long defaultValue)935     public long nextLongValue(long defaultValue) throws IOException {
936         return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue;
937     }
938 
939     /**
940      * Method that fetches next token (as if calling {@link #nextToken}) and
941      * if it is {@link JsonToken#VALUE_TRUE} or {@link JsonToken#VALUE_FALSE}
942      * returns matching Boolean value; otherwise return null.
943      * It is functionally equivalent to:
944      *<pre>
945      *  JsonToken t = nextToken();
946      *  if (t == JsonToken.VALUE_TRUE) return Boolean.TRUE;
947      *  if (t == JsonToken.VALUE_FALSE) return Boolean.FALSE;
948      *  return null;
949      *</pre>
950      * but may be faster for parser to process, and can therefore be used if caller
951      * expects to get a Boolean value next from input.
952      */
nextBooleanValue()953     public Boolean nextBooleanValue() throws IOException {
954         JsonToken t = nextToken();
955         if (t == JsonToken.VALUE_TRUE) { return Boolean.TRUE; }
956         if (t == JsonToken.VALUE_FALSE) { return Boolean.FALSE; }
957         return null;
958     }
959 
960     /**
961      * Method that will skip all child tokens of an array or
962      * object token that the parser currently points to,
963      * iff stream points to
964      * {@link JsonToken#START_OBJECT} or {@link JsonToken#START_ARRAY}.
965      * If not, it will do nothing.
966      * After skipping, stream will point to <b>matching</b>
967      * {@link JsonToken#END_OBJECT} or {@link JsonToken#END_ARRAY}
968      * (possibly skipping nested pairs of START/END OBJECT/ARRAY tokens
969      * as well as value tokens).
970      * The idea is that after calling this method, application
971      * will call {@link #nextToken} to point to the next
972      * available token, if any.
973      */
skipChildren()974     public abstract JsonParser skipChildren() throws IOException;
975 
976     /**
977      * Method that may be used to force full handling of the current token
978      * so that even if lazy processing is enabled, the whole contents are
979      * read for possible retrieval. This is usually used to ensure that
980      * the token end location is available, as well as token contents
981      * (similar to what calling, say {@link #getTextCharacters()}, would
982      * achieve).
983      *<p>
984      * Note that for many dataformat implementations this method
985      * will not do anything; this is the default implementation unless
986      * overridden by sub-classes.
987      *
988      * @since 2.8
989      */
finishToken()990     public void finishToken() throws IOException {
991         ; // nothing
992     }
993 
994     /*
995     /**********************************************************
996     /* Public API, simple token id/type access
997     /**********************************************************
998      */
999 
1000     /**
1001      * Accessor to find which token parser currently points to, if any;
1002      * null will be returned if none.
1003      * If return value is non-null, data associated with the token
1004      * is available via other accessor methods.
1005      *
1006      * @return Type of the token this parser currently points to,
1007      *   if any: null before any tokens have been read, and
1008      *   after end-of-input has been encountered, as well as
1009      *   if the current token has been explicitly cleared.
1010      *
1011      * @since 2.8
1012      */
currentToken()1013     public JsonToken currentToken() {
1014         return getCurrentToken();
1015     }
1016 
1017     /**
1018      * Method similar to {@link #getCurrentToken()} but that returns an
1019      * <code>int</code> instead of {@link JsonToken} (enum value).
1020      *<p>
1021      * Use of int directly is typically more efficient on switch statements,
1022      * so this method may be useful when building low-overhead codecs.
1023      * Note, however, that effect may not be big enough to matter: make sure
1024      * to profile performance before deciding to use this method.
1025      *
1026      * @since 2.8
1027      *
1028      * @return <code>int</code> matching one of constants from {@link JsonTokenId}.
1029      */
currentTokenId()1030     public int currentTokenId() {
1031         return getCurrentTokenId();
1032     }
1033 
1034     /**
1035      * Alias for {@link #currentToken()}, may be deprecated sometime after
1036      * Jackson 2.12 (will be removed from 3.0).
1037      */
getCurrentToken()1038     public abstract JsonToken getCurrentToken();
1039 
1040     /**
1041      * Alias for {@link #currentTokenId()}.
1042      *
1043      * @deprecated Since 2.12 use {@link #currentTokenId} instead
1044      */
1045     @Deprecated
getCurrentTokenId()1046     public abstract int getCurrentTokenId();
1047 
1048     /**
1049      * Method for checking whether parser currently points to
1050      * a token (and data for that token is available).
1051      * Equivalent to check for <code>parser.getCurrentToken() != null</code>.
1052      *
1053      * @return True if the parser just returned a valid
1054      *   token via {@link #nextToken}; false otherwise (parser
1055      *   was just constructed, encountered end-of-input
1056      *   and returned null from {@link #nextToken}, or the token
1057      *   has been consumed)
1058      */
hasCurrentToken()1059     public abstract boolean hasCurrentToken();
1060 
1061     /**
1062      * Method that is functionally equivalent to:
1063      *<code>
1064      *  return currentTokenId() == id
1065      *</code>
1066      * but may be more efficiently implemented.
1067      *<p>
1068      * Note that no traversal or conversion is performed; so in some
1069      * cases calling method like {@link #isExpectedStartArrayToken()}
1070      * is necessary instead.
1071      *
1072      * @since 2.5
1073      */
hasTokenId(int id)1074     public abstract boolean hasTokenId(int id);
1075 
1076     /**
1077      * Method that is functionally equivalent to:
1078      *<code>
1079      *  return currentToken() == t
1080      *</code>
1081      * but may be more efficiently implemented.
1082      *<p>
1083      * Note that no traversal or conversion is performed; so in some
1084      * cases calling method like {@link #isExpectedStartArrayToken()}
1085      * is necessary instead.
1086      *
1087      * @since 2.6
1088      */
hasToken(JsonToken t)1089     public abstract boolean hasToken(JsonToken t);
1090 
1091     /**
1092      * Specialized accessor that can be used to verify that the current
1093      * token indicates start array (usually meaning that current token
1094      * is {@link JsonToken#START_ARRAY}) when start array is expected.
1095      * For some specialized parsers this can return true for other cases
1096      * as well; this is usually done to emulate arrays in cases underlying
1097      * format is ambiguous (XML, for example, has no format-level difference
1098      * between Objects and Arrays; it just has elements).
1099      *<p>
1100      * Default implementation is equivalent to:
1101      *<pre>
1102      *   currentToken() == JsonToken.START_ARRAY
1103      *</pre>
1104      * but may be overridden by custom parser implementations.
1105      *
1106      * @return True if the current token can be considered as a
1107      *   start-array marker (such {@link JsonToken#START_ARRAY});
1108      *   false if not.
1109      */
isExpectedStartArrayToken()1110     public boolean isExpectedStartArrayToken() { return currentToken() == JsonToken.START_ARRAY; }
1111 
1112     /**
1113      * Similar to {@link #isExpectedStartArrayToken()}, but checks whether stream
1114      * currently points to {@link JsonToken#START_OBJECT}.
1115      *
1116      * @since 2.5
1117      */
isExpectedStartObjectToken()1118     public boolean isExpectedStartObjectToken() { return currentToken() == JsonToken.START_OBJECT; }
1119 
1120     /**
1121      * Similar to {@link #isExpectedStartArrayToken()}, but checks whether stream
1122      * currently points to {@link JsonToken#VALUE_NUMBER_INT}.
1123      *<p>
1124      * The initial use case is for XML backend to efficiently (attempt to) coerce
1125      * textual content into numbers.
1126      *
1127      * @since 2.12
1128      */
isExpectedNumberIntToken()1129     public boolean isExpectedNumberIntToken() { return currentToken() == JsonToken.VALUE_NUMBER_INT; }
1130 
1131     /**
1132      * Access for checking whether current token is a numeric value token, but
1133      * one that is of "not-a-number" (NaN) variety (including both "NaN" AND
1134      * positive/negative infinity!): not supported by all formats,
1135      * but often supported for {@link JsonToken#VALUE_NUMBER_FLOAT}.
1136      * NOTE: roughly equivalent to calling <code>!Double.isFinite()</code>
1137      * on value you would get from calling {@link #getDoubleValue()}.
1138      *
1139      * @since 2.9
1140      */
isNaN()1141     public boolean isNaN() throws IOException {
1142         return false;
1143     }
1144 
1145     /*
1146     /**********************************************************
1147     /* Public API, token state overrides
1148     /**********************************************************
1149      */
1150 
1151     /**
1152      * Method called to "consume" the current token by effectively
1153      * removing it so that {@link #hasCurrentToken} returns false, and
1154      * {@link #getCurrentToken} null).
1155      * Cleared token value can still be accessed by calling
1156      * {@link #getLastClearedToken} (if absolutely needed), but
1157      * usually isn't.
1158      *<p>
1159      * Method was added to be used by the optional data binder, since
1160      * it has to be able to consume last token used for binding (so that
1161      * it will not be used again).
1162      */
clearCurrentToken()1163     public abstract void clearCurrentToken();
1164 
1165     /**
1166      * Method that can be called to get the last token that was
1167      * cleared using {@link #clearCurrentToken}. This is not necessarily
1168      * the latest token read.
1169      * Will return null if no tokens have been cleared,
1170      * or if parser has been closed.
1171      */
getLastClearedToken()1172     public abstract JsonToken getLastClearedToken();
1173 
1174     /**
1175      * Method that can be used to change what is considered to be
1176      * the current (field) name.
1177      * May be needed to support non-JSON data formats or unusual binding
1178      * conventions; not needed for typical processing.
1179      *<p>
1180      * Note that use of this method should only be done as sort of last
1181      * resort, as it is a work-around for regular operation.
1182      *
1183      * @param name Name to use as the current name; may be null.
1184      */
overrideCurrentName(String name)1185     public abstract void overrideCurrentName(String name);
1186 
1187     /*
1188     /**********************************************************
1189     /* Public API, access to token information, text
1190     /**********************************************************
1191      */
1192 
1193     /**
1194      * Method that can be called to get the name associated with
1195      * the current token: for {@link JsonToken#FIELD_NAME}s it will
1196      * be the same as what {@link #getText} returns;
1197      * for field values it will be preceding field name;
1198      * and for others (array values, root-level values) null.
1199      */
getCurrentName()1200     public abstract String getCurrentName() throws IOException;
1201 
1202     // 15-Dec-2017, tatu: Forward-looking, added in 2.9.4 (and officially in 3.0)
1203     //   to smooth upgrading
currentName()1204     public String currentName() throws IOException {
1205         return getCurrentName();
1206     }
1207 
1208     /**
1209      * Method for accessing textual representation of the current token;
1210      * if no current token (before first call to {@link #nextToken}, or
1211      * after encountering end-of-input), returns null.
1212      * Method can be called for any token type.
1213      */
getText()1214     public abstract String getText() throws IOException;
1215 
1216     /**
1217      * Method to read the textual representation of the current token in chunks and
1218      * pass it to the given Writer.
1219      * Conceptually same as calling:
1220      *<pre>
1221      *  writer.write(parser.getText());
1222      *</pre>
1223      * but should typically be more efficient as longer content does need to
1224      * be combined into a single <code>String</code> to return, and write
1225      * can occur directly from intermediate buffers Jackson uses.
1226      *
1227      * @return The number of characters written to the Writer
1228      *
1229      * @since 2.8
1230      */
getText(Writer writer)1231     public int getText(Writer writer) throws IOException, UnsupportedOperationException
1232     {
1233         String str = getText();
1234         if (str == null) {
1235             return 0;
1236         }
1237         writer.write(str);
1238         return str.length();
1239     }
1240 
1241     /**
1242      * Method similar to {@link #getText}, but that will return
1243      * underlying (unmodifiable) character array that contains
1244      * textual value, instead of constructing a String object
1245      * to contain this information.
1246      * Note, however, that:
1247      *<ul>
1248      * <li>Textual contents are not guaranteed to start at
1249      *   index 0 (rather, call {@link #getTextOffset}) to
1250      *   know the actual offset
1251      *  </li>
1252      * <li>Length of textual contents may be less than the
1253      *  length of returned buffer: call {@link #getTextLength}
1254      *  for actual length of returned content.
1255      *  </li>
1256      * </ul>
1257      *<p>
1258      * Note that caller <b>MUST NOT</b> modify the returned
1259      * character array in any way -- doing so may corrupt
1260      * current parser state and render parser instance useless.
1261      *<p>
1262      * The only reason to call this method (over {@link #getText})
1263      * is to avoid construction of a String object (which
1264      * will make a copy of contents).
1265      */
getTextCharacters()1266     public abstract char[] getTextCharacters() throws IOException;
1267 
1268     /**
1269      * Accessor used with {@link #getTextCharacters}, to know length
1270      * of String stored in returned buffer.
1271      *
1272      * @return Number of characters within buffer returned
1273      *   by {@link #getTextCharacters} that are part of
1274      *   textual content of the current token.
1275      */
getTextLength()1276     public abstract int getTextLength() throws IOException;
1277 
1278     /**
1279      * Accessor used with {@link #getTextCharacters}, to know offset
1280      * of the first text content character within buffer.
1281      *
1282      * @return Offset of the first character within buffer returned
1283      *   by {@link #getTextCharacters} that is part of
1284      *   textual content of the current token.
1285      */
getTextOffset()1286     public abstract int getTextOffset() throws IOException;
1287 
1288     /**
1289      * Method that can be used to determine whether calling of
1290      * {@link #getTextCharacters} would be the most efficient
1291      * way to access textual content for the event parser currently
1292      * points to.
1293      *<p>
1294      * Default implementation simply returns false since only actual
1295      * implementation class has knowledge of its internal buffering
1296      * state.
1297      * Implementations are strongly encouraged to properly override
1298      * this method, to allow efficient copying of content by other
1299      * code.
1300      *
1301      * @return True if parser currently has character array that can
1302      *   be efficiently returned via {@link #getTextCharacters}; false
1303      *   means that it may or may not exist
1304      */
hasTextCharacters()1305     public abstract boolean hasTextCharacters();
1306 
1307     /*
1308     /**********************************************************
1309     /* Public API, access to token information, numeric
1310     /**********************************************************
1311      */
1312 
1313     /**
1314      * Generic number value accessor method that will work for
1315      * all kinds of numeric values. It will return the optimal
1316      * (simplest/smallest possible) wrapper object that can
1317      * express the numeric value just parsed.
1318      *
1319      * @return Numeric value of the current token in its most optimal
1320      *   representation
1321      *
1322      * @throws IOException Problem with access: {@link JsonParseException} if
1323      *    the current token is not numeric, or if decoding of the value fails
1324      *    (invalid format for numbers); plain {@link IOException} if underlying
1325      *    content read fails (possible if values are extracted lazily)
1326      */
getNumberValue()1327     public abstract Number getNumberValue() throws IOException;
1328 
1329     /**
1330      * Method similar to {@link #getNumberValue} with the difference that
1331      * for floating-point numbers value returned may be {@link BigDecimal}
1332      * if the underlying format does not store floating-point numbers using
1333      * native representation: for example, textual formats represent numbers
1334      * as Strings (which are 10-based), and conversion to {@link java.lang.Double}
1335      * is potentially lossy operation.
1336      *<p>
1337      * Default implementation simply returns {@link #getNumberValue()}
1338      *
1339      * @return Numeric value of the current token using most accurate representation
1340      *
1341      * @throws IOException Problem with access: {@link JsonParseException} if
1342      *    the current token is not numeric, or if decoding of the value fails
1343      *    (invalid format for numbers); plain {@link IOException} if underlying
1344      *    content read fails (possible if values are extracted lazily)
1345      *
1346      * @since 2.12
1347      */
getNumberValueExact()1348     public Number getNumberValueExact() throws IOException {
1349         return getNumberValue();
1350     }
1351 
1352     /**
1353      * If current token is of type
1354      * {@link JsonToken#VALUE_NUMBER_INT} or
1355      * {@link JsonToken#VALUE_NUMBER_FLOAT}, returns
1356      * one of {@link NumberType} constants; otherwise returns null.
1357      */
getNumberType()1358     public abstract NumberType getNumberType() throws IOException;
1359 
1360     /**
1361      * Numeric accessor that can be called when the current
1362      * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1363      * it can be expressed as a value of Java byte primitive type.
1364      * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1365      * if so, it is equivalent to calling {@link #getDoubleValue}
1366      * and then casting; except for possible overflow/underflow
1367      * exception.
1368      *<p>
1369      * Note: if the resulting integer value falls outside range of
1370      * Java byte, a {@link InputCoercionException}
1371      * will be thrown to indicate numeric overflow/underflow.
1372      */
getByteValue()1373     public byte getByteValue() throws IOException {
1374         int value = getIntValue();
1375         // So far so good: but does it fit?
1376         // [JACKSON-804]: Let's actually allow range of [-128, 255], as those are uniquely mapped
1377         //  (instead of just signed range of [-128, 127])
1378         if (value < MIN_BYTE_I || value > MAX_BYTE_I) {
1379             throw new InputCoercionException(this,
1380                     String.format("Numeric value (%s) out of range of Java byte", getText()),
1381                     JsonToken.VALUE_NUMBER_INT, Byte.TYPE);
1382         }
1383         return (byte) value;
1384     }
1385 
1386     /**
1387      * Numeric accessor that can be called when the current
1388      * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1389      * it can be expressed as a value of Java short primitive type.
1390      * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1391      * if so, it is equivalent to calling {@link #getDoubleValue}
1392      * and then casting; except for possible overflow/underflow
1393      * exception.
1394      *<p>
1395      * Note: if the resulting integer value falls outside range of
1396      * Java short, a {@link InputCoercionException}
1397      * will be thrown to indicate numeric overflow/underflow.
1398      */
getShortValue()1399     public short getShortValue() throws IOException
1400     {
1401         int value = getIntValue();
1402         if (value < MIN_SHORT_I || value > MAX_SHORT_I) {
1403             throw new InputCoercionException(this,
1404                     String.format("Numeric value (%s) out of range of Java short", getText()),
1405                     JsonToken.VALUE_NUMBER_INT, Short.TYPE);
1406         }
1407         return (short) value;
1408     }
1409 
1410     /**
1411      * Numeric accessor that can be called when the current
1412      * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1413      * it can be expressed as a value of Java int primitive type.
1414      * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1415      * if so, it is equivalent to calling {@link #getDoubleValue}
1416      * and then casting; except for possible overflow/underflow
1417      * exception.
1418      *<p>
1419      * Note: if the resulting integer value falls outside range of
1420      * Java int, a {@link InputCoercionException}
1421      * may be thrown to indicate numeric overflow/underflow.
1422      */
getIntValue()1423     public abstract int getIntValue() throws IOException;
1424 
1425     /**
1426      * Numeric accessor that can be called when the current
1427      * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1428      * it can be expressed as a Java long primitive type.
1429      * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1430      * if so, it is equivalent to calling {@link #getDoubleValue}
1431      * and then casting to int; except for possible overflow/underflow
1432      * exception.
1433      *<p>
1434      * Note: if the token is an integer, but its value falls
1435      * outside of range of Java long, a {@link InputCoercionException}
1436      * may be thrown to indicate numeric overflow/underflow.
1437      */
getLongValue()1438     public abstract long getLongValue() throws IOException;
1439 
1440     /**
1441      * Numeric accessor that can be called when the current
1442      * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1443      * it can not be used as a Java long primitive type due to its
1444      * magnitude.
1445      * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1446      * if so, it is equivalent to calling {@link #getDecimalValue}
1447      * and then constructing a {@link BigInteger} from that value.
1448      */
getBigIntegerValue()1449     public abstract BigInteger getBigIntegerValue() throws IOException;
1450 
1451     /**
1452      * Numeric accessor that can be called when the current
1453      * token is of type {@link JsonToken#VALUE_NUMBER_FLOAT} and
1454      * it can be expressed as a Java float primitive type.
1455      * It can also be called for {@link JsonToken#VALUE_NUMBER_INT};
1456      * if so, it is equivalent to calling {@link #getLongValue}
1457      * and then casting; except for possible overflow/underflow
1458      * exception.
1459      *<p>
1460      * Note: if the value falls
1461      * outside of range of Java float, a {@link InputCoercionException}
1462      * will be thrown to indicate numeric overflow/underflow.
1463      */
getFloatValue()1464     public abstract float getFloatValue() throws IOException;
1465 
1466     /**
1467      * Numeric accessor that can be called when the current
1468      * token is of type {@link JsonToken#VALUE_NUMBER_FLOAT} and
1469      * it can be expressed as a Java double primitive type.
1470      * It can also be called for {@link JsonToken#VALUE_NUMBER_INT};
1471      * if so, it is equivalent to calling {@link #getLongValue}
1472      * and then casting; except for possible overflow/underflow
1473      * exception.
1474      *<p>
1475      * Note: if the value falls
1476      * outside of range of Java double, a {@link InputCoercionException}
1477      * will be thrown to indicate numeric overflow/underflow.
1478      */
getDoubleValue()1479     public abstract double getDoubleValue() throws IOException;
1480 
1481     /**
1482      * Numeric accessor that can be called when the current
1483      * token is of type {@link JsonToken#VALUE_NUMBER_FLOAT} or
1484      * {@link JsonToken#VALUE_NUMBER_INT}. No under/overflow exceptions
1485      * are ever thrown.
1486      */
getDecimalValue()1487     public abstract BigDecimal getDecimalValue() throws IOException;
1488 
1489     /*
1490     /**********************************************************
1491     /* Public API, access to token information, other
1492     /**********************************************************
1493      */
1494 
1495     /**
1496      * Convenience accessor that can be called when the current
1497      * token is {@link JsonToken#VALUE_TRUE} or
1498      * {@link JsonToken#VALUE_FALSE}.
1499      *<p>
1500      * Note: if the token is not of above-mentioned boolean types,
1501  an integer, but its value falls
1502      * outside of range of Java long, a {@link JsonParseException}
1503      * may be thrown to indicate numeric overflow/underflow.
1504      */
getBooleanValue()1505     public boolean getBooleanValue() throws IOException {
1506         JsonToken t = currentToken();
1507         if (t == JsonToken.VALUE_TRUE) return true;
1508         if (t == JsonToken.VALUE_FALSE) return false;
1509         throw new JsonParseException(this,
1510             String.format("Current token (%s) not of boolean type", t))
1511                 .withRequestPayload(_requestPayload);
1512     }
1513 
1514     /**
1515      * Accessor that can be called if (and only if) the current token
1516      * is {@link JsonToken#VALUE_EMBEDDED_OBJECT}. For other token types,
1517      * null is returned.
1518      *<p>
1519      * Note: only some specialized parser implementations support
1520      * embedding of objects (usually ones that are facades on top
1521      * of non-streaming sources, such as object trees). One exception
1522      * is access to binary content (whether via base64 encoding or not)
1523      * which typically is accessible using this method, as well as
1524      * {@link #getBinaryValue()}.
1525      */
getEmbeddedObject()1526     public Object getEmbeddedObject() throws IOException { return null; }
1527 
1528     /*
1529     /**********************************************************
1530     /* Public API, access to token information, binary
1531     /**********************************************************
1532      */
1533 
1534     /**
1535      * Method that can be used to read (and consume -- results
1536      * may not be accessible using other methods after the call)
1537      * base64-encoded binary data
1538      * included in the current textual JSON value.
1539      * It works similar to getting String value via {@link #getText}
1540      * and decoding result (except for decoding part),
1541      * but should be significantly more performant.
1542      *<p>
1543      * Note that non-decoded textual contents of the current token
1544      * are not guaranteed to be accessible after this method
1545      * is called. Current implementation, for example, clears up
1546      * textual content during decoding.
1547      * Decoded binary content, however, will be retained until
1548      * parser is advanced to the next event.
1549      *
1550      * @param bv Expected variant of base64 encoded
1551      *   content (see {@link Base64Variants} for definitions
1552      *   of "standard" variants).
1553      *
1554      * @return Decoded binary data
1555      */
getBinaryValue(Base64Variant bv)1556     public abstract byte[] getBinaryValue(Base64Variant bv) throws IOException;
1557 
1558     /**
1559      * Convenience alternative to {@link #getBinaryValue(Base64Variant)}
1560      * that defaults to using
1561      * {@link Base64Variants#getDefaultVariant} as the default encoding.
1562      *
1563      * @return Decoded binary data
1564      */
getBinaryValue()1565     public byte[] getBinaryValue() throws IOException {
1566         return getBinaryValue(Base64Variants.getDefaultVariant());
1567     }
1568 
1569     /**
1570      * Method that can be used as an alternative to {@link #getBigIntegerValue()},
1571      * especially when value can be large. The main difference (beyond method
1572      * of returning content using {@link OutputStream} instead of as byte array)
1573      * is that content will NOT remain accessible after method returns: any content
1574      * processed will be consumed and is not buffered in any way. If caller needs
1575      * buffering, it has to implement it.
1576      *
1577      * @param out Output stream to use for passing decoded binary data
1578      *
1579      * @return Number of bytes that were decoded and written via {@link OutputStream}
1580      *
1581      * @since 2.1
1582      */
readBinaryValue(OutputStream out)1583     public int readBinaryValue(OutputStream out) throws IOException {
1584         return readBinaryValue(Base64Variants.getDefaultVariant(), out);
1585     }
1586 
1587     /**
1588      * Similar to {@link #readBinaryValue(OutputStream)} but allows explicitly
1589      * specifying base64 variant to use.
1590      *
1591      * @param bv base64 variant to use
1592      * @param out Output stream to use for passing decoded binary data
1593      *
1594      * @return Number of bytes that were decoded and written via {@link OutputStream}
1595      *
1596      * @since 2.1
1597      */
readBinaryValue(Base64Variant bv, OutputStream out)1598     public int readBinaryValue(Base64Variant bv, OutputStream out) throws IOException {
1599         _reportUnsupportedOperation();
1600         return 0; // never gets here
1601     }
1602 
1603     /*
1604     /**********************************************************
1605     /* Public API, access to token information, coercion/conversion
1606     /**********************************************************
1607      */
1608 
1609     /**
1610      * Method that will try to convert value of current token to a
1611      * <b>int</b>.
1612      * Numbers are coerced using default Java rules; booleans convert to 0 (false)
1613      * and 1 (true), and Strings are parsed using default Java language integer
1614      * parsing rules.
1615      *<p>
1616      * If representation can not be converted to an int (including structured type
1617      * markers like start/end Object/Array)
1618      * default value of <b>0</b> will be returned; no exceptions are thrown.
1619      */
getValueAsInt()1620     public int getValueAsInt() throws IOException {
1621         return getValueAsInt(0);
1622     }
1623 
1624     /**
1625      * Method that will try to convert value of current token to a
1626      * <b>int</b>.
1627      * Numbers are coerced using default Java rules; booleans convert to 0 (false)
1628      * and 1 (true), and Strings are parsed using default Java language integer
1629      * parsing rules.
1630      *<p>
1631      * If representation can not be converted to an int (including structured type
1632      * markers like start/end Object/Array)
1633      * specified <b>def</b> will be returned; no exceptions are thrown.
1634      */
getValueAsInt(int def)1635     public int getValueAsInt(int def) throws IOException { return def; }
1636 
1637     /**
1638      * Method that will try to convert value of current token to a
1639      * <b>long</b>.
1640      * Numbers are coerced using default Java rules; booleans convert to 0 (false)
1641      * and 1 (true), and Strings are parsed using default Java language integer
1642      * parsing rules.
1643      *<p>
1644      * If representation can not be converted to a long (including structured type
1645      * markers like start/end Object/Array)
1646      * default value of <b>0L</b> will be returned; no exceptions are thrown.
1647      */
getValueAsLong()1648     public long getValueAsLong() throws IOException {
1649         return getValueAsLong(0);
1650     }
1651 
1652     /**
1653      * Method that will try to convert value of current token to a
1654      * <b>long</b>.
1655      * Numbers are coerced using default Java rules; booleans convert to 0 (false)
1656      * and 1 (true), and Strings are parsed using default Java language integer
1657      * parsing rules.
1658      *<p>
1659      * If representation can not be converted to a long (including structured type
1660      * markers like start/end Object/Array)
1661      * specified <b>def</b> will be returned; no exceptions are thrown.
1662      */
getValueAsLong(long def)1663     public long getValueAsLong(long def) throws IOException {
1664         return def;
1665     }
1666 
1667     /**
1668      * Method that will try to convert value of current token to a Java
1669      * <b>double</b>.
1670      * Numbers are coerced using default Java rules; booleans convert to 0.0 (false)
1671      * and 1.0 (true), and Strings are parsed using default Java language floating
1672      * point parsing rules.
1673      *<p>
1674      * If representation can not be converted to a double (including structured types
1675      * like Objects and Arrays),
1676      * default value of <b>0.0</b> will be returned; no exceptions are thrown.
1677      */
getValueAsDouble()1678     public double getValueAsDouble() throws IOException {
1679         return getValueAsDouble(0.0);
1680     }
1681 
1682     /**
1683      * Method that will try to convert value of current token to a
1684      * Java <b>double</b>.
1685      * Numbers are coerced using default Java rules; booleans convert to 0.0 (false)
1686      * and 1.0 (true), and Strings are parsed using default Java language floating
1687      * point parsing rules.
1688      *<p>
1689      * If representation can not be converted to a double (including structured types
1690      * like Objects and Arrays),
1691      * specified <b>def</b> will be returned; no exceptions are thrown.
1692      */
getValueAsDouble(double def)1693     public double getValueAsDouble(double def) throws IOException {
1694         return def;
1695     }
1696 
1697     /**
1698      * Method that will try to convert value of current token to a
1699      * <b>boolean</b>.
1700      * JSON booleans map naturally; integer numbers other than 0 map to true, and
1701      * 0 maps to false
1702      * and Strings 'true' and 'false' map to corresponding values.
1703      *<p>
1704      * If representation can not be converted to a boolean value (including structured types
1705      * like Objects and Arrays),
1706      * default value of <b>false</b> will be returned; no exceptions are thrown.
1707      */
getValueAsBoolean()1708     public boolean getValueAsBoolean() throws IOException {
1709         return getValueAsBoolean(false);
1710     }
1711 
1712     /**
1713      * Method that will try to convert value of current token to a
1714      * <b>boolean</b>.
1715      * JSON booleans map naturally; integer numbers other than 0 map to true, and
1716      * 0 maps to false
1717      * and Strings 'true' and 'false' map to corresponding values.
1718      *<p>
1719      * If representation can not be converted to a boolean value (including structured types
1720      * like Objects and Arrays),
1721      * specified <b>def</b> will be returned; no exceptions are thrown.
1722      */
getValueAsBoolean(boolean def)1723     public boolean getValueAsBoolean(boolean def) throws IOException {
1724         return def;
1725     }
1726 
1727     /**
1728      * Method that will try to convert value of current token to a
1729      * {@link java.lang.String}.
1730      * JSON Strings map naturally; scalar values get converted to
1731      * their textual representation.
1732      * If representation can not be converted to a String value (including structured types
1733      * like Objects and Arrays and null token), default value of
1734      * <b>null</b> will be returned; no exceptions are thrown.
1735      *
1736      * @since 2.1
1737      */
getValueAsString()1738     public String getValueAsString() throws IOException {
1739         return getValueAsString(null);
1740     }
1741 
1742     /**
1743      * Method that will try to convert value of current token to a
1744      * {@link java.lang.String}.
1745      * JSON Strings map naturally; scalar values get converted to
1746      * their textual representation.
1747      * If representation can not be converted to a String value (including structured types
1748      * like Objects and Arrays and null token), specified default value
1749      * will be returned; no exceptions are thrown.
1750      *
1751      * @since 2.1
1752      */
getValueAsString(String def)1753     public abstract String getValueAsString(String def) throws IOException;
1754 
1755     /*
1756     /**********************************************************
1757     /* Public API, Native Ids (type, object)
1758     /**********************************************************
1759      */
1760 
1761     /**
1762      * Introspection method that may be called to see if the underlying
1763      * data format supports some kind of Object Ids natively (many do not;
1764      * for example, JSON doesn't).
1765      *<p>
1766      * Default implementation returns true; overridden by data formats
1767      * that do support native Object Ids. Caller is expected to either
1768      * use a non-native notation (explicit property or such), or fail,
1769      * in case it can not use native object ids.
1770      *
1771      * @since 2.3
1772      */
canReadObjectId()1773     public boolean canReadObjectId() { return false; }
1774 
1775     /**
1776      * Introspection method that may be called to see if the underlying
1777      * data format supports some kind of Type Ids natively (many do not;
1778      * for example, JSON doesn't).
1779      *<p>
1780      * Default implementation returns true; overridden by data formats
1781      * that do support native Type Ids. Caller is expected to either
1782      * use a non-native notation (explicit property or such), or fail,
1783      * in case it can not use native type ids.
1784      *
1785      * @since 2.3
1786      */
canReadTypeId()1787     public boolean canReadTypeId() { return false; }
1788 
1789     /**
1790      * Method that can be called to check whether current token
1791      * (one that was just read) has an associated Object id, and if
1792      * so, return it.
1793      * Note that while typically caller should check with {@link #canReadObjectId}
1794      * first, it is not illegal to call this method even if that method returns
1795      * true; but if so, it will return null. This may be used to simplify calling
1796      * code.
1797      *<p>
1798      * Default implementation will simply return null.
1799      *
1800      * @since 2.3
1801      */
getObjectId()1802     public Object getObjectId() throws IOException { return null; }
1803 
1804     /**
1805      * Method that can be called to check whether current token
1806      * (one that was just read) has an associated type id, and if
1807      * so, return it.
1808      * Note that while typically caller should check with {@link #canReadTypeId}
1809      * first, it is not illegal to call this method even if that method returns
1810      * true; but if so, it will return null. This may be used to simplify calling
1811      * code.
1812      *<p>
1813      * Default implementation will simply return null.
1814      *
1815      * @since 2.3
1816      */
getTypeId()1817     public Object getTypeId() throws IOException { return null; }
1818 
1819     /*
1820     /**********************************************************
1821     /* Public API, optional data binding functionality
1822     /**********************************************************
1823      */
1824 
1825     /**
1826      * Method to deserialize JSON content into a non-container
1827      * type (it can be an array type, however): typically a bean, array
1828      * or a wrapper type (like {@link java.lang.Boolean}).
1829      * <b>Note</b>: method can only be called if the parser has
1830      * an object codec assigned; this is true for parsers constructed
1831      * by <code>MappingJsonFactory</code> (from "jackson-databind" jar)
1832      * but not for {@link JsonFactory} (unless its <code>setCodec</code>
1833      * method has been explicitly called).
1834      *<p>
1835      * This method may advance the event stream, for structured types
1836      * the current token will be the closing end marker (END_ARRAY,
1837      * END_OBJECT) of the bound structure. For non-structured Json types
1838      * (and for {@link JsonToken#VALUE_EMBEDDED_OBJECT})
1839      * stream is not advanced.
1840      *<p>
1841      * Note: this method should NOT be used if the result type is a
1842      * container ({@link java.util.Collection} or {@link java.util.Map}.
1843      * The reason is that due to type erasure, key and value types
1844      * can not be introspected when using this method.
1845      */
readValueAs(Class<T> valueType)1846     public <T> T readValueAs(Class<T> valueType) throws IOException {
1847         return _codec().readValue(this, valueType);
1848     }
1849 
1850     /**
1851      * Method to deserialize JSON content into a Java type, reference
1852      * to which is passed as argument. Type is passed using so-called
1853      * "super type token"
1854      * and specifically needs to be used if the root type is a
1855      * parameterized (generic) container type.
1856      * <b>Note</b>: method can only be called if the parser has
1857      * an object codec assigned; this is true for parsers constructed
1858      * by <code>MappingJsonFactory</code> (defined in 'jackson-databind' bundle)
1859      * but not for {@link JsonFactory} (unless its <code>setCodec</code>
1860      * method has been explicitly called).
1861      *<p>
1862      * This method may advance the event stream, for structured types
1863      * the current token will be the closing end marker (END_ARRAY,
1864      * END_OBJECT) of the bound structure. For non-structured Json types
1865      * (and for {@link JsonToken#VALUE_EMBEDDED_OBJECT})
1866      * stream is not advanced.
1867      */
1868     @SuppressWarnings("unchecked")
readValueAs(TypeReference<?> valueTypeRef)1869     public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException {
1870         return (T) _codec().readValue(this, valueTypeRef);
1871     }
1872 
1873     /**
1874      * Method for reading sequence of Objects from parser stream,
1875      * all with same specified value type.
1876      */
readValuesAs(Class<T> valueType)1877     public <T> Iterator<T> readValuesAs(Class<T> valueType) throws IOException {
1878         return _codec().readValues(this, valueType);
1879     }
1880 
1881     /**
1882      * Method for reading sequence of Objects from parser stream,
1883      * all with same specified value type.
1884      */
readValuesAs(TypeReference<T> valueTypeRef)1885     public <T> Iterator<T> readValuesAs(TypeReference<T> valueTypeRef) throws IOException {
1886         return _codec().readValues(this, valueTypeRef);
1887     }
1888 
1889     /**
1890      * Method to deserialize JSON content into equivalent "tree model",
1891      * represented by root {@link TreeNode} of resulting model.
1892      * For JSON Arrays it will an array node (with child nodes),
1893      * for objects object node (with child nodes), and for other types
1894      * matching leaf node type. Empty or whitespace documents are null.
1895      *
1896      * @return root of the document, or null if empty or whitespace.
1897      */
1898     @SuppressWarnings("unchecked")
readValueAsTree()1899     public <T extends TreeNode> T readValueAsTree() throws IOException {
1900         return (T) _codec().readTree(this);
1901     }
1902 
_codec()1903     protected ObjectCodec _codec() {
1904         ObjectCodec c = getCodec();
1905         if (c == null) {
1906             throw new IllegalStateException("No ObjectCodec defined for parser, needed for deserialization");
1907         }
1908         return c;
1909     }
1910 
1911     /*
1912     /**********************************************************
1913     /* Internal methods
1914     /**********************************************************
1915      */
1916 
1917     /**
1918      * Helper method for constructing {@link JsonParseException}s
1919      * based on current state of the parser
1920      */
_constructError(String msg)1921     protected JsonParseException _constructError(String msg) {
1922         return new JsonParseException(this, msg)
1923             .withRequestPayload(_requestPayload);
1924     }
1925 
1926     /**
1927      * Helper method to call for operations that are not supported by
1928      * parser implementation.
1929      *
1930      * @since 2.1
1931      */
_reportUnsupportedOperation()1932     protected void _reportUnsupportedOperation() {
1933         throw new UnsupportedOperationException("Operation not supported by parser of type "+getClass().getName());
1934     }
1935 }
1936