Class ParserSession
- All Implemented Interfaces:
BeanSession,ConverterSession
- 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 ClassesModifier and TypeClassDescriptionstatic classParserSession.Builder<SELF extends ParserSession.Builder<SELF>>Builder class.static final classConcrete default builder leaf for the non-subclassedcreate()path (CRTP terminal). -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static final intDefault value forParserSession.Builder.maxParseDepth(int).Fields inherited from class org.apache.juneau.marshall.MarshallingSession
NAME_PROPERTY_NAME -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedParserSession(ParserSession.Builder<?> builder) Constructor. -
Method Summary
Modifier and TypeMethodDescriptionprotected final <T> TallocateLocal(String what, Supplier<T> alloc) Runs a local, parser-controlled allocation (e.g. pre-sizing an array/collection/buffer from a wire-declared count) and converts anOutOfMemoryErrorthrown specifically from it into a boundedParseException.protected final Objectcast(MarshalledMap m, BeanPropertyMeta pMeta, ClassMeta<?> eType) Converts the specifiedMarshalledMapinto a bean identified by the"_type" property in the map.protected final <T> BeanMap<T>checkRequired(BeanMap<T> m) ThrowsMissingRequiredPropertyExceptionif the bean map is missing@BeanProp(required=true)properties.protected final <T> TconvertAttrToType(Object outer, String s, ClassMeta<T> type) Converts the specified string to the specified type.static ParserSession.Builder<?>Creates 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> TdoRead(ParserPipe pipe, ClassMeta<T> type) Workhorse method.protected <E> Collection<E>doReadIntoCollection(ParserPipe pipe, Collection<E> c, Type elementType) Implementation method.protected <K,V> Map<K, V> doReadIntoMap(ParserPipe pipe, Map<K, V> m, Type keyType, Type valueType) Implementation method.protected <T> voiddoReadToBeanConsumer(ParserPipe pipe, BeanConsumer<T> consumer, Class<T> elementType) Format-specific implementation forreadToBeanConsumer(java.lang.Object, org.apache.juneau.commons.function.BeanConsumer<T>, java.lang.Class<T>).protected final voidEnters one level of recursive databind parsing, enforcing the sharedParserSession.Builder.maxParseDepth(int)budget (default 1000).protected final voidExits one level of recursive databind parsing previously entered viaenterParseDepth().protected final CalendarFormatCalendar parse hint format.protected final ClassMeta<?>getClassMeta(String typeName, BeanPropertyMeta pMeta, ClassMeta<?> eType) Give the specified dictionary name, resolve it to a class.protected final DateFormatDate parse hint format.protected final intDebug output lines.protected final DurationFormatDuration parse hint format.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 LocaleFormatLocale parse hint format.final NullsgetNulls()Returns the effectiveNullsdefault for this session — the per-session override (set viaParserSession.Builder.nulls(Nulls)) when present, otherwise the parser context'sParser.getNulls()value.protected final ObjectgetOuter()Returns the outer object used for instantiating top-level non-static member classes.protected final PeriodFormatPeriod parse hint format.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 TemporalFormatTemporal parse hint format.protected final TimeZoneFormatTime-zone parse hint format.protected final booleanAuto-close streams.booleanReturnstrue if this parser subclasses fromReaderParser.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.protected final ObjectReturns the nearest enclosing bean used as the parent for@ParentPropertyinjection.Returns the properties on this bean as a map for debugging.final <T> TSame asread(Object, Type, Type...)except optimized for a non-parameterized class.final <T> TParses input into the specified object type.final <T> TSame asread(Object, Type, Type...)except the type has already been converted into aClassMetaobject.final <T> TSame asread(Object, Class)but parses from a string and doesn't throw anIOException.final <T> TSame asread(Object,Type,Type...)but parses from a string and doesn't throw anIOException.final <T> TSame asread(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.protected final <T> TreadCalendar(String s, ClassMeta<T> cm) Parses an ISO 8601 wire value into aCalendarorXMLGregorianCalendartarget using this session's configured calendar format and time zone.protected final <T> TParses an ISO 8601 wire value into aDatetarget using this session's configured date format and time zone.protected final DurationParses an ISO 8601 / numeric wire value into aDurationusing this session's configured duration format as the disambiguation hint.final <E> Collection<E>readIntoCollection(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> readIntoMap(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.protected final PeriodreadPeriod(String s) Parses an ISO 8601 / numeric wire value into aPeriodusing this session's configured period format as the disambiguation hint.protected final <T> TreadTemporal(String s, ClassMeta<T> cm) Parses an ISO 8601 wire value into the specifiedTemporalsubtype using this session's configured temporal format and time zone.final <T> voidreadToBeanConsumer(Object input, BeanConsumer<T> consumer, Class<T> elementType) Parses the input and streams each parsed element into the givenBeanConsumer.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 ObjectswapParentBean(Object value) Sets the nearest-enclosing-bean tracker used for@ParentPropertyinjection.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.marshall.MarshallingSession
addWarning, convertToMemberType, convertToMemberType, convertToMemberType, convertToType, convertToType, convertToType, convertToType, create, get, getActiveView, getAnnotationProvider, getArgsClassMeta, getBeanClassVisibility, getBeanConstructorVisibility, getBeanDictionary, getBeanFieldVisibility, getBeanMeta, getBeanMethodVisibility, getBeanRegistry, getBeanTypePropertyName, getBeanTypePropertyName, getClassLoader, getClassMeta, getClassMeta, getClassMetaForObject, getClassMetaForObject, getLocale, getMarshallingContext, getMediaType, getNotBeanClasses, getNotBeanPackagesNames, getPropertyNamer, getSwaps, getTimeZone, getTimeZoneId, isBean, isBean, isBeanMapPutReturnsOldValue, isBeansRequireDefaultConstructor, isBeansRequireSerializable, isBeansRequireSettersForGetters, isBeansRequireSomeProperties, isFindFluentSetters, isIgnoreInvocationExceptionsOnGetters, isIgnoreInvocationExceptionsOnSetters, isIgnoreMissingSetters, isIgnoreUnknownBeanProperties, isIgnoreUnknownNullBeanProperties, isPropertyInActiveView, isRecordComponentOrder, isUnsortedProperties, isUseInterfaceProxies, isUseJavaBeanIntrospector, isValidateSchema, newBean, newBean, newBeanMap, newBeanMap, newGenericList, newGenericMap, newGenericMap, object, parseToList, parseToMap, string, toArray, toBeanMap, toBeanMap, toBeanMapMethods inherited from class org.apache.juneau.marshall.ContextSession
checkForWarnings, getContext, getSessionProperties, getWarnings, isDebug, toStringMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface org.apache.juneau.commons.conversion.ConverterSession
get
-
Field Details
-
DEFAULT_MAX_PARSE_DEPTH
Default value forParserSession.Builder.maxParseDepth(int).- See Also:
-
-
Constructor Details
-
ParserSession
Constructor.- Parameters:
builder- The builder for this object.
Cannot benull .
-
-
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.
Can benull (no-op).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.
Can benull (no-op).o- The object.parent- The parent to set.- Throws:
ExecutableException- Exception occurred on invoked constructor/method/field.
-
parentBean
Returns the nearest enclosing bean used as the parent for@ParentPropertyinjection.Unlike
getOuter()(which also serves as the instantiation context for non-static member/inner classes), this value tracks only the nearest enclosing bean as the object graph is parsed, deliberately skipping any intermediate collections/maps/arrays. It isnullat the document root (no enclosing bean), which means a bean parsed at the root or directly inside a top-level collection has no parent injected.- Returns:
- The nearest enclosing bean, or
nullif there is none.
-
swapParentBean
Sets the nearest-enclosing-bean tracker used for@ParentPropertyinjection.Callers should invoke this when they begin populating a bean's properties (passing that bean), then pass the returned previous value back to this method once done, restoring the tracker stack-style.
- Parameters:
value- The new nearest enclosing bean (typically the bean currently being populated).- Returns:
- The previous value, to be passed back to this method to restore the tracker.
-
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.
-
read
Same asread(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 .read(json , String.class );// Parse into a bean. MyBeanbean =parser .read(json , MyBean.class );// Parse into a bean array. MyBean[]beanArray =parser .read(json , MyBean[].class );// Parse into a linked-list of objects. Listlist =parser .read(json , LinkedList.class );// Parse into a map of object keys/values. Mapmap =parser .read(json , TreeMap.class );- Type Parameters:
T- The class type of the object being created.- Parameters:
input- The input. Seeread(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.
-
read
Same asread(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. Seeread(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.
-
read
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 .read(json , LinkedList.class , String.class );// Parse into a linked-list of beans. Listlist2 =parser .read(json , LinkedList.class , MyBean.class );// Parse into a linked-list of linked-lists of strings. Listlist3 =parser .read(json , LinkedList.class , LinkedList.class , String.class );// Parse into a map of string keys/values. Mapmap1 =parser .read(json , TreeMap.class , String.class , String.class );// Parse into a map containing string keys and values of lists containing beans. Mapmap2 =parser .read(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
read(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).
Stream-based parsers can handle the following input class types:null InputStreambyte []
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
-
read
Same asread(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 .read(json , String.class );// Parse into a bean. MyBeanbean =parser .read(json , MyBean.class );// Parse into a bean array. MyBean[]beanArray =parser .read(json , MyBean[].class );// Parse into a linked-list of objects. Listlist =parser .read(json , LinkedList.class );// Parse into a map of object keys/values. Mapmap =parser .read(json , TreeMap.class );- Type Parameters:
T- The class type of the object being created.- Parameters:
input- The input. Seeread(Object, Type, Type...)for details.type- The object type to create.- Returns:
- The parsed object.
- Throws:
ParseException- Malformed input encountered.
-
read
Same asread(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. Seeread(Object, Type, Type...)for details.type- The object type to create.- Returns:
- The parsed object.
- Throws:
ParseException- Malformed input encountered.
-
read
Same asread(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).
Stream-based parsers can handle the following input class types:null InputStreambyte []
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:
-
readArgs
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
-
readIntoCollection
public final <E> Collection<E> readIntoCollection(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. Seeread(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
-
readIntoMap
public final <K,V> Map<K,V> readIntoMap(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. Seeread(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
-
readToBeanConsumer
public final <T> void readToBeanConsumer(Object input, BeanConsumer<T> consumer, Class<T> elementType) throws ParseException, IOException Parses the input and streams each parsed element into the givenBeanConsumer.This is the primary API for large-dataset parsing where parsed beans should be consumed lazily (e.g. inserted directly into a database) rather than collected into an in-memory collection.
The parser drives the full consumer lifecycle:
- Calls
BeanConsumer.begin()before parsing starts - Calls
ThrowingConsumer.acceptThrows(Object)for each parsed element - If
ThrowingConsumer.acceptThrows(Object)throws, callsBeanConsumer.onError(Exception); ifonError()absorbs the exception, parsing continues to the next element - Always calls
BeanConsumer.complete()at the end (likefinally)
The default implementation parses the input into a
Listfirst and then feeds each element to the consumer. Format-specific subclasses may overridedoReadToBeanConsumer(org.apache.juneau.marshall.parser.ParserPipe, org.apache.juneau.commons.function.BeanConsumer<T>, java.lang.Class<T>)for true streaming behavior without loading all elements into memory.- Type Parameters:
T- The element type.- Parameters:
input- The input to parse.consumer- The consumer to receive parsed elements.elementType- The type of each element.- Throws:
ParseException- If a parse error occurs that causesonError()to rethrow.IOException- If an I/O error occurs reading the input.
- Calls
-
doReadToBeanConsumer
protected <T> void doReadToBeanConsumer(ParserPipe pipe, BeanConsumer<T> consumer, Class<T> elementType) throws ParseException, IOException Format-specific implementation forreadToBeanConsumer(java.lang.Object, org.apache.juneau.commons.function.BeanConsumer<T>, java.lang.Class<T>).The default implementation parses the input as a
Listand feeds each element to the consumer. Override this method in format-specific parsers to support true streaming without collecting all elements into memory.- Type Parameters:
T- The element type.- Parameters:
pipe- The parser input pipe.consumer- The consumer to receive parsed elements.elementType- The type of each element.- Throws:
ParseException- If a parse error occurs.IOException- If an I/O error occurs.
-
checkRequired
ThrowsMissingRequiredPropertyExceptionif the bean map is missing@BeanProp(required=true)properties.Call once per bean, after all input properties have been put into the map and before
BeanMap.getBean()constructs it. Do not call it for intermediate bean maps that are filled in later.- Type Parameters:
T- The bean type.- Parameters:
m- The bean map. Can benull .- Returns:
- The same bean map.
-
cast
Converts the specifiedMarshalledMapinto a bean identified by the"_type" property in the map.- Parameters:
m- The map to convert to a bean.
Must not benull .pMeta- The current bean property being parsed.
Can benull (the@MarshalledProp(dictionary={}) registry lookup is skipped).eType- The current expected type being parsed.
Can benull (the@Marshalled(dictionary={}) registry lookup on the expected type is skipped).- 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.
Can benull if the target is not a non-static inner class requiring an enclosing instance.s- The string to convert.
Can benull (returnsnull ).type- The class type to convert the string to.
Can benull (defaults toObject ).- Returns:
- The string converted as an object of the specified type, or
null if the input string wasnull . - 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)).
For byte-based parsers, this can be any of the following types:null InputStreambyte []CharSequencecontaining encoded bytes according to theMarshallingContextable.Builder.binaryFormat(BinaryFormat)setting.
- Returns:
- A new
ParserPipewrapper around the specified input object.
-
doRead
protected <T> T doRead(ParserPipe pipe, ClassMeta<T> type) throws IOException, ParseException, ExecutableException Workhorse method.Subclasses are expected to implement this method or
Parser.doRead(ParserSession,ParserPipe,ClassMeta).The default implementation of this method simply calls
Parser.doRead(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.
-
doReadIntoCollection
protected <E> Collection<E> doReadIntoCollection(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.
-
doReadIntoMap
protected <K,V> Map<K,V> doReadIntoMap(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.
Can benull (the@MarshalledProp(dictionary={}) registry lookup is skipped).eType- The expected type we're currently parsing.
Can benull (the@Marshalled(dictionary={}) registry lookup on the expected type is skipped).- 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, or
null if not set.
-
getListenerClass
Parser listener.- Returns:
- Class used to listen for errors and warnings that occur during parsing, or
null if none was configured. - 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, or
null if none was specified.
-
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:
-
isTrimStrings
Trim parsed strings.- Returns:
true if string values will be trimmed of whitespace usingString.trim()before being added to the POJO.- See Also:
-
getNulls
Returns the effectiveNullsdefault for this session — the per-session override (set viaParserSession.Builder.nulls(Nulls)) when present, otherwise the parser context'sParser.getNulls()value.- Returns:
- The current session-level value (never
null ;Nulls.NOT_SETwhen unconfigured). - Since:
- 10.0.0
-
isUnbuffered
Unbuffered.- Returns:
true if parsers don't use internal buffering during parsing.- See Also:
-
getDurationFormat
Duration parse hint format.- Returns:
- The configured duration parse hint format.
-
getPeriodFormat
Period parse hint format.- Returns:
- The configured period parse hint format.
-
getCalendarFormat
Calendar parse hint format.- Returns:
- The configured calendar parse hint format.
-
getDateFormat
Date parse hint format.- Returns:
- The configured date parse hint format.
-
getTemporalFormat
Temporal parse hint format.- Returns:
- The configured temporal parse hint format.
-
getTimeZoneFormat
Time-zone parse hint format.- Returns:
- The configured time-zone parse hint format.
-
getLocaleFormat
Locale parse hint format.- Returns:
- The configured locale parse hint format.
-
readDuration
Parses an ISO 8601 / numeric wire value into aDurationusing this session's configured duration format as the disambiguation hint.- Parameters:
s- The wire value to parse.null or empty returnsnull .- Returns:
- The parsed
Duration, ornull ifsisnull or empty.
-
readPeriod
Parses an ISO 8601 / numeric wire value into aPeriodusing this session's configured period format as the disambiguation hint.- Parameters:
s- The wire value to parse.null or empty returnsnull .- Returns:
- The parsed
Period, ornull ifsisnull or empty.
-
readDate
Parses an ISO 8601 wire value into aDatetarget using this session's configured date format and time zone.- Type Parameters:
T- The target type (unbounded to matchIso8601Utils.parseDate(java.lang.String, org.apache.juneau.marshall.ClassMeta<T>, org.apache.juneau.marshall.DateFormat, java.util.TimeZone)).- Parameters:
s- The wire value to parse.null returnsnull .cm- The target class metadata.- Returns:
- The parsed value, or
null ifsisnull or the target is not a recognizedDatetype.
-
readCalendar
Parses an ISO 8601 wire value into aCalendarorXMLGregorianCalendartarget using this session's configured calendar format and time zone.- Type Parameters:
T- The target type (unbounded becauseXMLGregorianCalendaris not aCalendarsubclass).- Parameters:
s- The wire value to parse.null returnsnull .cm- The target class metadata.- Returns:
- The parsed value, or
null ifsisnull or the target is not a recognized calendar type.
-
readTemporal
Parses an ISO 8601 wire value into the specifiedTemporalsubtype using this session's configured temporal format and time zone.- Type Parameters:
T- The target type (unbounded to matchIso8601Utils.parseTemporal(java.lang.String, org.apache.juneau.marshall.ClassMeta<T>, org.apache.juneau.marshall.TemporalFormat, java.util.TimeZone)).- Parameters:
s- The wire value to parse.null returnsnull .cm- The target class metadata.- Returns:
- The parsed value, or
null ifsisnull or the target is not aTemporalsubtype.
-
enterParseDepth
Enters one level of recursive databind parsing, enforcing the sharedParserSession.Builder.maxParseDepth(int)budget (default 1000).Binary codec sessions (CBOR, Protobuf, MsgPack) call this at their recursive databind entry point before descending into a nested array/map/message element, and must call
exitParseDepth()in a matchingfinally block regardless of outcome. Exceeding the budget throws aParseExceptionso an adversarial deeply-nested document fails cleanly instead of exhausting the call stack with aStackOverflowError.Intentionally not applied to the JSON/XML/text parsers, whose recursive-descent parsers already rely on
StackOverflowErrorconversion at the outer parse boundary.- Throws:
ParseException- If the configured maximum parse depth was exceeded.
-
exitParseDepth
Exits one level of recursive databind parsing previously entered viaenterParseDepth().Must be called exactly once per successful
enterParseDepth()call, in a matchingfinally block so the depth counter is restored even when the nested parse throws. -
allocateLocal
Runs a local, parser-controlled allocation (e.g. pre-sizing an array/collection/buffer from a wire-declared count) and converts anOutOfMemoryErrorthrown specifically from it into a boundedParseException.Only an
OutOfMemoryErrorthrown fromalloc's own execution is converted here. Any otherOutOfMemoryError— one raised elsewhere in the call stack, signaling a JVM that is genuinely running out of heap — is not this method's concern and is never observed by it; a dying JVM is not a client input-validation failure and must not be reported as one. Format-specific parser sessions should route untrusted-length-driven local allocations through this helper instead of relying on a blanket catch at an outer parse boundary.- Type Parameters:
T- The allocated object's type.- Parameters:
what- A short human-readable description of what's being allocated, used in the exception message if the allocation fails.
Must not benull .alloc- The allocation to attempt.
Must not benull .- Returns:
- The allocated object.
- Throws:
ParseException- Ifallocitself threw anOutOfMemoryError.
-
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.
Must not benull .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.
Must not benull .beanMap- The bean that doesn't have the expected property.
Must not benull .value- The parsed value.
Can benull , in which case whether the property is ignored is governed byMarshallingContext.Builder.disableIgnoreUnknownNullBeanProperties()rather thanMarshallingContext.Builder.ignoreUnknownBeanProperties().- Throws:
ParseException- Automatically thrown ifMarshallingContext.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 classMarshallingSession- 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.
Must not benull .o- The input object.eType- The expected type.- Returns:
- The swapped object.
- Throws:
ParseException- If swap method threw an exception.
-