001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau.json;
014
015import java.util.*;
016import java.util.concurrent.*;
017
018import org.apache.juneau.*;
019import org.apache.juneau.annotation.*;
020import org.apache.juneau.collections.*;
021import org.apache.juneau.parser.*;
022
023/**
024 * Parses any valid JSON text into a POJO model.
025 *
026 * <h5 class='topic'>Media types</h5>
027 *
028 * Handles <c>Content-Type</c> types:  <bc>application/json, text/json</bc>
029 *
030 * <h5 class='topic'>Description</h5>
031 *
032 * This parser uses a state machine, which makes it very fast and efficient.  It parses JSON in about 70% of the
033 * time that it takes the built-in Java DOM parsers to parse equivalent XML.
034 *
035 * <p>
036 * This parser handles all valid JSON syntax.
037 * In addition, when strict mode is disable, the parser also handles the following:
038 * <ul class='spaced-list'>
039 *    <li>
040 *       Javascript comments (both {@code /*} and {@code //}) are ignored.
041 *    <li>
042 *       Both single and double quoted strings.
043 *    <li>
044 *       Automatically joins concatenated strings (e.g. <code><js>"aaa"</js> + <js>'bbb'</js></code>).
045 *    <li>
046 *       Unquoted attributes.
047 * </ul>
048 *
049 * <p>
050 * Also handles negative, decimal, hexadecimal, octal, and double numbers, including exponential notation.
051 *
052 * <p>
053 * This parser handles the following input, and automatically returns the corresponding Java class.
054 * <ul class='spaced-list'>
055 *    <li>
056 *       JSON objects (<js>"{...}"</js>) are converted to {@link OMap OMaps}.
057 *       <b>Note:</b>  If a <code><xa>_type</xa>=<xs>'xxx'</xs></code> attribute is specified on the object, then an
058 *       attempt is made to convert the object to an instance of the specified Java bean class.
059 *       See the <c>beanTypeName</c> setting on the {@link PropertyStore} for more information about parsing
060 *       beans from JSON.
061 *    <li>
062 *       JSON arrays (<js>"[...]"</js>) are converted to {@link OList OLists}.
063 *    <li>
064 *       JSON string literals (<js>"'xyz'"</js>) are converted to {@link String Strings}.
065 *    <li>
066 *       JSON numbers (<js>"123"</js>, including octal/hexadecimal/exponential notation) are converted to
067 *       {@link Integer Integers}, {@link Long Longs}, {@link Float Floats}, or {@link Double Doubles} depending on
068 *       whether the number is decimal, and the size of the number.
069 *    <li>
070 *       JSON booleans (<js>"false"</js>) are converted to {@link Boolean Booleans}.
071 *    <li>
072 *       JSON nulls (<js>"null"</js>) are converted to <jk>null</jk>.
073 *    <li>
074 *       Input consisting of only whitespace or JSON comments are converted to <jk>null</jk>.
075 * </ul>
076 *
077 * <p>
078 * Input can be any of the following:
079 * <ul class='spaced-list'>
080 *    <li>
081 *       <js>"{...}"</js> - Converted to an {@link OMap} or an instance of a Java bean if a <xa>_type</xa>
082 *       attribute is present.
083 *    <li>
084 *       <js>"[...]"</js> - Converted to an {@link OList}.
085 *    <li>
086 *       <js>"123..."</js> - Converted to a {@link Number} (either {@link Integer}, {@link Long}, {@link Float},
087 *       or {@link Double}).
088 *    <li>
089 *       <js>"true"</js>/<js>"false"</js> - Converted to a {@link Boolean}.
090 *    <li>
091 *       <js>"null"</js> - Returns <jk>null</jk>.
092 *    <li>
093 *       <js>"'xxx'"</js> - Converted to a {@link String}.
094 *    <li>
095 *       <js>"\"xxx\""</js> - Converted to a {@link String}.
096 *    <li>
097 *       <js>"'xxx' + \"yyy\""</js> - Converted to a concatenated {@link String}.
098 * </ul>
099 *
100 * <p>
101 * TIP:  If you know you're parsing a JSON object or array, it can be easier to parse it using the
102 * {@link OMap#OMap(CharSequence) OMap(CharSequence)} or {@link OList#OList(CharSequence)
103 * OList(CharSequence)} constructors instead of using this class.
104 * The end result should be the same.
105 */
106@ConfigurableContext
107public class JsonParser extends ReaderParser implements JsonMetaProvider, JsonCommon {
108
109   //-------------------------------------------------------------------------------------------------------------------
110   // Configurable properties
111   //-------------------------------------------------------------------------------------------------------------------
112
113   static final String PREFIX = "JsonParser";
114
115   /**
116    * Configuration property:  Validate end.
117    *
118    * <h5 class='section'>Property:</h5>
119    * <ul class='spaced-list'>
120    *    <li><b>ID:</b>  {@link org.apache.juneau.json.JsonParser#JSON_validateEnd JSON_validateEnd}
121    *    <li><b>Name:</b>  <js>"JsonParser.validateEnd.b"</js>
122    *    <li><b>Data type:</b>  <jk>boolean</jk>
123    *    <li><b>System property:</b>  <c>JsonParser.validateEnd</c>
124    *    <li><b>Environment variable:</b>  <c>JSONPARSER_VALIDATEEND</c>
125    *    <li><b>Default:</b>  <jk>false</jk>
126    *    <li><b>Session property:</b>  <jk>false</jk>
127    *    <li><b>Annotations:</b>
128    *       <ul>
129    *          <li class='ja'>{@link org.apache.juneau.json.annotation.JsonConfig#validateEnd()}
130    *       </ul>
131    *    <li><b>Methods:</b>
132    *       <ul>
133    *          <li class='jm'>{@link org.apache.juneau.json.JsonParserBuilder#validateEnd()}
134    *       </ul>
135    * </ul>
136    *
137    * <h5 class='section'>Description:</h5>
138    * <p>
139    * If <jk>true</jk>, after parsing a POJO from the input, verifies that the remaining input in
140    * the stream consists of only comments or whitespace.
141    *
142    * <h5 class='section'>Example:</h5>
143    * <p class='bcode w800'>
144    *    <jc>// Create a parser that validates that there's no garbage at the end of the input.</jc>
145    *    ReaderParser p = JsonParser.
146    *       .<jsm>create</jsm>()
147    *       .validateEnd()
148    *       .build();
149    *
150    *    <jc>// Same, but use property.</jc>
151    *    ReaderParser p = JsonParser.
152    *       .<jsm>create</jsm>()
153    *       .set(<jsf>JSON_validateEnd</jsf>, <jk>true</jk>)
154    *       .build();
155    *
156    *    <jc>// Should fail because input has multiple POJOs.</jc>
157    *    String in = <js>"{foo:'bar'}{baz:'qux'}"</js>;
158    *    MyBean myBean = p.parse(in, MyBean.<jk>class</jk>);
159    * </p>
160    */
161   public static final String JSON_validateEnd = PREFIX + ".validateEnd.b";
162
163   //-------------------------------------------------------------------------------------------------------------------
164   // Predefined instances
165   //-------------------------------------------------------------------------------------------------------------------
166
167   /** Default parser, all default settings.*/
168   public static final JsonParser DEFAULT = new JsonParser(PropertyStore.DEFAULT);
169
170   /** Default parser, all default settings.*/
171   public static final JsonParser DEFAULT_STRICT = new JsonParser.Strict(PropertyStore.DEFAULT);
172
173
174   //-------------------------------------------------------------------------------------------------------------------
175   // Predefined subclasses
176   //-------------------------------------------------------------------------------------------------------------------
177
178   /** Default parser, strict mode. */
179   public static class Strict extends JsonParser {
180
181      /**
182       * Constructor.
183       *
184       * @param ps The property store containing all the settings for this object.
185       */
186      public Strict(PropertyStore ps) {
187         super(ps.builder().setDefault(PARSER_strict, true).setDefault(JSON_validateEnd, true).build());
188      }
189   }
190
191
192
193   //-------------------------------------------------------------------------------------------------------------------
194   // Instance
195   //-------------------------------------------------------------------------------------------------------------------
196
197   private final boolean validateEnd;
198   private final Map<ClassMeta<?>,JsonClassMeta> jsonClassMetas = new ConcurrentHashMap<>();
199   private final Map<BeanPropertyMeta,JsonBeanPropertyMeta> jsonBeanPropertyMetas = new ConcurrentHashMap<>();
200
201   /**
202    * Constructor.
203    *
204    * @param ps The property store containing all the settings for this object.
205    */
206   public JsonParser(PropertyStore ps) {
207      this(ps, "application/json", "text/json");
208   }
209
210   /**
211    * Constructor.
212    *
213    * @param ps The property store containing all the settings for this object.
214    * @param consumes The list of media types that this parser consumes (e.g. <js>"application/json"</js>).
215    */
216   public JsonParser(PropertyStore ps, String...consumes) {
217      super(ps, consumes);
218      validateEnd = getBooleanProperty(JSON_validateEnd, false);
219   }
220
221   @Override /* Context */
222   public JsonParserBuilder builder() {
223      return new JsonParserBuilder(getPropertyStore());
224   }
225
226   /**
227    * Instantiates a new clean-slate {@link JsonParserBuilder} object.
228    *
229    * <p>
230    * This is equivalent to simply calling <code><jk>new</jk> JsonParserBuilder()</code>.
231    *
232    * <p>
233    * Note that this method creates a builder initialized to all default settings, whereas {@link #builder()} copies
234    * the settings of the object called on.
235    *
236    * @return A new {@link JsonParserBuilder} object.
237    */
238   public static JsonParserBuilder create() {
239      return new JsonParserBuilder();
240   }
241
242   @Override /* Parser */
243   public JsonParserSession createSession() {
244      return createSession(createDefaultSessionArgs());
245   }
246
247   @Override /* Parser */
248   public JsonParserSession createSession(ParserSessionArgs args) {
249      return new JsonParserSession(this, args);
250   }
251
252   //-----------------------------------------------------------------------------------------------------------------
253   // Extended metadata
254   //-----------------------------------------------------------------------------------------------------------------
255
256   @Override /* JsonMetaProvider */
257   public JsonClassMeta getJsonClassMeta(ClassMeta<?> cm) {
258      JsonClassMeta m = jsonClassMetas.get(cm);
259      if (m == null) {
260         m = new JsonClassMeta(cm, this);
261         jsonClassMetas.put(cm, m);
262      }
263      return m;
264   }
265
266   @Override /* JsonMetaProvider */
267   public JsonBeanPropertyMeta getJsonBeanPropertyMeta(BeanPropertyMeta bpm) {
268      if (bpm == null)
269         return JsonBeanPropertyMeta.DEFAULT;
270      JsonBeanPropertyMeta m = jsonBeanPropertyMetas.get(bpm);
271      if (m == null) {
272         m = new JsonBeanPropertyMeta(bpm.getDelegateFor(), this);
273         jsonBeanPropertyMetas.put(bpm, m);
274      }
275      return m;
276   }
277
278   //-----------------------------------------------------------------------------------------------------------------
279   // Properties
280   //-----------------------------------------------------------------------------------------------------------------
281
282   /**
283    * Validate end.
284    *
285    * @see #JSON_validateEnd
286    * @return
287    *    <jk>true</jk> if after parsing a POJO from the input, verifies that the remaining input in
288    *    the stream consists of only comments or whitespace.
289    */
290   protected final boolean isValidateEnd() {
291      return validateEnd;
292   }
293
294   //-----------------------------------------------------------------------------------------------------------------
295   // Other methods
296   //-----------------------------------------------------------------------------------------------------------------
297
298   @Override /* Context */
299   public OMap toMap() {
300      return super.toMap()
301         .a("JsonParser", new DefaultFilteringOMap());
302   }
303}