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.parser;
014
015import static org.apache.juneau.internal.StringUtils.*;
016import static org.apache.juneau.parser.Parser.*;
017
018import java.io.*;
019import java.lang.reflect.*;
020import java.util.*;
021
022import org.apache.juneau.*;
023import org.apache.juneau.annotation.*;
024import org.apache.juneau.transform.*;
025import org.apache.juneau.utils.*;
026
027/**
028 * Session object that lives for the duration of a single use of {@link Parser}.
029 *
030 * <p>
031 * This class is NOT thread safe.
032 * It is typically discarded after one-time use although it can be reused against multiple inputs.
033 */
034public abstract class ParserSession extends BeanSession {
035
036   private final Parser ctx;
037   private final Method javaMethod;
038   private final Object outer;
039
040   // Writable properties.
041   private BeanPropertyMeta currentProperty;
042   private ClassMeta<?> currentClass;
043   private final ParserListener listener;
044
045   private Position mark = new Position(-1);
046
047   private ParserPipe pipe;
048
049   /**
050    * Create a new session using properties specified in the context.
051    *
052    * @param ctx
053    *    The context creating this session object.
054    *    The context contains all the configuration settings for this object.
055    * @param args
056    *    Runtime session arguments.
057    */
058   protected ParserSession(Parser ctx, ParserSessionArgs args) {
059      super(ctx, args == null ? ParserSessionArgs.DEFAULT : args);
060      args = args == null ? ParserSessionArgs.DEFAULT : args;
061      this.ctx = ctx;
062      javaMethod = args.javaMethod;
063      outer = args.outer;
064      listener = getInstanceProperty(PARSER_listener, ParserListener.class, ctx.getListenerClass());
065   }
066
067   /**
068    * Default constructor.
069    *
070    * @param args
071    *    Runtime session arguments.
072    */
073   protected ParserSession(ParserSessionArgs args) {
074      this(Parser.DEFAULT, args);
075   }
076
077   @Override /* Session */
078   public ObjectMap asMap() {
079      return super.asMap()
080         .append("ParserSession", new ObjectMap()
081            .append("javaMethod", javaMethod)
082            .append("listener", listener)
083            .append("outer", outer)
084         );
085   }
086
087   //-----------------------------------------------------------------------------------------------------------------
088   // Abstract methods
089   //-----------------------------------------------------------------------------------------------------------------
090
091   /**
092    * Workhorse method.
093    *
094    * <p>
095    * Subclasses are expected to implement this method.
096    *
097    * @param pipe Where to get the input from.
098    * @param type
099    *    The class type of the object to create.
100    *    If <jk>null</jk> or <code>Object.<jk>class</jk></code>, object type is based on what's being parsed.
101    *    For example, when parsing JSON text, it may return a <code>String</code>, <code>Number</code>,
102    *    <code>ObjectMap</code>, etc...
103    * @param <T> The class type of the object to create.
104    * @return The parsed object.
105    * @throws Exception If thrown from underlying stream, or if the input contains a syntax error or is malformed.
106    */
107   protected abstract <T> T doParse(ParserPipe pipe, ClassMeta<T> type) throws Exception;
108
109   /**
110    * Returns <jk>true</jk> if this parser subclasses from {@link ReaderParser}.
111    *
112    * @return <jk>true</jk> if this parser subclasses from {@link ReaderParser}.
113    */
114   public abstract boolean isReaderParser();
115
116
117   //-----------------------------------------------------------------------------------------------------------------
118   // Other methods
119   //-----------------------------------------------------------------------------------------------------------------
120
121   /**
122    * Wraps the specified input object into a {@link ParserPipe} object so that it can be easily converted into
123    * a stream or reader.
124    *
125    * @param input
126    *    The input.
127    *    <br>For character-based parsers, this can be any of the following types:
128    *    <ul>
129    *       <li><jk>null</jk>
130    *       <li>{@link Reader}
131    *       <li>{@link CharSequence}
132    *       <li>{@link InputStream} containing UTF-8 encoded text (or whatever the encoding specified by
133    *          {@link ReaderParser#RPARSER_inputStreamCharset}).
134    *       <li><code><jk>byte</jk>[]</code> containing UTF-8 encoded text (or whatever the encoding specified by
135    *          {@link ReaderParser#RPARSER_inputStreamCharset}).
136    *       <li>{@link File} containing system encoded text (or whatever the encoding specified by
137    *          {@link ReaderParser#RPARSER_fileCharset}).
138    *    </ul>
139    *    <br>For byte-based parsers, this can be any of the following types:
140    *    <ul>
141    *       <li><jk>null</jk>
142    *       <li>{@link InputStream}
143    *       <li><code><jk>byte</jk>[]</code>
144    *       <li>{@link File}
145    *       <li>{@link CharSequence} containing encoded bytes according to the {@link InputStreamParser#ISPARSER_binaryFormat} setting.
146    *    </ul>
147    * @return
148    *    A new {@link ParserPipe} wrapper around the specified input object.
149    */
150   protected ParserPipe createPipe(Object input) {
151      return null;
152   }
153
154   /**
155    * Returns information used to determine at what location in the parse a failure occurred.
156    *
157    * @return A map, typically containing something like <code>{line:123,column:456,currentProperty:"foobar"}</code>
158    */
159   public final ObjectMap getLastLocation() {
160      ObjectMap m = new ObjectMap();
161      if (currentClass != null)
162         m.put("currentClass", currentClass.toString(true));
163      if (currentProperty != null)
164         m.put("currentProperty", currentProperty);
165      return m;
166   }
167
168   /**
169    * Returns the Java method that invoked this parser.
170    *
171    * <p>
172    * When using the REST API, this is the Java method invoked by the REST call.
173    * Can be used to access annotations defined on the method or class.
174    *
175    * @return The Java method that invoked this parser.
176   */
177   protected final Method getJavaMethod() {
178      return javaMethod;
179   }
180
181   /**
182    * Returns the outer object used for instantiating top-level non-static member classes.
183    *
184    * <p>
185    * When using the REST API, this is the servlet object.
186    *
187    * @return The outer object.
188   */
189   protected final Object getOuter() {
190      return outer;
191   }
192
193   /**
194    * Sets the current bean property being parsed for proper error messages.
195    *
196    * @param currentProperty The current property being parsed.
197    */
198   protected final void setCurrentProperty(BeanPropertyMeta currentProperty) {
199      this.currentProperty = currentProperty;
200   }
201
202   /**
203    * Sets the current class being parsed for proper error messages.
204    *
205    * @param currentClass The current class being parsed.
206    */
207   protected final void setCurrentClass(ClassMeta<?> currentClass) {
208      this.currentClass = currentClass;
209   }
210
211   /**
212    * Trims the specified object if it's a <code>String</code> and {@link #isTrimStrings()} returns <jk>true</jk>.
213    *
214    * @param o The object to trim.
215    * @return The trimmed string if it's a string.
216    */
217   @SuppressWarnings("unchecked")
218   protected final <K> K trim(K o) {
219      if (isTrimStrings() && o instanceof String)
220         return (K)o.toString().trim();
221      return o;
222
223   }
224
225   /**
226    * Trims the specified string if {@link ParserSession#isTrimStrings()} returns <jk>true</jk>.
227    *
228    * @param s The input string to trim.
229    * @return The trimmed string, or <jk>null</jk> if the input was <jk>null</jk>.
230    */
231   protected final String trim(String s) {
232      if (isTrimStrings() && s != null)
233         return s.trim();
234      return s;
235   }
236
237   /**
238    * Converts the specified <code>ObjectMap</code> into a bean identified by the <js>"_type"</js> property in the map.
239    *
240    * @param m The map to convert to a bean.
241    * @param pMeta The current bean property being parsed.
242    * @param eType The current expected type being parsed.
243    * @return
244    *    The converted bean, or the same map if the <js>"_type"</js> entry wasn't found or didn't resolve to a bean.
245    */
246   protected final Object cast(ObjectMap m, BeanPropertyMeta pMeta, ClassMeta<?> eType) {
247
248      String btpn = getBeanTypePropertyName(eType);
249
250      Object o = m.get(btpn);
251      if (o == null)
252         return m;
253      String typeName = o.toString();
254
255      ClassMeta<?> cm = getClassMeta(typeName, pMeta, eType);
256
257      if (cm != null) {
258         BeanMap<?> bm = m.getBeanSession().newBeanMap(cm.getInnerClass());
259
260         // Iterate through all the entries in the map and set the individual field values.
261         for (Map.Entry<String,Object> e : m.entrySet()) {
262            String k = e.getKey();
263            Object v = e.getValue();
264            if (! k.equals(btpn)) {
265               // Attempt to recursively cast child maps.
266               if (v instanceof ObjectMap)
267                  v = cast((ObjectMap)v, pMeta, eType);
268               bm.put(k, v);
269            }
270         }
271         return bm.getBean();
272      }
273
274      return m;
275   }
276
277   /**
278    * Give the specified dictionary name, resolve it to a class.
279    *
280    * @param typeName The dictionary name to resolve.
281    * @param pMeta The bean property we're currently parsing.
282    * @param eType The expected type we're currently parsing.
283    * @return The resolved class, or <jk>null</jk> if the type name could not be resolved.
284    */
285   protected final ClassMeta<?> getClassMeta(String typeName, BeanPropertyMeta pMeta, ClassMeta<?> eType) {
286      BeanRegistry br = null;
287
288      // Resolve via @BeanProperty(beanDictionary={})
289      if (pMeta != null) {
290         br = pMeta.getBeanRegistry();
291         if (br != null && br.hasName(typeName))
292            return br.getClassMeta(typeName);
293      }
294
295      // Resolve via @Bean(beanDictionary={}) on the expected type where the
296      // expected type is an interface with subclasses.
297      if (eType != null) {
298         br = eType.getBeanRegistry();
299         if (br != null && br.hasName(typeName))
300            return br.getClassMeta(typeName);
301      }
302
303      // Last resort, resolve using the session registry.
304      return getBeanRegistry().getClassMeta(typeName);
305   }
306
307   /**
308    * Method that gets called when an unknown bean property name is encountered.
309    *
310    * @param propertyName The unknown bean property name.
311    * @param beanMap The bean that doesn't have the expected property.
312    * @throws ParseException
313    *    Automatically thrown if {@link BeanContext#BEAN_ignoreUnknownBeanProperties} setting on this parser is
314    *    <jk>false</jk>
315    * @param <T> The class type of the bean map that doesn't have the expected property.
316    */
317   protected final <T> void onUnknownProperty(String propertyName, BeanMap<T> beanMap) throws ParseException {
318      if (propertyName.equals(getBeanTypePropertyName(beanMap.getClassMeta())))
319         return;
320      if (! isIgnoreUnknownBeanProperties())
321         throw new ParseException(this,
322            "Unknown property ''{0}'' encountered while trying to parse into class ''{1}''", propertyName,
323            beanMap.getClassMeta());
324      if (listener != null)
325         listener.onUnknownBeanProperty(this, propertyName, beanMap.getClassMeta().getInnerClass(), beanMap.getBean());
326   }
327
328   /**
329    * Parses input into the specified object type.
330    *
331    * <p>
332    * The type can be a simple type (e.g. beans, strings, numbers) or parameterized type (collections/maps).
333    *
334    * <h5 class='section'>Examples:</h5>
335    * <p class='bcode w800'>
336    *    ReaderParser p = JsonParser.<jsf>DEFAULT</jsf>;
337    *
338    *    <jc>// Parse into a linked-list of strings.</jc>
339    *    List l = p.parse(json, LinkedList.<jk>class</jk>, String.<jk>class</jk>);
340    *
341    *    <jc>// Parse into a linked-list of beans.</jc>
342    *    List l = p.parse(json, LinkedList.<jk>class</jk>, MyBean.<jk>class</jk>);
343    *
344    *    <jc>// Parse into a linked-list of linked-lists of strings.</jc>
345    *    List l = p.parse(json, LinkedList.<jk>class</jk>, LinkedList.<jk>class</jk>, String.<jk>class</jk>);
346    *
347    *    <jc>// Parse into a map of string keys/values.</jc>
348    *    Map m = p.parse(json, TreeMap.<jk>class</jk>, String.<jk>class</jk>, String.<jk>class</jk>);
349    *
350    *    <jc>// Parse into a map containing string keys and values of lists containing beans.</jc>
351    *    Map m = p.parse(json, TreeMap.<jk>class</jk>, String.<jk>class</jk>, List.<jk>class</jk>, MyBean.<jk>class</jk>);
352    * </p>
353    *
354    * <p>
355    * <code>Collection</code> classes are assumed to be followed by zero or one objects indicating the element type.
356    *
357    * <p>
358    * <code>Map</code> classes are assumed to be followed by zero or two meta objects indicating the key and value types.
359    *
360    * <p>
361    * The array can be arbitrarily long to indicate arbitrarily complex data structures.
362    *
363    * <h5 class='section'>Notes:</h5>
364    * <ul class='spaced-list'>
365    *    <li>
366    *       Use the {@link #parse(Object, Class)} method instead if you don't need a parameterized map/collection.
367    * </ul>
368    *
369    * @param <T> The class type of the object to create.
370    * @param input
371    *    The input.
372    *    <br>Character-based parsers can handle the following input class types:
373    *    <ul>
374    *       <li><jk>null</jk>
375    *       <li>{@link Reader}
376    *       <li>{@link CharSequence}
377    *       <li>{@link InputStream} containing UTF-8 encoded text (or charset defined by
378    *          {@link ReaderParser#RPARSER_inputStreamCharset} property value).
379    *       <li><code><jk>byte</jk>[]</code> containing UTF-8 encoded text (or charset defined by
380    *          {@link ReaderParser#RPARSER_inputStreamCharset} property value).
381    *       <li>{@link File} containing system encoded text (or charset defined by
382    *          {@link ReaderParser#RPARSER_fileCharset} property value).
383    *    </ul>
384    *    <br>Stream-based parsers can handle the following input class types:
385    *    <ul>
386    *       <li><jk>null</jk>
387    *       <li>{@link InputStream}
388    *       <li><code><jk>byte</jk>[]</code>
389    *       <li>{@link File}
390    *    </ul>
391    * @param type
392    *    The object type to create.
393    *    <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
394    * @param args
395    *    The type arguments of the class if it's a collection or map.
396    *    <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
397    *    <br>Ignored if the main type is not a map or collection.
398    * @return The parsed object.
399    * @throws ParseException
400    *    If the input contains a syntax error or is malformed, or is not valid for the specified type.
401    * @see BeanSession#getClassMeta(Type,Type...) for argument syntax for maps and collections.
402    */
403   @SuppressWarnings("unchecked")
404   public final <T> T parse(Object input, Type type, Type...args) throws ParseException {
405      try (ParserPipe pipe = createPipe(input)) {
406         return (T)parseInner(pipe, getClassMeta(type, args));
407      }
408   }
409
410   /**
411    * Same as {@link #parse(Object, Type, Type...)} except optimized for a non-parameterized class.
412    *
413    * <p>
414    * This is the preferred parse method for simple types since you don't need to cast the results.
415    *
416    * <h5 class='section'>Examples:</h5>
417    * <p class='bcode w800'>
418    *    ReaderParser p = JsonParser.<jsf>DEFAULT</jsf>;
419    *
420    *    <jc>// Parse into a string.</jc>
421    *    String s = p.parse(json, String.<jk>class</jk>);
422    *
423    *    <jc>// Parse into a bean.</jc>
424    *    MyBean b = p.parse(json, MyBean.<jk>class</jk>);
425    *
426    *    <jc>// Parse into a bean array.</jc>
427    *    MyBean[] ba = p.parse(json, MyBean[].<jk>class</jk>);
428    *
429    *    <jc>// Parse into a linked-list of objects.</jc>
430    *    List l = p.parse(json, LinkedList.<jk>class</jk>);
431    *
432    *    <jc>// Parse into a map of object keys/values.</jc>
433    *    Map m = p.parse(json, TreeMap.<jk>class</jk>);
434    * </p>
435    *
436    * @param <T> The class type of the object being created.
437    * @param input
438    *    The input.
439    *    See {@link #parse(Object, Type, Type...)} for details.
440    * @param type The object type to create.
441    * @return The parsed object.
442    * @throws ParseException
443    *    If the input contains a syntax error or is malformed, or is not valid for the specified type.
444    */
445   public final <T> T parse(Object input, Class<T> type) throws ParseException {
446      try (ParserPipe pipe = createPipe(input)) {
447         return parseInner(pipe, getClassMeta(type));
448      }
449   }
450
451   /**
452    * Same as {@link #parse(Object, Type, Type...)} except the type has already been converted into a {@link ClassMeta}
453    * object.
454    *
455    * <p>
456    * This is mostly an internal method used by the framework.
457    *
458    * @param <T> The class type of the object being created.
459    * @param input
460    *    The input.
461    *    See {@link #parse(Object, Type, Type...)} for details.
462    * @param type The object type to create.
463    * @return The parsed object.
464    * @throws ParseException
465    *    If the input contains a syntax error or is malformed, or is not valid for the specified type.
466    */
467   public final <T> T parse(Object input, ClassMeta<T> type) throws ParseException {
468      try (ParserPipe pipe = createPipe(input)) {
469         return parseInner(pipe, type);
470      }
471   }
472
473   /**
474    * Entry point for all parsing calls.
475    *
476    * <p>
477    * Calls the {@link #doParse(ParserPipe, ClassMeta)} implementation class and catches/re-wraps any exceptions
478    * thrown.
479    *
480    * @param pipe The parser input.
481    * @param type The class type of the object to create.
482    * @param <T> The class type of the object to create.
483    * @return The parsed object.
484    * @throws ParseException
485    *    If the input contains a syntax error or is malformed, or is not valid for the specified type.
486    */
487   private <T> T parseInner(ParserPipe pipe, ClassMeta<T> type) throws ParseException {
488      if (type.isVoid())
489         return null;
490      try {
491         return doParse(pipe, type);
492      } catch (ParseException e) {
493         throw e;
494      } catch (StackOverflowError e) {
495         throw new ParseException(this, "Depth too deep.  Stack overflow occurred.");
496      } catch (IOException e) {
497         throw new ParseException(this, e, "I/O exception occurred.  exception={0}, message={1}.",
498            e.getClass().getSimpleName(), e.getLocalizedMessage());
499      } catch (Exception e) {
500         throw new ParseException(this, e, "Exception occurred.  exception={0}, message={1}.",
501            e.getClass().getSimpleName(), e.getLocalizedMessage());
502      } finally {
503         checkForWarnings();
504      }
505   }
506
507   /**
508    * Parses the contents of the specified reader and loads the results into the specified map.
509    *
510    * <p>
511    * Reader must contain something that serializes to a map (such as text containing a JSON object).
512    *
513    * <p>
514    * Used in the following locations:
515    * <ul class='spaced-list'>
516    *    <li>
517    *       The various character-based constructors in {@link ObjectMap} (e.g.
518    *       {@link ObjectMap#ObjectMap(CharSequence,Parser)}).
519    * </ul>
520    *
521    * @param <K> The key class type.
522    * @param <V> The value class type.
523    * @param input The input.  See {@link #parse(Object, ClassMeta)} for supported input types.
524    * @param m The map being loaded.
525    * @param keyType The class type of the keys, or <jk>null</jk> to default to <code>String.<jk>class</jk></code>.
526    * @param valueType The class type of the values, or <jk>null</jk> to default to whatever is being parsed.
527    * @return The same map that was passed in to allow this method to be chained.
528    * @throws ParseException If the input contains a syntax error or is malformed, or is not valid for the specified type.
529    * @throws UnsupportedOperationException If not implemented.
530    */
531   public final <K,V> Map<K,V> parseIntoMap(Object input, Map<K,V> m, Type keyType, Type valueType) throws ParseException {
532      try (ParserPipe pipe = createPipe(input)) {
533         return doParseIntoMap(pipe, m, keyType, valueType);
534      } catch (ParseException e) {
535         throw e;
536      } catch (Exception e) {
537         throw new ParseException(this, e);
538      } finally {
539         checkForWarnings();
540      }
541   }
542
543   /**
544    * Implementation method.
545    *
546    * <p>
547    * Default implementation throws an {@link UnsupportedOperationException}.
548    *
549    * @param pipe The parser input.
550    * @param m The map being loaded.
551    * @param keyType The class type of the keys, or <jk>null</jk> to default to <code>String.<jk>class</jk></code>.
552    * @param valueType The class type of the values, or <jk>null</jk> to default to whatever is being parsed.
553    * @return The same map that was passed in to allow this method to be chained.
554    * @throws Exception If thrown from underlying stream, or if the input contains a syntax error or is malformed.
555    */
556   protected <K,V> Map<K,V> doParseIntoMap(ParserPipe pipe, Map<K,V> m, Type keyType, Type valueType) throws Exception {
557      throw new UnsupportedOperationException("Parser '"+getClass().getName()+"' does not support this method.");
558   }
559
560   /**
561    * Parses the contents of the specified reader and loads the results into the specified collection.
562    *
563    * <p>
564    * Used in the following locations:
565    * <ul class='spaced-list'>
566    *    <li>
567    *       The various character-based constructors in {@link ObjectList} (e.g.
568    *       {@link ObjectList#ObjectList(CharSequence,Parser)}.
569    * </ul>
570    *
571    * @param <E> The element class type.
572    * @param input The input.  See {@link #parse(Object, ClassMeta)} for supported input types.
573    * @param c The collection being loaded.
574    * @param elementType The class type of the elements, or <jk>null</jk> to default to whatever is being parsed.
575    * @return The same collection that was passed in to allow this method to be chained.
576    * @throws ParseException
577    *    If the input contains a syntax error or is malformed, or is not valid for the specified type.
578    * @throws UnsupportedOperationException If not implemented.
579    */
580   public final <E> Collection<E> parseIntoCollection(Object input, Collection<E> c, Type elementType) throws ParseException {
581      try (ParserPipe pipe = createPipe(input)) {
582         return doParseIntoCollection(pipe, c, elementType);
583      } catch (ParseException e) {
584         throw e;
585      } catch (StackOverflowError e) {
586         throw new ParseException(this, "Depth too deep.  Stack overflow occurred.");
587      } catch (IOException e) {
588         throw new ParseException(this, e, "I/O exception occurred.  exception={0}, message={1}.",
589            e.getClass().getSimpleName(), e.getLocalizedMessage());
590      } catch (Exception e) {
591         throw new ParseException(this, e, "Exception occurred.  exception={0}, message={1}.",
592            e.getClass().getSimpleName(), e.getLocalizedMessage());
593      } finally {
594         checkForWarnings();
595      }
596   }
597
598   /**
599    * Implementation method.
600    *
601    * <p>
602    * Default implementation throws an {@link UnsupportedOperationException}.
603    *
604    * @param pipe The parser input.
605    * @param c The collection being loaded.
606    * @param elementType The class type of the elements, or <jk>null</jk> to default to whatever is being parsed.
607    * @return The same collection that was passed in to allow this method to be chained.
608    * @throws Exception If thrown from underlying stream, or if the input contains a syntax error or is malformed.
609    */
610   protected <E> Collection<E> doParseIntoCollection(ParserPipe pipe, Collection<E> c, Type elementType) throws Exception {
611      throw new UnsupportedOperationException("Parser '"+getClass().getName()+"' does not support this method.");
612   }
613
614   /**
615    * Parses the specified array input with each entry in the object defined by the {@code argTypes}
616    * argument.
617    *
618    * <p>
619    * Used for converting arrays (e.g. <js>"[arg1,arg2,...]"</js>) into an {@code Object[]} that can be passed
620    * to the {@code Method.invoke(target, args)} method.
621    *
622    * <p>
623    * Used in the following locations:
624    * <ul class='spaced-list'>
625    *    <li>
626    *       Used to parse argument strings in the {@link PojoIntrospector#invokeMethod(Method, Reader)} method.
627    * </ul>
628    *
629    * @param input The input.  Subclasses can support different input types.
630    * @param argTypes Specifies the type of objects to create for each entry in the array.
631    * @return An array of parsed objects.
632    * @throws ParseException
633    *    If the input contains a syntax error or is malformed, or is not valid for the specified type.
634    */
635   public final Object[] parseArgs(Object input, Type[] argTypes) throws ParseException {
636      try (ParserPipe pipe = createPipe(input)) {
637         return doParse(pipe, getArgsClassMeta(argTypes));
638      } catch (ParseException e) {
639         throw e;
640      } catch (StackOverflowError e) {
641         throw new ParseException(this, "Depth too deep.  Stack overflow occurred.");
642      } catch (IOException e) {
643         throw new ParseException(this, e, "I/O exception occurred.  exception={0}, message={1}.",
644            e.getClass().getSimpleName(), e.getLocalizedMessage());
645      } catch (Exception e) {
646         throw new ParseException(this, e, "Exception occurred.  exception={0}, message={1}.",
647            e.getClass().getSimpleName(), e.getLocalizedMessage());
648      } finally {
649         checkForWarnings();
650      }
651   }
652
653   /**
654    * Converts the specified string to the specified type.
655    *
656    * @param outer
657    *    The outer object if we're converting to an inner object that needs to be created within the context
658    *    of an outer object.
659    * @param s The string to convert.
660    * @param type The class type to convert the string to.
661    * @return The string converted as an object of the specified type.
662    * @throws Exception If the input contains a syntax error or is malformed, or is not valid for the specified type.
663    * @param <T> The class type to convert the string to.
664    */
665   @SuppressWarnings({ "unchecked", "rawtypes" })
666   protected final <T> T convertAttrToType(Object outer, String s, ClassMeta<T> type) throws Exception {
667      if (s == null)
668         return null;
669
670      if (type == null)
671         type = (ClassMeta<T>)object();
672      PojoSwap swap = type.getPojoSwap(this);
673      ClassMeta<?> sType = swap == null ? type : swap.getSwapClassMeta(this);
674
675      Object o = s;
676      if (sType.isChar())
677         o = parseCharacter(s);
678      else if (sType.isNumber())
679         if (type.canCreateNewInstanceFromNumber(outer))
680            o = type.newInstanceFromNumber(this, outer, parseNumber(s, type.getNewInstanceFromNumberClass()));
681         else
682            o = parseNumber(s, (Class<? extends Number>)sType.getInnerClass());
683      else if (sType.isBoolean())
684         o = Boolean.parseBoolean(s);
685      else if (! (sType.isCharSequence() || sType.isObject())) {
686         if (sType.canCreateNewInstanceFromString(outer))
687            o = sType.newInstanceFromString(outer, s);
688         else
689            throw new ParseException(this, "Invalid conversion from string to class ''{0}''", type);
690      }
691
692      if (swap != null)
693         o = swap.unswap(this, o, type);
694
695      return (T)o;
696   }
697
698   /**
699    * Convenience method for calling the {@link ParentProperty @ParentProperty} method on the specified object if it
700    * exists.
701    *
702    * @param cm The class type of the object.
703    * @param o The object.
704    * @param parent The parent to set.
705    * @throws Exception
706    */
707   protected static final void setParent(ClassMeta<?> cm, Object o, Object parent) throws Exception {
708      Setter m = cm.getParentProperty();
709      if (m != null)
710         m.set(o, parent);
711   }
712
713   /**
714    * Convenience method for calling the {@link NameProperty @NameProperty} method on the specified object if it exists.
715    *
716    * @param cm The class type of the object.
717    * @param o The object.
718    * @param name The name to set.
719    * @throws Exception
720    */
721   protected static final void setName(ClassMeta<?> cm, Object o, Object name) throws Exception {
722      if (cm != null) {
723         Setter m = cm.getNameProperty();
724         if (m != null)
725            m.set(o, name);
726      }
727   }
728
729   /**
730    * Returns the listener associated with this session.
731    *
732    * @return The listener associated with this session, or <jk>null</jk> if there is no listener.
733    */
734   public ParserListener getListener() {
735      return listener;
736   }
737
738   /**
739    * Returns the listener associated with this session.
740    *
741    * @param c The listener class to cast to.
742    * @return The listener associated with this session, or <jk>null</jk> if there is no listener.
743    */
744   @SuppressWarnings("unchecked")
745   public <T extends ParserListener> T getListener(Class<T> c) {
746      return (T)listener;
747   }
748
749   /**
750    * The {@link #createPipe(Object)} method should call this method to set the pipe for debugging purposes.
751    *
752    * @param pipe The pipe created for this session.
753    * @return The same pipe.
754    */
755   protected ParserPipe setPipe(ParserPipe pipe) {
756      this.pipe = pipe;
757      return pipe;
758   }
759
760   /**
761    * Returns the current position into the reader or input stream.
762    *
763    * @return
764    *    The current position into the reader or input stream.
765    *    <br>Never <jk>null</jk>.
766    */
767   public Position getPosition() {
768      if (mark.line != -1 || mark.column != -1 || mark.position != -1)
769         return mark;
770      if (pipe == null)
771         return Position.UNKNOWN;
772      return pipe.getPosition();
773   }
774
775   /**
776    * Marks the current position.
777    */
778   protected void mark() {
779      if (pipe != null) {
780         Position p = pipe.getPosition();
781         mark.line = p.line;
782         mark.column = p.column;
783         mark.position = p.position;
784      }
785   }
786
787   /**
788    * Unmarks the current position.
789    */
790   protected void unmark() {
791      mark.line = -1;
792      mark.column = -1;
793      mark.position = -1;
794   }
795
796   /**
797    * Returns the input as a string.
798    *
799    * <p>
800    * This always returns a value for input of type {@link CharSequence}.
801    * <br>For other input types, use {@link BeanContext#BEAN_debug} setting to enable caching to a string
802    * before parsing so that this method returns the input.
803    *
804    * @return The input as a string, or <jk>null</jk> if no pipe has been created or we're reading from an uncached reader or input stream source.
805    */
806   public String getInputAsString() {
807      return pipe == null ? null : pipe.getInputAsString();
808   }
809
810   //-----------------------------------------------------------------------------------------------------------------
811   // Properties
812   //-----------------------------------------------------------------------------------------------------------------
813
814   /**
815    * Configuration property:  Trim parsed strings.
816    *
817    * @see Parser#PARSER_trimStrings
818    * @return
819    *    <jk>true</jk> if string values will be trimmed of whitespace using {@link String#trim()} before being added to
820    *    the POJO.
821    */
822   protected final boolean isTrimStrings() {
823      return ctx.isTrimStrings();
824   }
825
826   /**
827    * Configuration property:  Strict mode.
828    *
829    * @see Parser#PARSER_strict
830    * @return
831    *    <jk>true</jk> if strict mode for the parser is enabled.
832    */
833   protected final boolean isStrict() {
834      return ctx.isStrict();
835   }
836
837   /**
838    * Configuration property:  Auto-close streams.
839    *
840    * @see Parser#PARSER_autoCloseStreams
841    * @return
842    *    <jk>true</jk> if <l>InputStreams</l> and <l>Readers</l> passed into parsers will be closed
843    *    after parsing is complete.
844    */
845   protected final boolean isAutoCloseStreams() {
846      return ctx.isAutoCloseStreams();
847   }
848
849   /**
850    * Configuration property:  Unbuffered.
851    *
852    * @see Parser#PARSER_unbuffered
853    * @return
854    *    <jk>true</jk> if parsers don't use internal buffering during parsing.
855    */
856   protected final boolean isUnbuffered() {
857      return ctx.isUnbuffered();
858   }
859
860   /**
861    * Configuration property:  Debug output lines.
862    *
863    * @see Parser#PARSER_debugOutputLines
864    * @return
865    *    The number of lines of input before and after the error location to be printed as part of the exception message.
866    */
867   protected final int getDebugOutputLines() {
868      return ctx.getDebugOutputLines();
869   }
870
871   /**
872    * Configuration property:  Parser listener.
873    *
874    * @see Parser#PARSER_listener
875    * @return
876    *    Class used to listen for errors and warnings that occur during parsing.
877    */
878   protected final Class<? extends ParserListener> getListenerClass() {
879      return ctx.getListenerClass();
880   }
881}