Class ParserSession

Direct Known Subclasses:
InputStreamParserSession, ReaderParserSession

public class ParserSession extends BeanSession
Session object that lives for the duration of a single use of Parser.
Notes:
  • This class is not thread safe and is typically discarded after one use.
See Also:
  • Constructor Details

  • Method Details

    • create

      public static ParserSession.Builder create(Parser ctx)
      Creates a new builder for this object.
      Parameters:
      ctx - The context creating this session.
      Returns:
      A new builder.
    • doParse

      protected <T> T doParse(ParserPipe pipe, ClassMeta<T> type) throws IOException, ParseException, ExecutableException
      Workhorse method.

      Subclasses are expected to implement this method or Parser.doParse(ParserSession,ParserPipe,ClassMeta).

      The default implementation of this method simply calls Parser.doParse(ParserSession,ParserPipe,ClassMeta).

      Type Parameters:
      T - The class type of the object to create.
      Parameters:
      pipe - Where to get the input from.
      type - The class type of the object to create. If null or Object.class, object type is based on what's being parsed. For example, when parsing JSON text, it may return a String, Number, JsonMap, etc...
      Returns:
      The parsed object.
      Throws:
      IOException - Thrown by underlying stream.
      ParseException - Malformed input encountered.
      ExecutableException - Exception occurred on invoked constructor/method/field.
    • isReaderParser

      public boolean isReaderParser()
      Returns true if this parser subclasses from ReaderParser.
      Returns:
      true if this parser subclasses from ReaderParser.
    • createPipe

      protected ParserPipe createPipe(Object input)
      Wraps the specified input object into a ParserPipe object so that it can be easily converted into a stream or reader.
      Parameters:
      input - The input.
      For character-based parsers, this can be any of the following types:
      For byte-based parsers, this can be any of the following types:
      Returns:
      A new ParserPipe wrapper around the specified input object.
    • getLastLocation

      public final JsonMap getLastLocation()
      Returns information used to determine at what location in the parse a failure occurred.
      Returns:
      A map, typically containing something like {line:123,column:456,currentProperty:"foobar"}
    • getJavaMethod

      protected final Method getJavaMethod()
      Returns the Java method that invoked this parser.

      When using the REST API, this is the Java method invoked by the REST call. Can be used to access annotations defined on the method or class.

      Returns:
      The Java method that invoked this parser.
    • getOuter

      protected final Object getOuter()
      Returns the outer object used for instantiating top-level non-static member classes.

      When using the REST API, this is the servlet object.

      Returns:
      The outer object.
    • setCurrentProperty

      protected final void setCurrentProperty(BeanPropertyMeta currentProperty)
      Sets the current bean property being parsed for proper error messages.
      Parameters:
      currentProperty - The current property being parsed.
    • setCurrentClass

      protected final void setCurrentClass(ClassMeta<?> currentClass)
      Sets the current class being parsed for proper error messages.
      Parameters:
      currentClass - The current class being parsed.
    • trim

      protected final <K> K trim(K o)
      Trims the specified object if it's a String and isTrimStrings() returns true.
      Type Parameters:
      K - The object type.
      Parameters:
      o - The object to trim.
      Returns:
      The trimmed string if it's a string.
    • trim

      protected final String trim(String s)
      Trims the specified string if isTrimStrings() returns true.
      Parameters:
      s - The input string to trim.
      Returns:
      The trimmed string, or null if the input was null.
    • cast

      protected final Object cast(JsonMap m, BeanPropertyMeta pMeta, ClassMeta<?> eType)
      Converts the specified JsonMap into a bean identified by the "_type" property in the map.
      Parameters:
      m - The map to convert to a bean.
      pMeta - The current bean property being parsed.
      eType - The current expected type being parsed.
      Returns:
      The converted bean, or the same map if the "_type" entry wasn't found or didn't resolve to a bean.
    • getClassMeta

      protected final ClassMeta<?> getClassMeta(String typeName, BeanPropertyMeta pMeta, ClassMeta<?> eType)
      Give the specified dictionary name, resolve it to a class.
      Parameters:
      typeName - The dictionary name to resolve.
      pMeta - The bean property we're currently parsing.
      eType - The expected type we're currently parsing.
      Returns:
      The resolved class, or null if the type name could not be resolved.
    • onBeanSetterException

      protected final void onBeanSetterException(BeanPropertyMeta p, Throwable t)
      Specialized warning when an exception is thrown while executing a bean setter.
      Parameters:
      p - The bean map entry representing the bean property.
      t - The throwable that the bean setter threw.
    • onUnknownProperty

      protected final <T> void onUnknownProperty(String propertyName, BeanMap<T> beanMap, Object value) throws ParseException
      Method that gets called when an unknown bean property name is encountered.
      Type Parameters:
      T - The class type of the bean map that doesn't have the expected property.
      Parameters:
      propertyName - The unknown bean property name.
      beanMap - The bean that doesn't have the expected property.
      value - The parsed value.
      Throws:
      ParseException - Automatically thrown if BeanContext.Builder.ignoreUnknownBeanProperties() setting on this parser is false
    • parse

      public final <T> T parse(Object input, Type type, Type... args) throws ParseException, IOException
      Parses input into the specified object type.

      The type can be a simple type (e.g. beans, strings, numbers) or parameterized type (collections/maps).

      Examples:

      ReaderParser parser = JsonParser.DEFAULT; // Parse into a linked-list of strings. List list1 = parser.parse(json, LinkedList.class, String.class); // Parse into a linked-list of beans. List list2 = parser.parse(json, LinkedList.class, MyBean.class); // Parse into a linked-list of linked-lists of strings. List list3 = parser.parse(json, LinkedList.class, LinkedList.class, String.class); // Parse into a map of string keys/values. Map map1 = parser.parse(json, TreeMap.class, String.class, String.class); // Parse into a map containing string keys and values of lists containing beans. Map map2 = parser.parse(json, TreeMap.class, String.class, List.class, MyBean.class);

      Collection classes are assumed to be followed by zero or one objects indicating the element type.

      Map classes are assumed to be followed by zero or two meta objects indicating the key and value types.

      The array can be arbitrarily long to indicate arbitrarily complex data structures.

      Notes:
      Type Parameters:
      T - The class type of the object to create.
      Parameters:
      input - The input.
      Character-based parsers can handle the following input class types:
      Stream-based parsers can handle the following input class types:
      type - The object type to create.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      args - The type arguments of the class if it's a collection or map.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      Ignored if the main type is not a map or collection.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
      IOException - Thrown by the underlying stream.
      See Also:
    • parse

      public final <T> T parse(String input, Type type, Type... args) throws ParseException
      Same as parse(Object,Type,Type...) but parses from a string and doesn't throw an IOException.
      Type Parameters:
      T - The class type of the object to create.
      Parameters:
      input - The input.
      Character-based parsers can handle the following input class types:
      Stream-based parsers can handle the following input class types:
      type - The object type to create.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      args - The type arguments of the class if it's a collection or map.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      Ignored if the main type is not a map or collection.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
      See Also:
    • parse

      public final <T> T parse(Object input, Class<T> type) throws ParseException, IOException
      Same as parse(Object, Type, Type...) except optimized for a non-parameterized class.

      This is the preferred parse method for simple types since you don't need to cast the results.

      Examples:

      ReaderParser parser = JsonParser.DEFAULT; // Parse into a string. String string = parser.parse(json, String.class); // Parse into a bean. MyBean bean = parser.parse(json, MyBean.class); // Parse into a bean array. MyBean[] beanArray = parser.parse(json, MyBean[].class); // Parse into a linked-list of objects. List list = parser.parse(json, LinkedList.class); // Parse into a map of object keys/values. Map map = parser.parse(json, TreeMap.class);

      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      input - The input. See parse(Object, Type, Type...) for details.
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
      IOException - Thrown by the underlying stream.
    • parse

      public final <T> T parse(String input, Class<T> type) throws ParseException
      Same as parse(Object, Class) but parses from a string and doesn't throw an IOException.

      This is the preferred parse method for simple types since you don't need to cast the results.

      Examples:

      ReaderParser parser = JsonParser.DEFAULT; // Parse into a string. String string = parser.parse(json, String.class); // Parse into a bean. MyBean bean = parser.parse(json, MyBean.class); // Parse into a bean array. MyBean[] beanArray = parser.parse(json, MyBean[].class); // Parse into a linked-list of objects. List list = parser.parse(json, LinkedList.class); // Parse into a map of object keys/values. Map map = parser.parse(json, TreeMap.class);

      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      input - The input. See parse(Object, Type, Type...) for details.
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
    • parse

      public final <T> T parse(Object input, ClassMeta<T> type) throws ParseException, IOException
      Same as parse(Object, Type, Type...) except the type has already been converted into a ClassMeta object.

      This is mostly an internal method used by the framework.

      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      input - The input. See parse(Object, Type, Type...) for details.
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
      IOException - Thrown by the underlying stream.
    • parse

      public final <T> T parse(String input, ClassMeta<T> type) throws ParseException
      Same as parse(Object, ClassMeta) except parses from a string and doesn't throw an IOException.

      This is mostly an internal method used by the framework.

      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      input - The input. See parse(Object, Type, Type...) for details.
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      ParseException - Malformed input encountered.
    • parseIntoMap

      public final <K, V> Map<K,V> parseIntoMap(Object input, Map<K,V> m, Type keyType, Type valueType) throws ParseException
      Parses the contents of the specified reader and loads the results into the specified map.

      Reader must contain something that serializes to a map (such as text containing a JSON object).

      Used in the following locations:

      Type Parameters:
      K - The key class type.
      V - The value class type.
      Parameters:
      input - The input. See parse(Object, ClassMeta) for supported input types.
      m - The map being loaded.
      keyType - The class type of the keys, or null to default to String.class.
      valueType - The class type of the values, or null to default to whatever is being parsed.
      Returns:
      The same map that was passed in to allow this method to be chained.
      Throws:
      ParseException - Malformed input encountered.
      UnsupportedOperationException - If not implemented.
    • doParseIntoMap

      protected <K, V> Map<K,V> doParseIntoMap(ParserPipe pipe, Map<K,V> m, Type keyType, Type valueType) throws Exception
      Implementation method.

      Default implementation throws an UnsupportedOperationException.

      Type Parameters:
      K - The key type.
      V - The value type.
      Parameters:
      pipe - The parser input.
      m - The map being loaded.
      keyType - The class type of the keys, or null to default to String.class.
      valueType - The class type of the values, or null to default to whatever is being parsed.
      Returns:
      The same map that was passed in to allow this method to be chained.
      Throws:
      Exception - If thrown from underlying stream, or if the input contains a syntax error or is malformed.
    • parseIntoCollection

      public final <E> Collection<E> parseIntoCollection(Object input, Collection<E> c, Type elementType) throws ParseException
      Parses the contents of the specified reader and loads the results into the specified collection.

      Used in the following locations:

      Type Parameters:
      E - The element class type.
      Parameters:
      input - The input. See parse(Object, ClassMeta) for supported input types.
      c - The collection being loaded.
      elementType - The class type of the elements, or null to default to whatever is being parsed.
      Returns:
      The same collection that was passed in to allow this method to be chained.
      Throws:
      ParseException - Malformed input encountered.
      UnsupportedOperationException - If not implemented.
    • doParseIntoCollection

      protected <E> Collection<E> doParseIntoCollection(ParserPipe pipe, Collection<E> c, Type elementType) throws Exception
      Implementation method.

      Default implementation throws an UnsupportedOperationException.

      Type Parameters:
      E - The element type.
      Parameters:
      pipe - The parser input.
      c - The collection being loaded.
      elementType - The class type of the elements, or null to default to whatever is being parsed.
      Returns:
      The same collection that was passed in to allow this method to be chained.
      Throws:
      Exception - If thrown from underlying stream, or if the input contains a syntax error or is malformed.
    • parseArgs

      public final Object[] parseArgs(Object input, Type[] argTypes) throws ParseException
      Parses the specified array input with each entry in the object defined by the argTypes argument.

      Used for converting arrays (e.g. "[arg1,arg2,...]") into an Object[] that can be passed to the Method.invoke(target, args) method.

      Used in the following locations:

      Parameters:
      input - The input. Subclasses can support different input types.
      argTypes - Specifies the type of objects to create for each entry in the array.
      Returns:
      An array of parsed objects.
      Throws:
      ParseException - Malformed input encountered.
    • convertAttrToType

      protected final <T> T convertAttrToType(Object outer, String s, ClassMeta<T> type) throws ParseException
      Converts the specified string to the specified type.
      Type Parameters:
      T - The class type to convert the string to.
      Parameters:
      outer - The outer object if we're converting to an inner object that needs to be created within the context of an outer object.
      s - The string to convert.
      type - The class type to convert the string to.
      Returns:
      The string converted as an object of the specified type.
      Throws:
      ParseException - Malformed input encountered.
      ExecutableException - Exception occurred on invoked constructor/method/field.
    • setParent

      protected static final void setParent(ClassMeta<?> cm, Object o, Object parent) throws ExecutableException
      Convenience method for calling the @ParentProperty method on the specified object if it exists.
      Parameters:
      cm - The class type of the object.
      o - The object.
      parent - The parent to set.
      Throws:
      ExecutableException - Exception occurred on invoked constructor/method/field.
    • setName

      protected static final void setName(ClassMeta<?> cm, Object o, Object name) throws ExecutableException
      Convenience method for calling the @NameProperty method on the specified object if it exists.
      Parameters:
      cm - The class type of the object.
      o - The object.
      name - The name to set.
      Throws:
      ExecutableException - Exception occurred on invoked constructor/method/field.
    • getListener

      public <T extends ParserListener> T getListener(Class<T> c)
      Returns the listener associated with this session.
      Type Parameters:
      T - The listener type.
      Parameters:
      c - The listener class to cast to.
      Returns:
      The listener associated with this session, or null if there is no listener.
    • setPipe

      protected ParserPipe setPipe(ParserPipe pipe)
      The createPipe(Object) method should call this method to set the pipe for debugging purposes.
      Parameters:
      pipe - The pipe created for this session.
      Returns:
      The same pipe.
    • getPosition

      Returns the current position into the reader or input stream.
      Returns:
      The current position into the reader or input stream.
      Never null.
    • mark

      protected void mark()
      Marks the current position.
    • unmark

      protected void unmark()
      Unmarks the current position.
    • getInputAsString

      Returns the input as a string.

      This always returns a value for input of type CharSequence.
      For other input types, use Context.Builder.debug() setting to enable caching to a string before parsing so that this method returns the input.

      Returns:
      The input as a string, or null if no pipe has been created or we're reading from an uncached reader or input stream source.
    • unswap

      protected Object unswap(ObjectSwap swap, Object o, ClassMeta<?> eType) throws ParseException
      Invokes the specified swap on the specified object.
      Parameters:
      swap - The swap to invoke.
      o - The input object.
      eType - The expected type.
      Returns:
      The swapped object.
      Throws:
      ParseException - If swap method threw an exception.
    • getStringBuilder

      protected final StringBuilder getStringBuilder()
      Creates a reusable StringBuilder object from an internal pool.

      String builders are returned to the pool by calling returnStringBuilder(StringBuilder).

      Returns:
      A new or previously returned string builder.
    • returnStringBuilder

      protected final void returnStringBuilder(StringBuilder sb)
      Returns a StringBuilder object back into the internal reuse pool.
      Parameters:
      sb - The string builder to return to the pool. No-op if null.
    • isAutoCloseStreams

      protected final boolean isAutoCloseStreams()
      Auto-close streams.
      Returns:
      true if InputStreams and Readers passed into parsers will be closed after parsing is complete.
      See Also:
    • getDebugOutputLines

      protected final int getDebugOutputLines()
      Debug output lines.
      Returns:
      The number of lines of input before and after the error location to be printed as part of the exception message.
      See Also:
    • getListener

      Returns the listener associated with this session.
      Returns:
      The listener associated with this session, or null if there is no listener.
    • isStrict

      protected final boolean isStrict()
      Strict mode.
      Returns:
      true if strict mode for the parser is enabled.
      See Also:
    • isTrimStrings

      protected final boolean isTrimStrings()
      Trim parsed strings.
      Returns:
      true if string values will be trimmed of whitespace using String.trim() before being added to the POJO.
      See Also:
    • isUnbuffered

      protected final boolean isUnbuffered()
      Unbuffered.
      Returns:
      true if parsers don't use internal buffering during parsing.
      See Also:
    • getSchema

      public final HttpPartSchema getSchema()
      HTTP part schema of object being parsed.
      Returns:
      HTTP part schema of object being parsed, or null if not specified.
    • getListenerClass

      protected final Class<? extends ParserListener> getListenerClass()
      Parser listener.
      Returns:
      Class used to listen for errors and warnings that occur during parsing.
      See Also:
    • properties

      protected JsonMap properties()
      Description copied from class: ContextSession
      Returns the properties on this bean as a map for debugging.
      Overrides:
      properties in class ContextSession
      Returns:
      The properties on this bean as a map for debugging.