001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.marshall.parser; 018 019import static org.apache.juneau.commons.utils.CollectionUtils.*; 020import static org.apache.juneau.commons.utils.Shorts.*; 021import static org.apache.juneau.commons.utils.StringUtils.*; 022import static org.apache.juneau.commons.utils.SystemUtils.*; 023 024import java.io.*; 025import java.lang.reflect.*; 026import java.nio.charset.*; 027import java.util.*; 028 029import org.apache.juneau.commons.collections.*; 030import org.apache.juneau.commons.http.*; 031import org.apache.juneau.commons.reflect.*; 032import org.apache.juneau.marshall.*; 033import org.apache.juneau.marshall.collections.*; 034import org.apache.juneau.marshall.html.*; 035import org.apache.juneau.marshall.json.*; 036import org.apache.juneau.marshall.msgpack.*; 037import org.apache.juneau.marshall.objecttools.*; 038import org.apache.juneau.marshall.stream.*; 039import org.apache.juneau.marshall.swap.spi.*; 040import org.apache.juneau.marshall.uon.*; 041import org.apache.juneau.marshall.xml.*; 042 043/** 044 * Parent class for all Juneau parsers. 045 * 046 * <h2 class='topic'>Valid data conversions</h2> 047 * <p> 048 * Parsers can parse any parsable POJO types, as specified in the <a class="doclink" href="https://juneau.apache.org/docs/topics/PojoCategories">POJO Categories</a>. 049 * 050 * <p> 051 * Some examples of conversions are shown below... 052 * </p> 053 * <table class='styled'> 054 * <caption>Supported input data types</caption> 055 * <tr> 056 * <th>Data type</th> 057 * <th>Class type</th> 058 * <th>JSON example</th> 059 * <th>XML example</th> 060 * <th>Class examples</th> 061 * </tr> 062 * <tr> 063 * <td>object</td> 064 * <td>Maps, Java beans</td> 065 * <td class='code'>{name:<js>'John Smith'</js>,age:21}</td> 066 * <td class='code'><xt><object> 067 * <name</xt> <xa>type</xa>=<xs>'string'</xs><xt>></xt>John Smith<xt></name> 068 * <age</xt> <xa>type</xa>=<xs>'number'</xs><xt>></xt>21<xt></age> 069 * </object></xt></td> 070 * <td class='code'>HashMap, TreeMap<String,Integer></td> 071 * </tr> 072 * <tr> 073 * <td>array</td> 074 * <td>Collections, Java arrays</td> 075 * <td class='code'>[1,2,3]</td> 076 * <td class='code'><xt><array> 077 * <number></xt>1<xt></number> 078 * <number></xt>2<xt></number> 079 * <number></xt>3<xt></number> 080 * </array></xt></td> 081 * <td class='code'>List<Integer>, <jk>int</jk>[], Float[], Set<Person></td> 082 * </tr> 083 * <tr> 084 * <td>number</td> 085 * <td>Numbers</td> 086 * <td class='code'>123</td> 087 * <td class='code'><xt><number></xt>123<xt></number></xt></td> 088 * <td class='code'>Integer, Long, Float, <jk>int</jk></td> 089 * </tr> 090 * <tr> 091 * <td>boolean</td> 092 * <td>Booleans</td> 093 * <td class='code'><jk>true</jk></td> 094 * <td class='code'><xt><boolean></xt>true<xt></boolean></xt></td> 095 * <td class='code'>Boolean</td> 096 * </tr> 097 * <tr> 098 * <td>string</td> 099 * <td>CharSequences</td> 100 * <td class='code'><js>'foobar'</js></td> 101 * <td class='code'><xt><string></xt>foobar<xt></string></xt></td> 102 * <td class='code'>String, StringBuilder</td> 103 * </tr> 104 * </table> 105 * 106 * <p> 107 * In addition, any class types with {@link ObjectSwap ObjectSwaps} associated with them on the registered 108 * bean context can also be passed in. 109 * 110 * <p> 111 * For example, if a {@link CalendarFormat}-driven swap is used to generalize {@code Calendar} objects to {@code String} 112 * objects. 113 * When registered with this parser, you can construct {@code Calendar} objects from {@code Strings} using the 114 * following syntax... 115 * <p class='bjava'> 116 * Calendar <jv>calendar</jv> = <jv>parser</jv>.read(<js>"'Sun Mar 03 04:05:06 EST 2001'"</js>, GregorianCalendar.<jk>class</jk>); 117 * </p> 118 * 119 * <p> 120 * If <code>Object.<jk>class</jk></code> is specified as the target type, then the parser automatically determines the 121 * data types and generates the following object types... 122 * <table class='styled'> 123 * <caption>JSON types and the object types they produce</caption> 124 * <tr><th>JSON type</th><th>Class type</th></tr> 125 * <tr><td>object</td><td>{@link JsonMap}</td></tr> 126 * <tr><td>array</td><td>{@link JsonList}</td></tr> 127 * <tr><td>number</td><td>{@link Number}<br>(depending on length and format, could be {@link Integer}, 128 * {@link Double}, {@link Float}, etc...)</td></tr> 129 * <tr><td>boolean</td><td>{@link Boolean}</td></tr> 130 * <tr><td>string</td><td>{@link String}</td></tr> 131 * </table> 132 * 133 * <h2 class='section'>Notes:</h2><ul> 134 * <li class='note'>This class is thread safe and reusable. 135 * </ul> 136 * 137 * <h2 class='section'>See Also:</h2><ul> 138 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/SerializersAndParsers">Serializers and Parsers</a> 139 140 * </ul> 141 */ 142@SuppressWarnings({ 143 "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants 144 "rawtypes" // createParserBuilder() returns the raw Builder because the builder subtype is only known reflectively. 145}) 146public class Parser extends MarshallingContextable { 147 148 /** 149 * Builder class. 150 */ 151 @SuppressWarnings({ 152 "java:S119" // 'SELF' (CRTP self-type) is intentional and clearer than a single-letter name. 153 }) 154 public abstract static class Builder<SELF extends Builder<SELF>> extends MarshallingContextable.Builder<SELF> { 155 156 private boolean autoCloseStreams; 157 private boolean trimStrings; 158 private boolean includeInputInErrors; 159 private boolean unbuffered; 160 private Class<? extends ParserListener> listener; 161 private int debugOutputLines; 162 private String consumes; 163 private Nulls nulls; 164 165 /** 166 * Constructor, default settings. 167 */ 168 protected Builder() { 169 autoCloseStreams = env("Parser.autoCloseStreams", false); 170 trimStrings = env("Parser.trimStrings", false); 171 includeInputInErrors = env("Parser.includeInputInErrors", false); 172 unbuffered = env("Parser.unbuffered", false); 173 debugOutputLines = env("Parser.debugOutputLines", 5); 174 listener = null; 175 consumes = null; 176 nulls = Nulls.NOT_SET; 177 } 178 179 /** 180 * Copy constructor. 181 * 182 * @param copyFrom The builder to copy from. 183 * <br>Cannot be <jk>null</jk>. 184 */ 185 protected Builder(Builder<?> copyFrom) { 186 super(copyFrom); 187 autoCloseStreams = copyFrom.autoCloseStreams; 188 trimStrings = copyFrom.trimStrings; 189 includeInputInErrors = copyFrom.includeInputInErrors; 190 unbuffered = copyFrom.unbuffered; 191 debugOutputLines = copyFrom.debugOutputLines; 192 listener = copyFrom.listener; 193 consumes = copyFrom.consumes; 194 nulls = copyFrom.nulls; 195 } 196 197 /** 198 * Copy constructor. 199 * 200 * @param copyFrom The bean to copy from. 201 * <br>Cannot be <jk>null</jk>. 202 */ 203 protected Builder(Parser copyFrom) { 204 super(copyFrom); 205 autoCloseStreams = copyFrom.autoCloseStreams; 206 trimStrings = copyFrom.trimStrings; 207 includeInputInErrors = copyFrom.includeInputInErrors; 208 unbuffered = copyFrom.unbuffered; 209 debugOutputLines = copyFrom.debugOutputLines; 210 listener = copyFrom.listener; 211 consumes = copyFrom.consumes; 212 nulls = copyFrom.nulls; 213 } 214 215 /** 216 * Auto-close streams. 217 * 218 * <p> 219 * When enabled, <l>InputStreams</l> and <l>Readers</l> passed into parsers will be closed 220 * after parsing is complete. 221 * 222 * <h4 class='section'>Example:</h4> 223 * <p class='bjava'> 224 * <jc>// Create a parser using strict mode.</jc> 225 * ReaderParser <jv>parser</jv> = JsonParser 226 * .<jsm>create</jsm>() 227 * .autoCloseStreams() 228 * .build(); 229 * 230 * Reader <jv>myReader</jv> = <jk>new</jk> FileReader(<js>"/tmp/myfile.json"</js>); 231 * MyBean <jv>myBean</jv> = <jv>parser</jv>.read(<jv>myReader</jv>, MyBean.<jk>class</jk>); 232 * 233 * <jsm>assertTrue</jsm>(<jv>myReader</jv>.isClosed()); 234 * </p> 235 * 236 * @return This object. 237 */ 238 public SELF autoCloseStreams() { 239 return autoCloseStreams(true); 240 } 241 242 /** 243 * Same as {@link #autoCloseStreams()} but allows you to explicitly specify the value. 244 * 245 * @param value The value for this setting. 246 * @return This object. 247 */ 248 public SELF autoCloseStreams(boolean value) { 249 autoCloseStreams = value; 250 return self(); 251 } 252 253 @Override /* Overridden from Context.Builder<?> */ 254 public Parser build() { 255 return build(Parser.class); 256 } 257 258 /** 259 * Specifies the media type that this parser consumes. 260 * 261 * <p> 262 * <b>Token streams:</b> this setting is not honored by {@link TokenReadable#readTokens(Object) readTokens} 263 * — media-type metadata is informational, not behavioral. 264 * 265 * @param value The value for this setting. 266 * <br>Can be <jk>null</jk> (treated as empty string, no media types will be specified). 267 * @return This object. 268 */ 269 public SELF consumes(String value) { 270 consumes = value; 271 return self(); 272 } 273 274 @Override /* Overridden from Context.Builder<?> */ 275 public abstract SELF copy(); 276 277 /** 278 * Debug output lines. 279 * 280 * <p> 281 * When parse errors occur, this specifies the number of lines of input before and after the 282 * error location to be printed as part of the exception message. 283 * 284 * <h4 class='section'>Example:</h4> 285 * <p class='bjava'> 286 * <jc>// Create a parser whose exceptions print out 100 lines before and after the parse error location.</jc> 287 * ReaderParser <jv>parser</jv> = JsonParser 288 * .<jsm>create</jsm>() 289 * .debug() <jc>// Enable debug mode to capture Reader contents as strings.</jc> 290 * .includeInputInErrors() <jc>// Include the input lines around the error in exception messages.</jc> 291 * .debugOutputLines(100) 292 * .build(); 293 * 294 * Reader <jv>myReader</jv> = <jk>new</jk> FileReader(<js>"/tmp/mybadfile.json"</js>); 295 * <jk>try</jk> { 296 * <jv>parser</jv>.read(<jv>myReader</jv>, Object.<jk>class</jk>); 297 * } <jk>catch</jk> (ParseException <jv>e</jv>) { 298 * System.<jsf>err</jsf>.println(<jv>e</jv>.getMessage()); <jc>// Will display 200 lines of the output.</jc> 299 * } 300 * </p> 301 * 302 * <p> 303 * <b>Token streams:</b> this setting is not honored by {@link TokenReadable#readTokens(Object) readTokens} 304 * — it controls error-message formatting on the POJO databind path; the cursor uses its own 305 * exception text. 306 * 307 * @param value 308 * The new value for this property. 309 * <br>The default value is <c>5</c>. 310 * @return This object. 311 */ 312 public SELF debugOutputLines(int value) { 313 debugOutputLines = value; 314 return self(); 315 } 316 317 /** 318 * Returns the current value for the 'consumes' property. 319 * 320 * @return The current value for the 'consumes' property, or <jk>null</jk> if not specified. 321 */ 322 public String getConsumes() { return consumes; } 323 324 @Override /* Overridden from Context.Builder<?> */ 325 public HashKey hashKey() { 326 // @formatter:off 327 return HashKey.of( 328 super.hashKey(), 329 autoCloseStreams, 330 trimStrings, 331 includeInputInErrors, 332 unbuffered, 333 debugOutputLines, 334 listener, 335 consumes, 336 nulls 337 ); 338 // @formatter:on 339 } 340 341 /** 342 * Parser listener. 343 * 344 * <p> 345 * Class used to listen for errors and warnings that occur during parsing. 346 * 347 * <h4 class='section'>Example:</h4> 348 * <p class='bjava'> 349 * <jc>// Define our parser listener.</jc> 350 * <jc>// Simply captures all unknown bean property events.</jc> 351 * <jk>public class</jk> MyParserListener <jk>extends</jk> ParserListener { 352 * 353 * <jc>// A simple property to store our events.</jc> 354 * <jk>public</jk> List<String> <jf>events</jf> = <jk>new</jk> LinkedList<>(); 355 * 356 * <ja>@Override</ja> 357 * <jk>public</jk> <T> <jk>void</jk> onUnknownBeanProperty(ParserSession <jv>session</jv>, String <jv>propertyName</jv>, Class<T> <jv>beanClass</jv>, T <jv>bean</jv>) { 358 * Position <jv>position</jv> = <jv>parser</jv>.getPosition(); 359 * <jf>events</jf>.add(<jv>propertyName</jv> + <js>","</js> + <jv>position</jv>.getLine() + <js>","</js> + <jv>position</jv>.getColumn()); 360 * } 361 * } 362 * 363 * <jc>// Create a parser using our listener.</jc> 364 * ReaderParser <jv>parser</jv> = JsonParser 365 * .<jsm>create</jsm>() 366 * .listener(MyParserListener.<jk>class</jk>) 367 * .build(); 368 * 369 * <jc>// Create a session object.</jc> 370 * <jc>// Needed because listeners are created per-session.</jc> 371 * <jk>try</jk> (ReaderParserSession <jv>session</jv> = <jv>parser</jv>.createSession()) { 372 * 373 * <jc>// Parse some JSON object.</jc> 374 * MyBean <jv>myBean</jv> = <jv>session</jv>.read(<js>"{...}"</js>, MyBean.<jk>class</jk>); 375 * 376 * <jc>// Get the listener.</jc> 377 * MyParserListener <jv>listener</jv> = <jv>session</jv>.getListener(MyParserListener.<jk>class</jk>); 378 * 379 * <jc>// Dump the results to the console.</jc> 380 * Json5.<jsf>DEFAULT</jsf>.println(<jv>listener</jv>.<jf>events</jf>); 381 * } 382 * </p> 383 * 384 * <p> 385 * <b>Token streams:</b> this setting is not honored by {@link TokenReadable#readTokens(Object) readTokens} 386 * — listeners are POJO-level observers with no token-layer analog. 387 * 388 * @param value The new value for this property. 389 * <br>Can be <jk>null</jk> (no listener will be used, listener methods will not be called). 390 * @return This object. 391 */ 392 public SELF listener(Class<? extends ParserListener> value) { 393 listener = value; 394 return self(); 395 } 396 397 /** 398 * Sets the default per-property null-coercion policy applied during parsing. 399 * 400 * <p> 401 * Juneau's analog of Jackson's 402 * <c>ObjectMapper.setDefaultSetterInfo(JsonSetter.Value.forValueNulls(...))</c>. 403 * Applied as the fallback when no per-property 404 * {@link MarshalledProp#nulls() @MarshalledProp(nulls=…)} is configured. 405 * 406 * <h4 class='section'>Example:</h4> 407 * <p class='bjava'> 408 * <jc>// Substitute the empty value for any property whose wire value is null.</jc> 409 * ReaderParser <jv>parser</jv> = JsonParser 410 * .<jsm>create</jsm>() 411 * .nulls(Nulls.<jsf>EMPTY</jsf>) 412 * .build(); 413 * </p> 414 * 415 * @param value The new value for this property. 416 * <br>{@code null} or {@link Nulls#NOT_SET} disables the default (each property falls back to 417 * {@link Nulls#LEAVE}). 418 * @return This object. 419 * @since 10.0.0 420 */ 421 public SELF nulls(Nulls value) { 422 nulls = value == null ? Nulls.NOT_SET : value; 423 return self(); 424 } 425 426 /** 427 * Returns the current context-level {@link Nulls} default configured on this builder. 428 * 429 * @return The current value (never <jk>null</jk>; {@link Nulls#NOT_SET} when unconfigured). 430 * @since 10.0.0 431 */ 432 public Nulls getNulls() { return nulls == null ? Nulls.NOT_SET : nulls; } 433 434 /** 435 * Trim parsed strings. 436 * 437 * <p> 438 * When enabled, string values will be trimmed of whitespace using {@link String#trim()} before being added to 439 * the POJO. 440 * 441 * <h4 class='section'>Example:</h4> 442 * <p class='bjava'> 443 * <jc>// Create a parser with trim-strings enabled.</jc> 444 * ReaderParser <jv>parser</jv> = JsonParser 445 * .<jsm>create</jsm>() 446 * .trimStrings() 447 * .build(); 448 * 449 * <jc>// Use it.</jc> 450 * String <jv>json</jv> = <js>"{' foo ':' bar '}"</js>; 451 * Map<String,String> <jv>myMap</jv> = <jv>parser</jv>.read(<jv>json</jv>, HashMap.<jk>class</jk>, String.<jk>class</jk>, String.<jk>class</jk>); 452 * 453 * <jc>// Make sure strings are parsed.</jc> 454 * <jsm>assertEquals</jsm>(<js>"bar"</js>, <jv>myMap</jv>.get(<js>"foo"</js>)); 455 * </p> 456 * 457 * @return This object. 458 */ 459 public SELF trimStrings() { 460 return trimStrings(true); 461 } 462 463 /** 464 * Include input snippet in parse errors. 465 * 466 * <p> 467 * When enabled, {@link ParseException} messages include the lines of input around the error location 468 * (see {@link #debugOutputLines(int)}). 469 * <br>The input is only available for <c>String</c>/<c>Reader</c>-style input, or when 470 * {@link org.apache.juneau.marshall.Context.Builder#debug() debug} mode is enabled to capture it. 471 * 472 * <p> 473 * Off by default because the input may contain sensitive data. Debug mode alone does not enable it. 474 * 475 * @return This object. 476 */ 477 public SELF includeInputInErrors() { 478 return includeInputInErrors(true); 479 } 480 481 /** 482 * Same as {@link #includeInputInErrors()} but allows you to explicitly specify the value. 483 * 484 * @param value The value for this setting. 485 * @return This object. 486 */ 487 public SELF includeInputInErrors(boolean value) { 488 includeInputInErrors = value; 489 return self(); 490 } 491 492 /** 493 * Same as {@link #trimStrings()} but allows you to explicitly specify the value. 494 * 495 * @param value The value for this setting. 496 * @return This object. 497 */ 498 public SELF trimStrings(boolean value) { 499 trimStrings = value; 500 return self(); 501 } 502 503 /** 504 * Unbuffered. 505 * 506 * <p> 507 * When enabled, don't use internal buffering during parsing. 508 * 509 * <p> 510 * This is useful in cases when you want to parse the same input stream or reader multiple times 511 * because it may contain multiple independent POJOs to parse. 512 * <br>Buffering would cause the parser to read past the current POJO in the stream. 513 * 514 * <h4 class='section'>Example:</h4> 515 * <p class='bjava'> 516 * <jc>// Create a parser using strict mode.</jc> 517 * ReaderParser <jv>parser</jv> = JsonParser. 518 * .<jsm>create</jsm>() 519 * .unbuffered(<jk>true</jk>) 520 * .build(); 521 * 522 * <jc>// If you're calling parse on the same input multiple times, use a session instead of the parser directly.</jc> 523 * <jc>// It's more efficient because we don't need to recalc the session settings again. </jc> 524 * ReaderParserSession <jv>session</jv> = <jv>parser</jv>.createSession(); 525 * 526 * <jc>// Read input with multiple POJOs</jc> 527 * Reader <jv>json</jv> = <jk>new</jk> StringReader(<js>"{foo:'bar'}{foo:'baz'}"</js>); 528 * MyBean <jv>myBean1</jv> = <jv>session</jv>.read(<jv>json</jv>, MyBean.<jk>class</jk>); 529 * MyBean <jv>myBean2</jv> = <jv>session</jv>.read(<jv>json</jv>, MyBean.<jk>class</jk>); 530 * </p> 531 * 532 * <h4 class='section'>Notes:</h4><ul> 533 * <li class='note'> 534 * This only allows for multi-input streams for the following parsers: 535 * <ul> 536 * <li class='jc'>{@link JsonParser} 537 * <li class='jc'>{@link UonParser} 538 * </ul> 539 * It has no effect on the following parsers: 540 * <ul> 541 * <li class='jc'>{@link MsgPackParser} - It already doesn't use buffering. 542 * <li class='jc'>{@link XmlParser}, {@link HtmlParser} - These use StAX which doesn't allow for more than one root element anyway. 543 * <li>RDF parsers - These read everything into an internal model before any parsing begins. 544 * </ul> 545 * </ul> 546 * 547 * @return This object. 548 */ 549 public SELF unbuffered() { 550 return unbuffered(true); 551 } 552 553 /** 554 * Same as {@link #unbuffered()} but allows you to explicitly specify the value. 555 * 556 * @param value The value for this setting. 557 * @return This object. 558 */ 559 public SELF unbuffered(boolean value) { 560 unbuffered = value; 561 return self(); 562 } 563 564 565 } 566 567 /** 568 * Concrete default builder leaf for the non-subclassed {@link Parser#create()} / {@link Parser#copy()} path. 569 */ 570 public static final class DefaultBuilder extends Builder<DefaultBuilder> { 571 572 DefaultBuilder() {} 573 574 DefaultBuilder(Parser copyFrom) { 575 super(copyFrom); 576 } 577 578 DefaultBuilder(Builder<?> copyFrom) { 579 super(copyFrom); 580 } 581 582 @Override /* Overridden from Context.Builder<?> */ 583 public DefaultBuilder copy() { 584 return new DefaultBuilder(this); 585 } 586 } 587 588 /** 589 * Represents no Parser. 590 */ 591 public abstract static class Null extends Parser { 592 @SuppressWarnings({ 593 "java:S1186" // Constructor required by Parser parent class, even though Null is abstract and never instantiated directly 594 }) 595 private Null(Builder<?> builder) { 596 super(builder); 597 } 598 } 599 600 /** 601 * Creates a new builder for this object. 602 * 603 * @return A new builder. 604 */ 605 @SuppressWarnings({ 606 "java:S1452" // Self-typed builder: Builder<?> is the only non-raw, leaf-free return; chaining + build() unaffected. 607 }) 608 public static Builder<?> create() { 609 return new DefaultBuilder(); 610 } 611 612 /** 613 * Instantiates a builder of the specified parser class. 614 * 615 * <p> 616 * Looks for a public static method called <c>create</c> that returns an object that can be passed into a public 617 * or protected constructor of the class. 618 * 619 * @param c The builder to create. 620 * <br>Must not be <jk>null</jk>. 621 * @return A new builder. 622 */ 623 public static Builder createParserBuilder(Class<? extends Parser> c) { 624 return (Builder)Context.createBuilder(c); 625 } 626 627 protected final boolean autoCloseStreams; 628 protected final boolean trimStrings; 629 protected final boolean includeInputInErrors; 630 protected final boolean unbuffered; 631 protected final int debugOutputLines; 632 protected final Class<? extends ParserListener> listener; 633 protected final String consumes; 634 protected final Nulls nulls; 635 private final List<MediaType> consumesArray; 636 637 /** 638 * Constructor. 639 * 640 * @param builder The builder for this object. 641 * <br>Cannot be <jk>null</jk>. 642 */ 643 protected Parser(Builder<?> builder) { 644 super(builder); 645 646 autoCloseStreams = builder.autoCloseStreams; 647 consumes = builder.consumes; 648 debugOutputLines = builder.debugOutputLines; 649 listener = builder.listener; 650 trimStrings = builder.trimStrings; 651 includeInputInErrors = builder.includeInputInErrors; 652 unbuffered = builder.unbuffered; 653 nulls = builder.nulls == null ? Nulls.NOT_SET : builder.nulls; 654 655 String[] consumesParts = splita(nn(consumes) ? consumes : ""); 656 List<MediaType> consumesList = l(); 657 for (var consume : consumesParts) { 658 consumesList.add(MediaType.of(consume)); 659 } 660 this.consumesArray = u(consumesList); 661 } 662 663 /** 664 * Returns <jk>true</jk> if this parser can handle the specified content type. 665 * 666 * @param contentType The content type to test. 667 * <br>Can be <jk>null</jk> (returns <jk>false</jk>). 668 * @return <jk>true</jk> if this parser can handle the specified content type. 669 */ 670 public boolean canHandle(String contentType) { 671 if (nn(contentType)) 672 for (var mt : getMediaTypes()) 673 if (eq(contentType, mt.toString())) 674 return true; 675 return false; 676 } 677 678 @Override /* Overridden from Context */ 679 public Builder<?> copy() { 680 return new DefaultBuilder(this); 681 } 682 683 @Override /* Overridden from Context */ 684 public ParserSession.Builder<?> createSession() { 685 return ParserSession.create(this); 686 } 687 688 /** 689 * Workhorse method. 690 * 691 * <p> 692 * Subclasses are expected to either implement this method or {@link ParserSession#doRead(ParserPipe, ClassMeta)}. 693 * 694 * @param session The current session. 695 * @param pipe Where to get the input from. 696 * @param type 697 * The class type of the object to create. 698 * If <jk>null</jk> or <code>Object.<jk>class</jk></code>, object type is based on what's being parsed. 699 * For example, when parsing JSON text, it may return a <c>String</c>, <c>Number</c>, 700 * <c>JsonMap</c>, etc... 701 * @param <T> The class type of the object to create. 702 * @return The parsed object. 703 * @throws IOException Thrown by underlying stream. 704 * @throws ParseException Malformed input encountered. 705 * @throws ExecutableException Exception occurred on invoked constructor/method/field. 706 */ 707 public <T> T doRead(ParserSession session, ParserPipe pipe, ClassMeta<T> type) throws IOException, ParseException { 708 throw uoex(); 709 } 710 711 /** 712 * Returns the media types handled based on the values passed to the <c>consumes</c> constructor parameter. 713 * 714 * @return The list of media types. Never <jk>null</jk>. 715 */ 716 public final List<MediaType> getMediaTypes() { return consumesArray; } 717 718 /** 719 * Returns the first media type handled based on the values passed to the <c>consumes</c> constructor parameter. 720 * 721 * @return The media type, or <jk>null</jk> if no media types are handled by this parser. 722 */ 723 public final MediaType getPrimaryMediaType() { return first(consumesArray).orElse(null); } 724 725 @Override /* Overridden from Context */ 726 public ParserSession getSession() { return createSession().build(); } 727 728 /** 729 * Returns <jk>true</jk> if this parser subclasses from {@link ReaderParser}. 730 * 731 * @return <jk>true</jk> if this parser subclasses from {@link ReaderParser}. 732 */ 733 public boolean isReaderParser() { return true; } 734 735 /** 736 * Same as {@link #read(Object, Type, Type...)} except optimized for a non-parameterized class. 737 * 738 * <p> 739 * This is the preferred parse method for simple types since you don't need to cast the results. 740 * 741 * <h4 class='section'>Examples:</h4> 742 * <p class='bjava'> 743 * ReaderParser <jv>parser</jv> = JsonParser.<jsf>DEFAULT</jsf>; 744 * 745 * <jc>// Parse into a string.</jc> 746 * String <jv>string</jv> = <jv>parser</jv>.read(<jv>json</jv>, String.<jk>class</jk>); 747 * 748 * <jc>// Parse into a bean.</jc> 749 * MyBean <jv>bean</jv> = <jv>parser</jv>.read(<jv>json</jv>, MyBean.<jk>class</jk>); 750 * 751 * <jc>// Parse into a bean array.</jc> 752 * MyBean[] <jv>beanArray</jv> = <jv>parser</jv>.read(<jv>json</jv>, MyBean[].<jk>class</jk>); 753 * 754 * <jc>// Parse into a linked-list of objects.</jc> 755 * List <jv>list</jv> = <jv>parser</jv>.read(<jv>json</jv>, LinkedList.<jk>class</jk>); 756 * 757 * <jc>// Parse into a map of object keys/values.</jc> 758 * Map <jv>map</jv> = <jv>parser</jv>.read(<jv>json</jv>, TreeMap.<jk>class</jk>); 759 * </p> 760 * 761 * @param <T> The class type of the object being created. 762 * @param input 763 * The input. 764 * See {@link #read(Object, Type, Type...)} for details. 765 * @param type The object type to create. 766 * @return The parsed object. 767 * @throws ParseException Malformed input encountered. 768 * @throws IOException Thrown by the underlying stream. 769 */ 770 public final <T> T read(Object input, Class<T> type) throws ParseException, IOException { 771 return getSession().read(input, type); 772 } 773 774 /** 775 * Same as {@link #read(Object, Type, Type...)} except the type has already been converted into a {@link ClassMeta} 776 * object. 777 * 778 * <p> 779 * This is mostly an internal method used by the framework. 780 * 781 * @param <T> The class type of the object being created. 782 * @param input 783 * The input. 784 * See {@link #read(Object, Type, Type...)} for details. 785 * @param type The object type to create. 786 * @return The parsed object. 787 * @throws ParseException Malformed input encountered. 788 * @throws IOException Thrown by the underlying stream. 789 */ 790 public final <T> T read(Object input, ClassMeta<T> type) throws ParseException, IOException { 791 return getSession().read(input, type); 792 } 793 794 /** 795 * Parses input into the specified object type. 796 * 797 * <p> 798 * The type can be a simple type (e.g. beans, strings, numbers) or parameterized type (collections/maps). 799 * 800 * <h4 class='section'>Examples:</h4> 801 * <p class='bjava'> 802 * ReaderParser <jv>parser</jv> = JsonParser.<jsf>DEFAULT</jsf>; 803 * 804 * <jc>// Parse into a linked-list of strings.</jc> 805 * List <jv>list1</jv> = <jv>parser</jv>.read(<jv>json</jv>, LinkedList.<jk>class</jk>, String.<jk>class</jk>); 806 * 807 * <jc>// Parse into a linked-list of beans.</jc> 808 * List <jv>list2</jv> = <jv>parser</jv>.read(<jv>json</jv>, LinkedList.<jk>class</jk>, MyBean.<jk>class</jk>); 809 * 810 * <jc>// Parse into a linked-list of linked-lists of strings.</jc> 811 * List <jv>list3</jv> = <jv>parser</jv>.read(<jv>json</jv>, LinkedList.<jk>class</jk>, LinkedList.<jk>class</jk>, String.<jk>class</jk>); 812 * 813 * <jc>// Parse into a map of string keys/values.</jc> 814 * Map <jv>map1</jv> = <jv>parser</jv>.read(<jv>json</jv>, TreeMap.<jk>class</jk>, String.<jk>class</jk>, String.<jk>class</jk>); 815 * 816 * <jc>// Parse into a map containing string keys and values of lists containing beans.</jc> 817 * Map <jv>map2</jv> = <jv>parser</jv>.read(<jv>json</jv>, TreeMap.<jk>class</jk>, String.<jk>class</jk>, List.<jk>class</jk>, MyBean.<jk>class</jk>); 818 * </p> 819 * 820 * <p> 821 * <c>Collection</c> classes are assumed to be followed by zero or one objects indicating the element type. 822 * 823 * <p> 824 * <c>Map</c> classes are assumed to be followed by zero or two meta objects indicating the key and value types. 825 * 826 * <p> 827 * The array can be arbitrarily long to indicate arbitrarily complex data structures. 828 * 829 * <h4 class='section'>Notes:</h4><ul> 830 * <li class='note'> 831 * Use the {@link #read(Object, Class)} method instead if you don't need a parameterized map/collection. 832 * </ul> 833 * 834 * @param <T> The class type of the object to create. 835 * @param input 836 * The input. 837 * <br>Character-based parsers can handle the following input class types: 838 * <ul> 839 * <li><jk>null</jk> 840 * <li>{@link Reader} 841 * <li>{@link CharSequence} 842 * <li>{@link InputStream} containing UTF-8 encoded text (or charset defined by 843 * {@link ReaderParser.Builder#streamCharset(Charset)} property value). 844 * <li><code><jk>byte</jk>[]</code> containing UTF-8 encoded text (or charset defined by 845 * {@link ReaderParser.Builder#streamCharset(Charset)} property value). 846 * </ul> 847 * <br>Stream-based parsers can handle the following input class types: 848 * <ul> 849 * <li><jk>null</jk> 850 * <li>{@link InputStream} 851 * <li><code><jk>byte</jk>[]</code> 852 * <li>{@link CharSequence} containing encoded bytes according to the {@link InputStreamParser.Builder#binaryFormat(BinaryFormat)} setting. 853 * </ul> 854 * @param type 855 * The object type to create. 856 * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType} 857 * @param args 858 * The type arguments of the class if it's a collection or map. 859 * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType} 860 * <br>Ignored if the main type is not a map or collection. 861 * @return The parsed object. 862 * @throws ParseException Malformed input encountered. 863 * @throws IOException Thrown by underlying stream. 864 * @see MarshallingSession#getClassMeta(Type,Type...) for argument syntax for maps and collections. 865 */ 866 public final <T> T read(Object input, Type type, Type...args) throws ParseException, IOException { 867 return getSession().read(input, type, args); 868 } 869 870 /** 871 * Same as {@link #read(Object, Class)} but since it's a {@link String} input doesn't throw an {@link IOException}. 872 * 873 * @param <T> The class type of the object being created. 874 * @param input 875 * The input. 876 * See {@link #read(Object, Type, Type...)} for details. 877 * @param type The object type to create. 878 * @return The parsed object. 879 * @throws ParseException Malformed input encountered. 880 */ 881 public final <T> T read(String input, Class<T> type) throws ParseException { 882 return getSession().read(input, type); 883 } 884 885 /** 886 * Same as {@link #read(Object, ClassMeta)} but since it's a {@link String} input doesn't throw an {@link IOException}. 887 * 888 * @param <T> The class type of the object being created. 889 * @param input 890 * The input. 891 * See {@link #read(Object, Type, Type...)} for details. 892 * @param type The object type to create. 893 * @return The parsed object. 894 * @throws ParseException Malformed input encountered. 895 */ 896 public final <T> T read(String input, ClassMeta<T> type) throws ParseException { 897 return getSession().read(input, type); 898 } 899 900 /** 901 * Same as {@link #read(String, ClassMeta)} but creates the parser session with a specific outer object. 902 * 903 * <p> 904 * The outer object is used when instantiating top-level non-static inner classes and when setting 905 * {@link ParentProperty @ParentProperty} fields on parsed beans. 906 * This is important when a parser is used to parse inline content (e.g. JSON5 embedded in a Markdown 907 * table cell) where the parent bean context must be preserved. 908 * 909 * @param <T> The class type of the object being created. 910 * @param input The input string to parse. 911 * @param type The object type to create. 912 * @param outer 913 * The outer object to associate with this parse session. 914 * Used for {@link ParentProperty @ParentProperty} injection and 915 * non-static inner class construction. 916 * Can be <jk>null</jk> (no outer object is associated; <ja>@ParentProperty</ja> injection and non-static inner-class construction are skipped). 917 * @return The parsed object. 918 * @throws ParseException Malformed input encountered. 919 */ 920 public final <T> T readWithOuter(String input, ClassMeta<T> type, Object outer) throws ParseException { 921 return createSession().outer(outer).build().read(input, type); 922 } 923 924 /** 925 * Same as {@link #read(Object, Type, Type...)} but since it's a {@link String} input doesn't throw an {@link IOException}. 926 * 927 * @param <T> The class type of the object being created. 928 * @param input 929 * The input. 930 * See {@link #read(Object, Type, Type...)} for details. 931 * @param type 932 * The object type to create. 933 * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType} 934 * @param args 935 * The type arguments of the class if it's a collection or map. 936 * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType} 937 * <br>Ignored if the main type is not a map or collection. 938 * @return The parsed object. 939 * @throws ParseException Malformed input encountered. 940 */ 941 public final <T> T read(String input, Type type, Type...args) throws ParseException { 942 return getSession().read(input, type, args); 943 } 944 945 /** 946 * Parses the specified array input with each entry in the object defined by the {@code argTypes} 947 * argument. 948 * 949 * <p> 950 * Used for converting arrays (e.g. <js>"[arg1,arg2,...]"</js>) into an {@code Object[]} that can be passed 951 * to the {@code Method.invoke(target, args)} method. 952 * 953 * <p> 954 * Used in the following locations: 955 * <ul class='spaced-list'> 956 * <li> 957 * Used to parse argument strings in the {@link ObjectIntrospector#invokeMethod(Method, Reader)} method. 958 * </ul> 959 * 960 * @param input The input. Subclasses can support different input types. 961 * @param argTypes Specifies the type of objects to create for each entry in the array. 962 * @return An array of parsed objects. 963 * @throws ParseException Malformed input encountered. 964 */ 965 public final Object[] readArgs(Object input, Type[] argTypes) throws ParseException { 966 if (argTypes == null || argTypes.length == 0) 967 return new Object[0]; 968 return getSession().readArgs(input, argTypes); 969 } 970 971 /** 972 * Parses the contents of the specified reader and loads the results into the specified collection. 973 * 974 * <p> 975 * Used in the following locations: 976 * <ul class='spaced-list'> 977 * <li> 978 * The various character-based constructors in {@link JsonList} (e.g. 979 * {@link JsonList#JsonList(CharSequence,Parser)}. 980 * </ul> 981 * 982 * @param <E> The element class type. 983 * @param input The input. See {@link #read(Object, ClassMeta)} for supported input types. 984 * @param c The collection being loaded. 985 * @param elementType The class type of the elements, or <jk>null</jk> to default to whatever is being parsed. 986 * @return The same collection that was passed in to allow this method to be chained. 987 * @throws ParseException Malformed input encountered. 988 * @throws UnsupportedOperationException If not implemented. 989 */ 990 public final <E> Collection<E> readIntoCollection(Object input, Collection<E> c, Type elementType) throws ParseException { 991 return getSession().readIntoCollection(input, c, elementType); 992 } 993 994 /** 995 * Parses the contents of the specified reader and loads the results into the specified map. 996 * 997 * <p> 998 * Reader must contain something that serializes to a map (such as text containing a JSON object). 999 * 1000 * <p> 1001 * Used in the following locations: 1002 * <ul class='spaced-list'> 1003 * <li> 1004 * The various character-based constructors in {@link JsonMap} (e.g. 1005 * {@link JsonMap#JsonMap(CharSequence,Parser)}). 1006 * </ul> 1007 * 1008 * @param <K> The key class type. 1009 * @param <V> The value class type. 1010 * @param input The input. See {@link #read(Object, ClassMeta)} for supported input types. 1011 * @param m The map being loaded. 1012 * @param keyType The class type of the keys, or <jk>null</jk> to default to <code>String.<jk>class</jk></code>. 1013 * @param valueType The class type of the values, or <jk>null</jk> to default to whatever is being parsed. 1014 * @return The same map that was passed in to allow this method to be chained. 1015 * @throws ParseException Malformed input encountered. 1016 * @throws UnsupportedOperationException If not implemented. 1017 */ 1018 public final <K,V> Map<K,V> readIntoMap(Object input, Map<K,V> m, Type keyType, Type valueType) throws ParseException { 1019 return getSession().readIntoMap(input, m, keyType, valueType); 1020 } 1021 1022 /** 1023 * Debug output lines. 1024 * 1025 * @see Parser.Builder#debugOutputLines(int) 1026 * @return 1027 * The number of lines of input before and after the error location to be printed as part of the exception message. 1028 */ 1029 protected final int getDebugOutputLines() { return debugOutputLines; } 1030 1031 /** 1032 * Parser listener. 1033 * 1034 * @see Parser.Builder#listener(Class) 1035 * @return 1036 * Class used to listen for errors and warnings that occur during parsing, or <jk>null</jk> if none was configured. 1037 */ 1038 protected final Class<? extends ParserListener> getListener() { return listener; } 1039 1040 /** 1041 * Auto-close streams. 1042 * 1043 * @see Parser.Builder#autoCloseStreams() 1044 * @return 1045 * <jk>true</jk> if <l>InputStreams</l> and <l>Readers</l> passed into parsers will be closed 1046 * after parsing is complete. 1047 */ 1048 protected final boolean isAutoCloseStreams() { return autoCloseStreams; } 1049 1050 /** 1051 * Trim parsed strings. 1052 * 1053 * @see Parser.Builder#trimStrings() 1054 * @return 1055 * <jk>true</jk> if string values will be trimmed of whitespace using {@link String#trim()} before being added to 1056 * the POJO. 1057 */ 1058 protected final boolean isTrimStrings() { return trimStrings; } 1059 1060 /** 1061 * Include input in errors. 1062 * 1063 * @see Parser.Builder#includeInputInErrors() 1064 * @return 1065 * <jk>true</jk> if {@link ParseException} messages include a snippet of the input around the error location. 1066 */ 1067 protected final boolean isIncludeInputInErrors() { return includeInputInErrors; } 1068 1069 /** 1070 * Returns the context-level {@link Nulls} default consulted at parse-time when no per-property 1071 * {@link MarshalledProp#nulls() @MarshalledProp(nulls=…)} is configured. 1072 * 1073 * @return The current value (never <jk>null</jk>; {@link Nulls#NOT_SET} when unconfigured). 1074 * @see Parser.Builder#nulls(Nulls) 1075 * @since 10.0.0 1076 */ 1077 public final Nulls getNulls() { return nulls; } 1078 1079 /** 1080 * Unbuffered. 1081 * 1082 * @see Parser.Builder#unbuffered() 1083 * @return 1084 * <jk>true</jk> if parsers don't use internal buffering during parsing. 1085 */ 1086 protected final boolean isUnbuffered() { return unbuffered; } 1087 1088 @Override /* Overridden from MarshallingContextable */ 1089 protected FluentMap<String,Object> properties() { 1090 return super.properties() 1091 .a("autoCloseStreams", autoCloseStreams) 1092 .a("debugOutputLines", debugOutputLines) 1093 .a("listener", listener) 1094 .a("nulls", nulls) 1095 .a("trimStrings", trimStrings) 1096 .a("includeInputInErrors", includeInputInErrors) 1097 .a("unbuffered", unbuffered); 1098 } 1099}