001/*
002 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003 *
004 * Copyright (c) 2011-2017 Oracle and/or its affiliates. All rights reserved.
005 *
006 * The contents of this file are subject to the terms of either the GNU
007 * General Public License Version 2 only ("GPL") or the Common Development
008 * and Distribution License("CDDL") (collectively, the "License").  You
009 * may not use this file except in compliance with the License.  You can
010 * obtain a copy of the License at
011 * https://oss.oracle.com/licenses/CDDL+GPL-1.1
012 * or LICENSE.txt.  See the License for the specific
013 * language governing permissions and limitations under the License.
014 *
015 * When distributing the software, include this License Header Notice in each
016 * file and include the License file at LICENSE.txt.
017 *
018 * GPL Classpath Exception:
019 * Oracle designates this particular file as subject to the "Classpath"
020 * exception as provided by Oracle in the GPL Version 2 section of the License
021 * file that accompanied this code.
022 *
023 * Modifications:
024 * If applicable, add the following below the License Header, with the fields
025 * enclosed by brackets [] replaced by your own identifying information:
026 * "Portions Copyright [year] [name of copyright owner]"
027 *
028 * Contributor(s):
029 * If you wish your version of this file to be governed by only the CDDL or
030 * only the GPL Version 2, indicate your decision by adding "[Contributor]
031 * elects to include this software in this distribution under the [CDDL or GPL
032 * Version 2] license."  If you don't indicate a single choice of license, a
033 * recipient has the option to distribute your version of this file under
034 * either the CDDL, the GPL Version 2 or to extend the choice of license to
035 * its licensees as provided above.  However, if you add GPL Version 2 code
036 * and therefore, elected the GPL Version 2 license, then the option applies
037 * only if the new code is made subject to such option by the copyright
038 * holder.
039 */
040
041package javax.json.stream;
042
043
044import java.io.Closeable;
045import java.math.BigDecimal;
046import java.util.stream.Stream;
047import java.util.Map;
048
049import javax.json.JsonValue;
050import javax.json.JsonObject;
051import javax.json.JsonArray;
052
053/**
054 * Provides forward, read-only access to JSON data in a streaming way. This
055 * is the most efficient way for reading JSON data.
056 *
057 * <EMBED CLASS='external-html' DATA-FILE-ID=LICENSE DATA-CIETName=JsonParser>
058 * 
059 * <BR /><BR />This is the only way to parse and process JSON data that are too big to be loaded in
060 * memory.
061 *
062 * <BR /><BR />The class {@link javax.json.Json} contains methods to create parsers from input
063 * sources ({@link java.io.InputStream} and {@link java.io.Reader}).
064 *
065 * <BR /><BR />The following example demonstrates how to create a parser from a string
066 * that contains an empty JSON array:
067 * 
068 * <BR /><DIV CLASS=SNIP>{@code
069 * JsonParser parser = Json.createParser(new StringReader("[]"));
070 * }</DIV>
071 *
072 * <BR /><BR />
073 * The class {@link JsonParserFactory} also contains methods to create
074 * {@code JsonParser} instances. {@link JsonParserFactory} is preferred
075 * when creating multiple parser instances. A sample usage is shown
076 * in the following example:
077 * 
078 * <BR /><DIV CLASS=SNIP>{@code
079 * JsonParserFactory    factory = Json.createParserFactory();
080 * JsonParser           parser1 = factory.createParser(...);
081 * JsonParser           parser2 = factory.createParser(...);
082 * }</DIV>
083 *
084 * <BR /><BR />
085 * {@code JsonParser} parses JSON using the pull parsing programming model.
086 * In this model the client code controls the thread and calls the method
087 * {@code next()} to advance the parser to the next state after
088 * processing each element. The parser can generate the following events:
089 * {@code START_OBJECT}, {@code END_OBJECT}, {@code START_ARRAY},
090 * {@code END_ARRAY}, {@code KEY_NAME}, {@code VALUE_STRING},
091 * {@code VALUE_NUMBER}, {@code VALUE_TRUE}, {@code VALUE_FALSE},
092 * and {@code VALUE_NULL}.
093 *
094 * <BR /><BR />
095 * <b>For example</b>, for an empty JSON object ({ }), the parser generates the event
096 * {@code START_OBJECT} with the first call to the method {@code next()} and the
097 * event {@code END_OBJECT} with the second call to the method {@code next()}.
098 * The following code demonstrates how to access these events:
099 *
100 * <BR /><DIV CLASS=SNIP>{@code
101 * Event event = parser.next(); // START_OBJECT
102 * event = parser.next();       // END_OBJECT
103 * }</DIV>
104 *
105 * <BR /><BR /><b>For example</b>, for the following JSON:
106 * 
107 * <DIV CLASS=JSON>{@code
108 * {
109 *   "firstName": "John", "lastName": "Smith", "age": 25,
110 *   "phoneNumber": [
111 *       { "type": "home", "number": "212 555-1234" },
112 *       { "type": "fax", "number": "646 555-4567" }
113 *    ]
114 * }
115 * }</DIV>
116 *
117 * <BR />Calls to the method {@code next()} result in parse events at the specified
118 * locations below (marked in bold):
119 * 
120 * <BR /><BR /><DIV STYLE='border: solid lightgray; border-width: 0.1em 0.1em 0.1em 0.8em;
121 *  border-radius: 0.75em; background: black; color: lightgray;
122 *  padding: 0.5em 1em; white-space: pre; overflow: auto;'>{@code
123 * {<B>START_OBJECT</B>
124 *   "firstName"<B>KEY_NAME</B>: "John"<B>VALUE_STRING</B>, "lastName"<B>KEY_NAME</B>: "Smith"<B>VALUE_STRING</B>, "age"<B>KEY_NAME</B>: 25<B>VALUE_NUMBER</B>,
125 *   "phoneNumber"<B>KEY_NAME</B> : [<B>START_ARRAY</B>
126 *       {<B>START_OBJECT</B> "type"<B>KEY_NAME</B>: "home"<B>VALUE_STRING</B>, "number"<B>KEY_NAME</B>: "212 555-1234"<B>VALUE_STRING</B> }<B>END_OBJECT</B>,
127 *       {<B>START_OBJECT</B> "type"<B>KEY_NAME</B>: "fax"<B>VALUE_STRING</B>, "number"<B>KEY_NAME</B>: "646 555-4567"<B>VALUE_STRING</B> }<B>END_OBJECT</B>
128 *    ]<B>END_ARRAY</B>
129 * }<B>END_OBJECT</B>}</DIV>
130 *
131 * <BR />The methods {@link #next()} and {@link #hasNext()} enable iteration over
132 * parser events to process JSON data. {@code JsonParser} provides get methods
133 * to obtain the value at the current state of the parser. For example, the
134 * following code shows how to obtain the value "John" from the JSON above:
135 *
136 * <DIV CLASS=EXAMPLE>{@code
137 * Event event = parser.next(); // START_OBJECT
138 * event = parser.next();       // KEY_NAME
139 * event = parser.next();       // VALUE_STRING
140 * parser.getString();          // "John"
141 * }</DIV>
142 *
143 * <BR />Starting in version 1.1, it is possible to build a partial JSON object
144 * model from the stream, at the current parser position.
145 * The methods {@link #getArray} and {@link #getObject} can be used to read in
146 * a {@code JsonArray} or {@code JsonObject}.  For example, the following code
147 * shows how to obtain the phoneNumber in a JsonArray, from the JSON above:
148 *
149 * <DIV CLASS=EXAMPLE>{@code
150 * while (parser.hasNext())
151 * {
152 *      Event event = parser.next();
153 * 
154 *      if (event == JsonParser.Event.KEY_NAME)
155 *      {
156 *         String key = getString();
157 *         event = parser.next();
158 *
159 *         if (key.equals("phoneNumber")
160 *             JsonArray phones = parser.getArray();
161 *      }
162 * }
163 * }</DIV>
164 *
165 * <BR />The methods {@link #getArrayStream} and {@link #getObjectStream} can be used
166 * to get a stream of the elements of a {@code JsonArray} or {@code JsonObject}.
167 * For example, the following code shows another way to obtain John's phoneNumber
168 * in a {@code JsonArray} :
169 *
170 * <DIV CLASS=EXAMPLE>{@code
171 * Event event = parser.next(); // START_OBJECT
172 * 
173 * JsonArray phones = (JsonArray) parser
174 *      .getObjectStream()
175 *      .filter(e->e.getKey().equals("phoneNumber"))
176 *      .map(e->e.getValue())
177 *      .findFirst()
178 *      .get();
179 * }</DIV>
180 *
181 * <BR />The methods {@link #skipArray} and {@link #skipObject} can be used to
182 * skip tokens and position the parser to {@code END_ARRAY} or
183 * {@code END_OBJECT}.
184 * 
185 * <BR /><BR />
186 * {@code JsonParser} can be used to parse sequence of JSON values that are not
187 * enclosed in a JSON array, e.g. { } { }. The following code demonstrates how
188 * to parse such sequence.
189 * 
190 * <DIV CLASS=EXAMPLE>{@code
191 * JsonParser parser = Json.createParser(...);
192 * 
193 * while (parser.hasNext)
194 * {
195 *     parser.next(); // advance parser state
196 *     JsonValue value = parser.getValue();
197 * }
198 * }</DIV>
199 *
200 * @see javax.json.Json
201 * @see JsonParserFactory
202 */
203public interface JsonParser extends /*Auto*/Closeable {
204
205    /**
206     * An event from {@code JsonParser}.
207     */
208    enum Event {
209        /**
210         * Start of a JSON array. The position of the parser is after '['.
211         */
212        START_ARRAY,
213        /**
214         * Start of a JSON object. The position of the parser is after '{'.
215         */
216        START_OBJECT,
217        /**
218         * Name in a name/value pair of a JSON object. The position of the parser
219         * is after the key name. The method {@link #getString} returns the key
220         * name.
221         */
222        KEY_NAME,
223        /**
224         * String value in a JSON array or object. The position of the parser is
225         * after the string value. The method {@link #getString}
226         * returns the string value.
227         */
228        VALUE_STRING,
229        /**
230         * Number value in a JSON array or object. The position of the parser is
231         * after the number value. {@code JsonParser} provides the following
232         * methods to access the number value: {@link #getInt},
233         * {@link #getLong}, and {@link #getBigDecimal}.
234         */
235        VALUE_NUMBER,
236        /**
237         * {@code true} value in a JSON array or object. The position of the
238         * parser is after the {@code true} value.
239         */
240        VALUE_TRUE,
241        /**
242         * {@code false} value in a JSON array or object. The position of the
243         * parser is after the {@code false} value.
244         */
245        VALUE_FALSE,
246        /**
247         * {@code null} value in a JSON array or object. The position of the
248         * parser is after the {@code null} value.
249         */
250        VALUE_NULL,
251        /**
252         * End of a JSON object. The position of the parser is after '}'.
253         */
254        END_OBJECT,
255        /**
256         * End of a JSON array. The position of the parser is after ']'.
257         */
258        END_ARRAY
259    }
260
261    /**
262     * Returns {@code true} if there are more parsing states. This method returns
263     * {@code false} if the parser reaches the end of the JSON text.
264     *
265     * @return {@code true} if there are more parsing states.
266     * @throws javax.json.JsonException if an i/o error occurs (IOException
267     * would be cause of JsonException)
268     * @throws JsonParsingException if the parser encounters invalid JSON
269     * when advancing to next state.
270     */
271    boolean hasNext();
272
273    /**
274     * Returns the event for the next parsing state.
275     *
276     * @throws javax.json.JsonException if an i/o error occurs (IOException
277     * would be cause of JsonException)
278     * @throws JsonParsingException if the parser encounters invalid JSON
279     * when advancing to next state.
280     * @throws java.util.NoSuchElementException if there are no more parsing
281     * states.
282     * @return the event for the next parsing state
283     */
284    Event next();
285
286    /**
287     * Returns a {@code String} for the name in a name/value pair,
288     * for a string value or a number value. This method should only be called
289     * when the parser state is {@link Event#KEY_NAME}, {@link Event#VALUE_STRING},
290     * or {@link Event#VALUE_NUMBER}.
291     *
292     * @return a name when the parser state is {@link Event#KEY_NAME}
293     *         a string value when the parser state is {@link Event#VALUE_STRING}
294     *         a number value when the parser state is {@link Event#VALUE_NUMBER}
295     * @throws IllegalStateException when the parser state is not
296     *      {@code KEY_NAME}, {@code VALUE_STRING}, or {@code VALUE_NUMBER}
297     */
298    String getString();
299
300    /**
301     * Returns true if the JSON number at the current parser state is a
302     * integral number. A {@link BigDecimal} may be used to store the value
303     * internally and this method semantics are defined using its
304     * {@code scale()}. If the scale is zero, then it is considered integral
305     * type. This integral type information can be used to invoke an
306     * appropriate accessor method to obtain a numeric value as in the
307     * following example:
308     *
309     * <pre>
310     * <code>
311     * JsonParser parser = ...
312     * 
313     * if (parser.isIntegralNumber())
314     *     parser.getInt();     // or other methods to get integral value
315     * else
316     *     parser.getBigDecimal();
317     *
318     * </code>
319     * </pre>
320     *
321     * @return true if this number is a integral number, otherwise false
322     * @throws IllegalStateException when the parser state is not
323     *      {@code VALUE_NUMBER}
324     */
325    boolean isIntegralNumber();
326
327    /**
328     * Returns a JSON number as an integer. The returned value is equal
329     * to {@code new BigDecimal(getString()).intValue()}. Note that
330     * this conversion can lose information about the overall magnitude
331     * and precision of the number value as well as return a result with
332     * the opposite sign. This method should only be called when the parser
333     * state is {@link Event#VALUE_NUMBER}.
334     *
335     * @return an integer for a JSON number
336     * @throws IllegalStateException when the parser state is not
337     *      {@code VALUE_NUMBER}
338     * @see java.math.BigDecimal#intValue()
339     */
340    int getInt();
341
342    /**
343     * Returns a JSON number as a long. The returned value is equal
344     * to {@code new BigDecimal(getString()).longValue()}. Note that this
345     * conversion can lose information about the overall magnitude and
346     * precision of the number value as well as return a result with
347     * the opposite sign. This method is only called when the parser state is
348     * {@link Event#VALUE_NUMBER}.
349     *
350     * @return a long for a JSON number
351     * @throws IllegalStateException when the parser state is not
352     *      {@code VALUE_NUMBER}
353     * @see java.math.BigDecimal#longValue()
354     */
355    long getLong();
356
357    /**
358     * Returns a JSON number as a {@code BigDecimal}. The {@code BigDecimal}
359     * is created using {@code new BigDecimal(getString())}. This
360     * method should only called when the parser state is
361     * {@link Event#VALUE_NUMBER}.
362     *
363     * @return a {@code BigDecimal} for a JSON number
364     * @throws IllegalStateException when the parser state is not
365     *      {@code VALUE_NUMBER}
366     */
367    BigDecimal getBigDecimal();
368
369    /**
370     * Return the location that corresponds to the parser's current state in
371     * the JSON input source. The location information is only valid in the
372     * current parser state (or until the parser is advanced to a next state).
373     *
374     * @return a non-null location corresponding to the current parser state
375     * in JSON input source
376     */
377    JsonLocation getLocation();
378
379    /**
380     * Returns a {@code JsonObject} and advances the parser to the
381     * corresponding {@code END_OBJECT}.
382     *
383     * @return the {@code JsonObject} at the current parser position
384     *
385     * @throws IllegalStateException when the parser state is not
386     *     {@code START_OBJECT}
387     *
388     * @since 1.1
389     */
390    default public JsonObject getObject() {
391        throw new UnsupportedOperationException();
392    }
393
394    /**
395     * Returns a {@code JsonValue} at the current parser position.
396     * If the parser state is {@code START_ARRAY}, the behavior is
397     * the same as {@link #getArray}. If the parser state is
398     * {@code START_OBJECT}, the behavior is the same as
399     * {@link #getObject}. For all other cases, if applicable, the JSON value is
400     * read and returned.
401     *
402     * @return the {@code JsonValue} at the current parser position.
403     * @throws IllegalStateException when the parser state is
404     *     {@code END_OBJECT} or {@code END_ARRAY}
405     *
406     * @since 1.1
407     */
408    default public JsonValue getValue() {
409        throw new UnsupportedOperationException();
410    }
411
412    /**
413     * Returns a {@code JsonArray} and advance the parser to the
414     * the corresponding {@code END_ARRAY}.
415     *
416     * @return the {@code JsonArray} at the current parser position
417     *
418     * @throws IllegalStateException when the parser state is not
419     *     {@code START_ARRAY}
420     *
421     * @since 1.1
422     */
423    default public JsonArray getArray() {
424        throw new UnsupportedOperationException();
425    }
426
427    /**
428     * Returns a stream of the {@code JsonArray} elements.
429     * The parser state must be {@code START_ARRAY}.
430     * The elements are read lazily, on an as-needed basis, as
431     * required by the stream operations.
432     * If the stream operations do not consume
433     * all of the array elements, {@link skipArray} can be used to
434     * skip the unprocessed array elements.
435     *
436     * @return a stream of elements of the {@code JsonArray}
437     *
438     * @throws IllegalStateException when the parser state is not
439     *     {@code START_ARRAY}
440     *
441     * @since 1.1
442     */
443    default public Stream<JsonValue> getArrayStream() {
444        throw new UnsupportedOperationException();
445    }
446
447    /**
448     * Returns a stream of the {@code JsonObject}'s
449     * name/value pairs. The parser state must be {@code START_OBJECT}.
450     * The name/value pairs are read lazily, on an as-needed basis, as
451     * required by the stream operations.
452     * If the stream operations do not consume
453     * all of the object's name/value pairs, {@link skipObject} can be
454     * used to skip the unprocessed elements.
455     *
456     * @return a stream of name/value pairs of the {@code JsonObject}
457     *
458     * @throws IllegalStateException when the parser state is not
459     *     {@code START_OBJECT}
460     *
461     * @since 1.1
462     */
463    default public Stream<Map.Entry<String,JsonValue>> getObjectStream() {
464        throw new UnsupportedOperationException();
465    }
466
467    /**
468     * Returns a stream of {@code JsonValue} from a sequence of
469     * JSON values. The values are read lazily, on an as-needed basis,
470     * as needed by the stream operations.
471     *
472     * @return a Stream of {@code JsonValue}
473     *
474     * @throws IllegalStateException if the parser is in an array or object.
475     *
476     * @since 1.1
477     */
478    default public Stream<JsonValue> getValueStream() {
479        throw new UnsupportedOperationException();
480    }
481
482    /**
483     * Advance the parser to {@code END_ARRAY}.
484     * If the parser is in array context, i.e. it has previously
485     * encountered a {@code START_ARRAY} without encountering the
486     * corresponding {@code END_ARRAY}, the parser is advanced to
487     * the corresponding {@code END_ARRAY}.
488     * If the parser is not in any array context, nothing happens.
489     *
490     * @since 1.1
491     */
492    default public void skipArray() {
493        throw new UnsupportedOperationException();
494    }
495
496    /**
497     * Advance the parser to {@code END_OBJECT}.
498     * If the parser is in object context, i.e. it has previously
499     * encountered a {@code START_OBJECT} without encountering the
500     * corresponding {@code END_OBJECT}, the parser is advanced to
501     * the corresponding {@code END_OBJECT}.
502     * If the parser is not in any object context, nothing happens.
503     *
504     * @since 1.1
505     */
506    default public void skipObject() {
507        throw new UnsupportedOperationException();
508    }
509
510    /**
511     * Closes this parser and frees any resources associated with the
512     * parser. This method closes the underlying input source.
513     *
514     * @throws javax.json.JsonException if an i/o error occurs (IOException
515     * would be cause of JsonException)
516     */
517    @Override
518    void close();
519}