Class ParserSession
- Direct Known Subclasses:
InputStreamParserSession,ReaderParserSession
Parser.
Notes:
- This class is not thread safe and is typically discarded after one use.
See Also:
-
Nested Class Summary
Nested Classes -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedParserSession(ParserSession.Builder builder) Constructor. -
Method Summary
Modifier and TypeMethodDescriptionprotected final Objectcast(JsonMap m, BeanPropertyMeta pMeta, ClassMeta<?> eType) Converts the specifiedJsonMap into a bean identified by the"_type" property in the map.protected final <T> TconvertAttrToType(Object outer, String s, ClassMeta<T> type) Converts the specified string to the specified type.static ParserSession.BuilderCreates a new builder for this object.protected ParserPipecreatePipe(Object input) Wraps the specified input object into aParserPipeobject so that it can be easily converted into a stream or reader.protected <T> TdoParse(ParserPipe pipe, ClassMeta<T> type) Workhorse method.protected <E> Collection<E>doParseIntoCollection(ParserPipe pipe, Collection<E> c, Type elementType) Implementation method.protected <K,V> Map<K, V> doParseIntoMap(ParserPipe pipe, Map<K, V> m, Type keyType, Type valueType) Implementation method.protected final ClassMeta<?>getClassMeta(String typeName, BeanPropertyMeta pMeta, ClassMeta<?> eType) Give the specified dictionary name, resolve it to a class.protected final intDebug output lines.Returns the input as a string.protected final MethodReturns the Java method that invoked this parser.final JsonMapReturns information used to determine at what location in the parse a failure occurred.Returns the listener associated with this session.<T extends ParserListener>
TgetListener(Class<T> c) Returns the listener associated with this session.protected final Class<? extends ParserListener>Parser listener.protected final ObjectgetOuter()Returns the outer object used for instantiating top-level non-static member classes.Returns the current position into the reader or input stream.final HttpPartSchemaHTTP part schema of object being parsed.protected final StringBuilderCreates a reusableStringBuilderobject from an internal pool.protected final booleanAuto-close streams.booleanReturnstrue if this parser subclasses fromReaderParser.protected final booleanisStrict()Strict mode.protected final booleanTrim parsed strings.protected final booleanUnbuffered.protected voidmark()Marks the current position.protected final voidSpecialized warning when an exception is thrown while executing a bean setter.protected final <T> voidonUnknownProperty(String propertyName, BeanMap<T> beanMap, Object value) Method that gets called when an unknown bean property name is encountered.final <T> TSame asparse(Object, Type, Type...)except optimized for a non-parameterized class.final <T> TParses input into the specified object type.final <T> TSame asparse(Object, Type, Type...)except the type has already been converted into aClassMetaobject.final <T> TSame asparse(Object, Class)but parses from a string and doesn't throw anIOException.final <T> TSame asparse(Object,Type,Type...)but parses from a string and doesn't throw anIOException.final <T> TSame asparse(Object, ClassMeta)except parses from a string and doesn't throw anIOException.final Object[]Parses the specified array input with each entry in the object defined by theargTypesargument.final <E> Collection<E>parseIntoCollection(Object input, Collection<E> c, Type elementType) Parses the contents of the specified reader and loads the results into the specified collection.final <K,V> Map<K, V> parseIntoMap(Object input, Map<K, V> m, Type keyType, Type valueType) Parses the contents of the specified reader and loads the results into the specified map.Returns the properties on this bean as a map for debugging.protected final voidReturns aStringBuilderobject back into the internal reuse pool.protected final voidsetCurrentClass(ClassMeta<?> currentClass) Sets the current class being parsed for proper error messages.protected final voidsetCurrentProperty(BeanPropertyMeta currentProperty) Sets the current bean property being parsed for proper error messages.protected static final voidConvenience method for calling the@NamePropertymethod on the specified object if it exists.protected static final voidConvenience method for calling the@ParentPropertymethod on the specified object if it exists.protected ParserPipesetPipe(ParserPipe pipe) ThecreatePipe(Object)method should call this method to set the pipe for debugging purposes.protected final StringTrims the specified string ifisTrimStrings()returnstrue .protected final <K> Ktrim(K o) protected voidunmark()Unmarks the current position.protected Objectunswap(ObjectSwap swap, Object o, ClassMeta<?> eType) Invokes the specified swap on the specified object.Methods inherited from class org.apache.juneau.BeanSession
addWarning, convertToMemberType, convertToMemberType, convertToType, convertToType, convertToType, create, getAnnotationProvider, getArgsClassMeta, getBeanClassVisibility, getBeanConstructorVisibility, getBeanDictionary, getBeanFieldVisibility, getBeanMeta, getBeanMethodVisibility, getBeanRegistry, getBeanTypePropertyName, getBeanTypePropertyName, getClassMeta, getClassMeta, getClassMetaForObject, getClassMetaForObject, getLocale, getMediaType, getNamePropertyName, getNotBeanClasses, getNotBeanPackagesNames, getPropertyNamer, getSwaps, getTimeZone, getTimeZoneId, isBean, isBean, isBeanMapPutReturnsOldValue, isBeansRequireDefaultConstructor, isBeansRequireSerializable, isBeansRequireSettersForGetters, isBeansRequireSomeProperties, isFindFluentSetters, isIgnoreInvocationExceptionsOnGetters, isIgnoreInvocationExceptionsOnSetters, isIgnoreMissingSetters, isIgnoreUnknownBeanProperties, isIgnoreUnknownNullBeanProperties, isSortProperties, isUseEnumNames, isUseInterfaceProxies, isUseJavaBeanIntrospector, newBean, newBean, newBeanMap, newBeanMap, newGenericMap, object, string, toArray, toBeanMap, toBeanMap, toBeanMapMethods inherited from class org.apache.juneau.ContextSession
checkForWarnings, getContext, getSessionProperties, getWarnings, isDebug, toString
-
Constructor Details
-
ParserSession
Constructor.- Parameters:
builder- The builder for this object.
-
-
Method Details
-
create
Creates a new builder for this object.- Parameters:
ctx- The context creating this session.
Cannot benull .- Returns:
- A new builder.
-
setName
protected static final void setName(ClassMeta<?> cm, Object o, Object name) throws ExecutableException Convenience method for calling the@NamePropertymethod 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.
-
setParent
protected static final void setParent(ClassMeta<?> cm, Object o, Object parent) throws ExecutableException Convenience method for calling the@ParentPropertymethod 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.
-
getInputAsString
Returns the input as a string.This always returns a value for input of type
CharSequence.
For other input types, useContext.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.
-
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"}
-
getListener
Returns the listener associated with this session.- Returns:
- The listener associated with this session, or
null if there is no listener.
-
getListener
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.
-
getPosition
Returns the current position into the reader or input stream.- Returns:
- The current position into the reader or input stream.
Nevernull .
-
getSchema
HTTP part schema of object being parsed.- Returns:
- HTTP part schema of object being parsed, or
null if not specified.
-
isReaderParser
Returnstrue if this parser subclasses fromReaderParser.- Returns:
true if this parser subclasses fromReaderParser.
-
parse
Same asparse(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. Stringstring =parser .parse(json , String.class );// Parse into a bean. MyBeanbean =parser .parse(json , MyBean.class );// Parse into a bean array. MyBean[]beanArray =parser .parse(json , MyBean[].class );// Parse into a linked-list of objects. Listlist =parser .parse(json , LinkedList.class );// Parse into a map of object keys/values. Mapmap =parser .parse(json , TreeMap.class );- Type Parameters:
T- The class type of the object being created.- Parameters:
input- The input. Seeparse(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
Same asparse(Object, Type, Type...)except the type has already been converted into aClassMetaobject.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. Seeparse(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
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. Listlist1 =parser .parse(json , LinkedList.class , String.class );// Parse into a linked-list of beans. Listlist2 =parser .parse(json , LinkedList.class , MyBean.class );// Parse into a linked-list of linked-lists of strings. Listlist3 =parser .parse(json , LinkedList.class , LinkedList.class , String.class );// Parse into a map of string keys/values. Mapmap1 =parser .parse(json , TreeMap.class , String.class , String.class );// Parse into a map containing string keys and values of lists containing beans. Mapmap2 =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:
-
Use the
parse(Object, Class)method instead if you don't need a parameterized map/collection.
- 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:null ReaderCharSequenceInputStreamcontaining UTF-8 encoded text (or charset defined byReaderParser.Builder.streamCharset(Charset)property value).containing UTF-8 encoded text (or charset defined bybyte []ReaderParser.Builder.streamCharset(Charset)property value).Filecontaining system encoded text (or charset defined byReaderParser.Builder.fileCharset(Charset)property value).
Stream-based parsers can handle the following input class types:null InputStreambyte []File
type- The object type to create.
Can be any of the following:ClassMeta,Class,ParameterizedType,GenericArrayTypeargs- 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:
-
Use the
-
parse
Same asparse(Object, Class)but parses from a string and doesn't throw anIOException.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. Stringstring =parser .parse(json , String.class );// Parse into a bean. MyBeanbean =parser .parse(json , MyBean.class );// Parse into a bean array. MyBean[]beanArray =parser .parse(json , MyBean[].class );// Parse into a linked-list of objects. Listlist =parser .parse(json , LinkedList.class );// Parse into a map of object keys/values. Mapmap =parser .parse(json , TreeMap.class );- Type Parameters:
T- The class type of the object being created.- Parameters:
input- The input. Seeparse(Object, Type, Type...)for details.type- The object type to create.- Returns:
- The parsed object.
- Throws:
ParseException- Malformed input encountered.
-
parse
Same asparse(Object, ClassMeta)except parses from a string and doesn't throw anIOException.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. Seeparse(Object, Type, Type...)for details.type- The object type to create.- Returns:
- The parsed object.
- Throws:
ParseException- Malformed input encountered.
-
parse
Same asparse(Object,Type,Type...)but parses from a string and doesn't throw anIOException.- 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:null ReaderCharSequenceInputStreamcontaining UTF-8 encoded text (or charset defined byReaderParser.Builder.streamCharset(Charset)property value).containing UTF-8 encoded text (or charset defined bybyte []ReaderParser.Builder.streamCharset(Charset)property value).Filecontaining system encoded text (or charset defined byReaderParser.Builder.fileCharset(Charset)property value).
Stream-based parsers can handle the following input class types:null InputStreambyte []File
type- The object type to create.
Can be any of the following:ClassMeta,Class,ParameterizedType,GenericArrayTypeargs- 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:
-
parseArgs
Parses the specified array input with each entry in the object defined by theargTypesargument.Used for converting arrays (e.g.
"[arg1,arg2,...]" ) into anObject[]that can be passed to theMethod.invoke(target, args)method.Used in the following locations:
-
Used to parse argument strings in the
ObjectIntrospector.invokeMethod(Method, Reader)method.
- 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.
-
Used to parse argument strings in the
-
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:
-
The various character-based constructors in
JsonList(e.g.JsonList(CharSequence,Parser).
- Type Parameters:
E- The element class type.- Parameters:
input- The input. Seeparse(Object, ClassMeta)for supported input types.c- The collection being loaded.elementType- The class type of the elements, ornull 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.
-
The various character-based constructors in
-
parseIntoMap
public final <K,V> Map<K,V> parseIntoMap(Object input, Map<K, V> m, Type keyType, Type valueType) throws ParseExceptionParses 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:
-
The various character-based constructors in
JsonMap(e.g.JsonMap(CharSequence,Parser)).
- Type Parameters:
K- The key class type.V- The value class type.- Parameters:
input- The input. Seeparse(Object, ClassMeta)for supported input types.m- The map being loaded.keyType- The class type of the keys, ornull to default toString..class valueType- The class type of the values, ornull 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.
-
The various character-based constructors in
-
cast
Converts the specifiedJsonMap 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.
-
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.
-
createPipe
Wraps the specified input object into aParserPipeobject 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:null ReaderCharSequenceInputStreamcontaining UTF-8 encoded text (or whatever the encoding specified byReaderParser.Builder.streamCharset(Charset)).containing UTF-8 encoded text (or whatever the encoding specified bybyte []ReaderParser.Builder.streamCharset(Charset)).Filecontaining system encoded text (or whatever the encoding specified byReaderParser.Builder.fileCharset(Charset)).
For byte-based parsers, this can be any of the following types:null InputStreambyte []FileCharSequencecontaining encoded bytes according to theInputStreamParser.Builder.binaryFormat(BinaryFormat)setting.
- Returns:
- A new
ParserPipewrapper around the specified input object.
-
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. Ifnull orObject., object type is based on what's being parsed. For example, when parsing JSON text, it may return aclass 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.
-
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, ornull 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.
-
doParseIntoMap
protected <K,V> Map<K,V> doParseIntoMap(ParserPipe pipe, Map<K, V> m, Type keyType, Type valueType) throws ExceptionImplementation 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, ornull to default toString..class valueType- The class type of the values, ornull 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.
-
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.
-
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:
-
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.
-
getListenerClass
Parser listener.- Returns:
- Class used to listen for errors and warnings that occur during parsing.
- See Also:
-
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.
-
getStringBuilder
Creates a reusableStringBuilderobject from an internal pool.String builders are returned to the pool by calling
returnStringBuilder(StringBuilder).- Returns:
- A new or previously returned string builder.
-
isAutoCloseStreams
Auto-close streams.- Returns:
true ifInputStreams andReaders passed into parsers will be closed after parsing is complete.- See Also:
-
isStrict
Strict mode.- Returns:
true if strict mode for the parser is enabled.- See Also:
-
isTrimStrings
Trim parsed strings.- Returns:
true if string values will be trimmed of whitespace usingString.trim()before being added to the POJO.- See Also:
-
isUnbuffered
Unbuffered.- Returns:
true if parsers don't use internal buffering during parsing.- See Also:
-
mark
Marks the current position. -
onBeanSetterException
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 ifBeanContext.Builder.ignoreUnknownBeanProperties()setting on this parser isfalse
-
properties
Description copied from class:ContextSessionReturns the properties on this bean as a map for debugging.- Overrides:
propertiesin classBeanSession- Returns:
- The properties on this bean as a map for debugging.
-
returnStringBuilder
Returns aStringBuilderobject back into the internal reuse pool.- Parameters:
sb- The string builder to return to the pool. No-op ifnull .
-
setCurrentClass
Sets the current class being parsed for proper error messages.- Parameters:
currentClass- The current class being parsed.
-
setCurrentProperty
Sets the current bean property being parsed for proper error messages.- Parameters:
currentProperty- The current property being parsed.
-
setPipe
ThecreatePipe(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.
-
trim
- Type Parameters:
K- The object type.- Parameters:
o- The object to trim.- Returns:
- The trimmed string if it's a string.
-
trim
Trims the specified string ifisTrimStrings()returnstrue .- Parameters:
s- The input string to trim.- Returns:
- The trimmed string, or
null if the input wasnull .
-
unmark
Unmarks the current position. -
unswap
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.
-