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