1 /* Jackson JSON-processor. 2 * 3 * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi 4 */ 5 package com.fasterxml.jackson.core; 6 7 import java.io.*; 8 import java.lang.ref.SoftReference; 9 import java.net.URL; 10 11 import com.fasterxml.jackson.core.format.InputAccessor; 12 import com.fasterxml.jackson.core.format.MatchStrength; 13 import com.fasterxml.jackson.core.io.*; 14 import com.fasterxml.jackson.core.json.*; 15 import com.fasterxml.jackson.core.json.async.NonBlockingJsonParser; 16 import com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer; 17 import com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer; 18 import com.fasterxml.jackson.core.util.BufferRecycler; 19 import com.fasterxml.jackson.core.util.BufferRecyclers; 20 import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; 21 import com.fasterxml.jackson.core.util.JacksonFeature; 22 23 /** 24 * The main factory class of Jackson package, used to configure and 25 * construct reader (aka parser, {@link JsonParser}) 26 * and writer (aka generator, {@link JsonGenerator}) 27 * instances. 28 *<p> 29 * Factory instances are thread-safe and reusable after configuration 30 * (if any). Typically applications and services use only a single 31 * globally shared factory instance, unless they need differently 32 * configured factories. Factory reuse is important if efficiency matters; 33 * most recycling of expensive construct is done on per-factory basis. 34 *<p> 35 * Creation of a factory instance is a light-weight operation, 36 * and since there is no need for pluggable alternative implementations 37 * (as there is no "standard" JSON processor API to implement), 38 * the default constructor is used for constructing factory 39 * instances. 40 * 41 * @author Tatu Saloranta 42 */ 43 @SuppressWarnings("resource") 44 public class JsonFactory 45 extends TokenStreamFactory 46 implements Versioned, 47 java.io.Serializable // since 2.1 (for Android, mostly) 48 { 49 private static final long serialVersionUID = 2; 50 51 /* 52 /********************************************************** 53 /* Helper types 54 /********************************************************** 55 */ 56 57 /** 58 * Enumeration that defines all on/off features that can only be 59 * changed for {@link JsonFactory}. 60 */ 61 public enum Feature 62 implements JacksonFeature // since 2.12 63 { 64 // // // Symbol handling (interning etc) 65 66 /** 67 * Feature that determines whether JSON object field names are 68 * to be canonicalized using {@link String#intern} or not: 69 * if enabled, all field names will be intern()ed (and caller 70 * can count on this being true for all such names); if disabled, 71 * no intern()ing is done. There may still be basic 72 * canonicalization (that is, same String will be used to represent 73 * all identical object property names for a single document). 74 *<p> 75 * Note: this setting only has effect if 76 * {@link #CANONICALIZE_FIELD_NAMES} is true -- otherwise no 77 * canonicalization of any sort is done. 78 *<p> 79 * This setting is enabled by default. 80 */ 81 INTERN_FIELD_NAMES(true), 82 83 /** 84 * Feature that determines whether JSON object field names are 85 * to be canonicalized (details of how canonicalization is done 86 * then further specified by 87 * {@link #INTERN_FIELD_NAMES}). 88 *<p> 89 * This setting is enabled by default. 90 */ 91 CANONICALIZE_FIELD_NAMES(true), 92 93 /** 94 * Feature that determines what happens if we encounter a case in symbol 95 * handling where number of hash collisions exceeds a safety threshold 96 * -- which almost certainly means a denial-of-service attack via generated 97 * duplicate hash codes. 98 * If feature is enabled, an {@link IllegalStateException} is 99 * thrown to indicate the suspected denial-of-service attack; if disabled, processing continues but 100 * canonicalization (and thereby <code>intern()</code>ing) is disabled) as protective 101 * measure. 102 *<p> 103 * This setting is enabled by default. 104 * 105 * @since 2.4 106 */ 107 FAIL_ON_SYMBOL_HASH_OVERFLOW(true), 108 109 /** 110 * Feature that determines whether we will use {@link BufferRecycler} with 111 * {@link ThreadLocal} and {@link SoftReference}, for efficient reuse of 112 * underlying input/output buffers. 113 * This usually makes sense on normal J2SE/J2EE server-side processing; 114 * but may not make sense on platforms where {@link SoftReference} handling 115 * is broken (like Android), or if there are retention issues due to 116 * {@link ThreadLocal} (see 117 * <a href="https://github.com/FasterXML/jackson-core/issues/189">jackson-core#189</a> 118 * for a possible case) 119 *<p> 120 * This setting is enabled by default. 121 * 122 * @since 2.6 123 */ 124 USE_THREAD_LOCAL_FOR_BUFFER_RECYCLING(true) 125 126 ; 127 128 /** 129 * Whether feature is enabled or disabled by default. 130 */ 131 private final boolean _defaultState; 132 133 /** 134 * Method that calculates bit set (flags) of all features that 135 * are enabled by default. 136 */ collectDefaults()137 public static int collectDefaults() { 138 int flags = 0; 139 for (Feature f : values()) { 140 if (f.enabledByDefault()) { flags |= f.getMask(); } 141 } 142 return flags; 143 } 144 Feature(boolean defaultState)145 private Feature(boolean defaultState) { _defaultState = defaultState; } 146 147 @Override enabledByDefault()148 public boolean enabledByDefault() { return _defaultState; } 149 @Override enabledIn(int flags)150 public boolean enabledIn(int flags) { return (flags & getMask()) != 0; } 151 @Override getMask()152 public int getMask() { return (1 << ordinal()); } 153 } 154 155 /* 156 /********************************************************** 157 /* Constants 158 /********************************************************** 159 */ 160 161 /** 162 * Name used to identify JSON format 163 * (and returned by {@link #getFormatName()} 164 */ 165 public final static String FORMAT_NAME_JSON = "JSON"; 166 167 /** 168 * Bitfield (set of flags) of all factory features that are enabled by default. 169 */ 170 protected final static int DEFAULT_FACTORY_FEATURE_FLAGS = JsonFactory.Feature.collectDefaults(); 171 172 /** 173 * Bitfield (set of flags) of all parser features that are enabled 174 * by default. 175 */ 176 protected final static int DEFAULT_PARSER_FEATURE_FLAGS = JsonParser.Feature.collectDefaults(); 177 178 /** 179 * Bitfield (set of flags) of all generator features that are enabled 180 * by default. 181 */ 182 protected final static int DEFAULT_GENERATOR_FEATURE_FLAGS = JsonGenerator.Feature.collectDefaults(); 183 184 public final static SerializableString DEFAULT_ROOT_VALUE_SEPARATOR = DefaultPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR; 185 186 /** 187 * @since 2.10 188 */ 189 public final static char DEFAULT_QUOTE_CHAR = '"'; 190 191 /* 192 /********************************************************** 193 /* Buffer, symbol table management 194 /********************************************************** 195 */ 196 197 /** 198 * Each factory comes equipped with a shared root symbol table. 199 * It should not be linked back to the original blueprint, to 200 * avoid contents from leaking between factories. 201 */ 202 protected final transient CharsToNameCanonicalizer _rootCharSymbols = CharsToNameCanonicalizer.createRoot(); 203 204 /** 205 * Alternative to the basic symbol table, some stream-based 206 * parsers use different name canonicalization method. 207 *<p> 208 * TODO: should clean up this; looks messy having 2 alternatives 209 * with not very clear differences. 210 * 211 * @since 2.6 212 */ 213 protected final transient ByteQuadsCanonicalizer _byteSymbolCanonicalizer = ByteQuadsCanonicalizer.createRoot(); 214 215 /* 216 /********************************************************** 217 /* Configuration, simple feature flags 218 /********************************************************** 219 */ 220 221 /** 222 * Currently enabled factory features. 223 */ 224 protected int _factoryFeatures = DEFAULT_FACTORY_FEATURE_FLAGS; 225 226 /** 227 * Currently enabled parser features. 228 */ 229 protected int _parserFeatures = DEFAULT_PARSER_FEATURE_FLAGS; 230 231 /** 232 * Currently enabled generator features. 233 */ 234 protected int _generatorFeatures = DEFAULT_GENERATOR_FEATURE_FLAGS; 235 236 /* 237 /********************************************************** 238 /* Configuration, helper objects 239 /********************************************************** 240 */ 241 242 /** 243 * Object that implements conversion functionality between 244 * Java objects and JSON content. For base JsonFactory implementation 245 * usually not set by default, but can be explicitly set. 246 * Sub-classes (like @link org.codehaus.jackson.map.MappingJsonFactory} 247 * usually provide an implementation. 248 */ 249 protected ObjectCodec _objectCodec; 250 251 /** 252 * Definition of custom character escapes to use for generators created 253 * by this factory, if any. If null, standard data format specific 254 * escapes are used. 255 */ 256 protected CharacterEscapes _characterEscapes; 257 258 /** 259 * Optional helper object that may decorate input sources, to do 260 * additional processing on input during parsing. 261 */ 262 protected InputDecorator _inputDecorator; 263 264 /** 265 * Optional helper object that may decorate output object, to do 266 * additional processing on output during content generation. 267 */ 268 protected OutputDecorator _outputDecorator; 269 270 /** 271 * Separator used between root-level values, if any; null indicates 272 * "do not add separator". 273 * Default separator is a single space character. 274 * 275 * @since 2.1 276 */ 277 protected SerializableString _rootValueSeparator = DEFAULT_ROOT_VALUE_SEPARATOR; 278 279 /** 280 * Optional threshold used for automatically escaping character above certain character 281 * code value: either {@code 0} to indicate that no threshold is specified, or value 282 * at or above 127 to indicate last character code that is NOT automatically escaped 283 * (but depends on other configuration rules for checking). 284 * 285 * @since 2.10 286 */ 287 protected int _maximumNonEscapedChar; 288 289 /** 290 * Character used for quoting field names (if field name quoting has not 291 * been disabled with {@link JsonWriteFeature#QUOTE_FIELD_NAMES}) 292 * and JSON String values. 293 */ 294 protected final char _quoteChar; 295 296 /* 297 /********************************************************** 298 /* Construction 299 /********************************************************** 300 */ 301 302 /** 303 * Default constructor used to create factory instances. 304 * Creation of a factory instance is a light-weight operation, 305 * but it is still a good idea to reuse limited number of 306 * factory instances (and quite often just a single instance): 307 * factories are used as context for storing some reused 308 * processing objects (such as symbol tables parsers use) 309 * and this reuse only works within context of a single 310 * factory instance. 311 */ JsonFactory()312 public JsonFactory() { this((ObjectCodec) null); } 313 JsonFactory(ObjectCodec oc)314 public JsonFactory(ObjectCodec oc) { 315 _objectCodec = oc; 316 _quoteChar = DEFAULT_QUOTE_CHAR; 317 } 318 319 /** 320 * Constructor used when copy()ing a factory instance. 321 * 322 * @since 2.2.1 323 */ JsonFactory(JsonFactory src, ObjectCodec codec)324 protected JsonFactory(JsonFactory src, ObjectCodec codec) 325 { 326 _objectCodec = codec; 327 328 // General 329 _factoryFeatures = src._factoryFeatures; 330 _parserFeatures = src._parserFeatures; 331 _generatorFeatures = src._generatorFeatures; 332 _inputDecorator = src._inputDecorator; 333 _outputDecorator = src._outputDecorator; 334 335 // JSON-specific 336 _characterEscapes = src._characterEscapes; 337 _rootValueSeparator = src._rootValueSeparator; 338 _maximumNonEscapedChar = src._maximumNonEscapedChar; 339 _quoteChar = src._quoteChar; 340 } 341 342 /** 343 * Constructor used by {@link JsonFactoryBuilder} for instantiation. 344 * 345 * @since 2.10 346 */ JsonFactory(JsonFactoryBuilder b)347 public JsonFactory(JsonFactoryBuilder b) { 348 _objectCodec = null; 349 350 // General 351 _factoryFeatures = b._factoryFeatures; 352 _parserFeatures = b._streamReadFeatures; 353 _generatorFeatures = b._streamWriteFeatures; 354 _inputDecorator = b._inputDecorator; 355 _outputDecorator = b._outputDecorator; 356 357 // JSON-specific 358 _characterEscapes = b._characterEscapes; 359 _rootValueSeparator = b._rootValueSeparator; 360 _maximumNonEscapedChar = b._maximumNonEscapedChar; 361 _quoteChar = b._quoteChar; 362 } 363 364 /** 365 * Constructor for subtypes; needed to work around the fact that before 3.0, 366 * this factory has cumbersome dual role as generic type as well as actual 367 * implementation for json. 368 * 369 * @param b Builder that contains information 370 * @param bogus Argument only needed to separate constructor signature; ignored 371 */ JsonFactory(TSFBuilder<?,?> b, boolean bogus)372 protected JsonFactory(TSFBuilder<?,?> b, boolean bogus) { 373 _objectCodec = null; 374 375 _factoryFeatures = b._factoryFeatures; 376 _parserFeatures = b._streamReadFeatures; 377 _generatorFeatures = b._streamWriteFeatures; 378 _inputDecorator = b._inputDecorator; 379 _outputDecorator = b._outputDecorator; 380 381 // JSON-specific: need to assign even if not really used 382 _characterEscapes = null; 383 _rootValueSeparator = null; 384 _maximumNonEscapedChar = 0; 385 _quoteChar = DEFAULT_QUOTE_CHAR; 386 } 387 388 /** 389 * Method that allows construction of differently configured factory, starting 390 * with settings of this factory. 391 * 392 * @since 2.10 393 */ rebuild()394 public TSFBuilder<?,?> rebuild() { 395 // 13-Jun-2018, tatu: Verify sub-classing to prevent strange bugs in format impls 396 _requireJSONFactory("Factory implementation for format (%s) MUST override `rebuild()` method"); 397 return new JsonFactoryBuilder(this); 398 } 399 400 /** 401 * Main factory method to use for constructing {@link JsonFactory} instances with 402 * different configuration: creates and returns a builder for collecting configuration 403 * settings; instance created by calling {@code build()} after all configuration 404 * set. 405 *<p> 406 * NOTE: signature unfortunately does not expose true implementation type; this 407 * will be fixed in 3.0. 408 */ builder()409 public static TSFBuilder<?,?> builder() { 410 return new JsonFactoryBuilder(); 411 } 412 413 /** 414 * Method for constructing a new {@link JsonFactory} that has 415 * the same settings as this instance, but is otherwise 416 * independent (i.e. nothing is actually shared, symbol tables 417 * are separate). 418 * Note that {@link ObjectCodec} reference is not copied but is 419 * set to null; caller typically needs to set it after calling 420 * this method. Reason for this is that the codec is used for 421 * callbacks, and assumption is that there is strict 1-to-1 422 * mapping between codec, factory. Caller has to, then, explicitly 423 * set codec after making the copy. 424 * 425 * @since 2.1 426 */ copy()427 public JsonFactory copy() 428 { 429 _checkInvalidCopy(JsonFactory.class); 430 // as per above, do clear ObjectCodec 431 return new JsonFactory(this, null); 432 } 433 434 /** 435 * @since 2.1 436 */ _checkInvalidCopy(Class<?> exp)437 protected void _checkInvalidCopy(Class<?> exp) 438 { 439 if (getClass() != exp) { 440 throw new IllegalStateException("Failed copy(): "+getClass().getName() 441 +" (version: "+version()+") does not override copy(); it has to"); 442 } 443 } 444 445 /* 446 /********************************************************** 447 /* Serializable overrides 448 /********************************************************** 449 */ 450 451 /** 452 * Method that we need to override to actually make restoration go 453 * through constructors etc. 454 * Also: must be overridden by sub-classes as well. 455 */ readResolve()456 protected Object readResolve() { 457 return new JsonFactory(this, _objectCodec); 458 } 459 460 /* 461 /********************************************************** 462 /* Capability introspection 463 /********************************************************** 464 */ 465 466 /** 467 * Introspection method that higher-level functionality may call 468 * to see whether underlying data format requires a stable ordering 469 * of object properties or not. 470 * This is usually used for determining 471 * whether to force a stable ordering (like alphabetic ordering by name) 472 * if no ordering if explicitly specified. 473 *<p> 474 * Default implementation returns <code>false</code> as JSON does NOT 475 * require stable ordering. Formats that require ordering include positional 476 * textual formats like <code>CSV</code>, and schema-based binary formats 477 * like <code>Avro</code>. 478 * 479 * @since 2.3 480 */ 481 @Override requiresPropertyOrdering()482 public boolean requiresPropertyOrdering() { return false; } 483 484 /** 485 * Introspection method that higher-level functionality may call 486 * to see whether underlying data format can read and write binary 487 * data natively; that is, embeded it as-is without using encodings 488 * such as Base64. 489 *<p> 490 * Default implementation returns <code>false</code> as JSON does not 491 * support native access: all binary content must use Base64 encoding. 492 * Most binary formats (like Smile and Avro) support native binary content. 493 * 494 * @since 2.3 495 */ 496 @Override canHandleBinaryNatively()497 public boolean canHandleBinaryNatively() { return false; } 498 499 /** 500 * Introspection method that can be used by base factory to check 501 * whether access using <code>char[]</code> is something that actual 502 * parser implementations can take advantage of, over having to 503 * use {@link java.io.Reader}. Sub-types are expected to override 504 * definition; default implementation (suitable for JSON) alleges 505 * that optimization are possible; and thereby is likely to try 506 * to access {@link java.lang.String} content by first copying it into 507 * recyclable intermediate buffer. 508 * 509 * @since 2.4 510 */ canUseCharArrays()511 public boolean canUseCharArrays() { return true; } 512 513 /** 514 * Introspection method that can be used to check whether this 515 * factory can create non-blocking parsers: parsers that do not 516 * use blocking I/O abstractions but instead use a 517 * {@link com.fasterxml.jackson.core.async.NonBlockingInputFeeder}. 518 * 519 * @since 2.9 520 */ 521 @Override canParseAsync()522 public boolean canParseAsync() { 523 // 31-May-2017, tatu: Jackson 2.9 does support async parsing for JSON, 524 // but not all other formats, so need to do this: 525 return _isJSONFactory(); 526 } 527 528 @Override getFormatReadFeatureType()529 public Class<? extends FormatFeature> getFormatReadFeatureType() { 530 return null; 531 } 532 533 @Override getFormatWriteFeatureType()534 public Class<? extends FormatFeature> getFormatWriteFeatureType() { 535 return null; 536 } 537 538 /* 539 /********************************************************** 540 /* Format detection functionality 541 /********************************************************** 542 */ 543 544 /** 545 * Method that can be used to quickly check whether given schema 546 * is something that parsers and/or generators constructed by this 547 * factory could use. Note that this means possible use, at the level 548 * of data format (i.e. schema is for same data format as parsers and 549 * generators this factory constructs); individual schema instances 550 * may have further usage restrictions. 551 * 552 * @since 2.1 553 */ 554 @Override canUseSchema(FormatSchema schema)555 public boolean canUseSchema(FormatSchema schema) { 556 if (schema == null){ 557 return false; 558 } 559 String ourFormat = getFormatName(); 560 return (ourFormat != null) && ourFormat.equals(schema.getSchemaType()); 561 } 562 563 /** 564 * Method that returns short textual id identifying format 565 * this factory supports. 566 *<p> 567 * Note: sub-classes should override this method; default 568 * implementation will return null for all sub-classes 569 */ 570 @Override getFormatName()571 public String getFormatName() 572 { 573 /* Somewhat nasty check: since we can't make this abstract 574 * (due to backwards compatibility concerns), need to prevent 575 * format name "leakage" 576 */ 577 if (getClass() == JsonFactory.class) { 578 return FORMAT_NAME_JSON; 579 } 580 return null; 581 } 582 583 /** 584 * Convenience method for trying to determine whether input via given accessor 585 * is of format type supported by this factory. 586 */ hasFormat(InputAccessor acc)587 public MatchStrength hasFormat(InputAccessor acc) throws IOException 588 { 589 // since we can't keep this abstract, only implement for "vanilla" instance 590 if (getClass() == JsonFactory.class) { 591 return hasJSONFormat(acc); 592 } 593 return null; 594 } 595 596 /** 597 * Method that can be called to determine if a custom 598 * {@link ObjectCodec} is needed for binding data parsed 599 * using {@link JsonParser} constructed by this factory 600 * (which typically also implies the same for serialization 601 * with {@link JsonGenerator}). 602 * 603 * @return True if custom codec is needed with parsers and 604 * generators created by this factory; false if a general 605 * {@link ObjectCodec} is enough 606 * 607 * @since 2.1 608 */ requiresCustomCodec()609 public boolean requiresCustomCodec() { 610 return false; 611 } 612 613 /** 614 * Helper method that can be called to determine if content accessed 615 * using given accessor seems to be JSON content. 616 */ hasJSONFormat(InputAccessor acc)617 protected MatchStrength hasJSONFormat(InputAccessor acc) throws IOException 618 { 619 return ByteSourceJsonBootstrapper.hasJSONFormat(acc); 620 } 621 622 /* 623 /********************************************************** 624 /* Versioned 625 /********************************************************** 626 */ 627 628 @Override version()629 public Version version() { 630 return PackageVersion.VERSION; 631 } 632 633 /* 634 /********************************************************** 635 /* Configuration, factory features 636 /********************************************************** 637 */ 638 639 /** 640 * Method for enabling or disabling specified parser feature 641 * (check {@link JsonParser.Feature} for list of features) 642 * 643 * @deprecated since 2.10 use {@link JsonFactoryBuilder#configure(JsonFactory.Feature, boolean)} instead 644 */ 645 @Deprecated configure(JsonFactory.Feature f, boolean state)646 public final JsonFactory configure(JsonFactory.Feature f, boolean state) { 647 return state ? enable(f) : disable(f); 648 } 649 650 /** 651 * Method for enabling specified parser feature 652 * (check {@link JsonFactory.Feature} for list of features) 653 * 654 * @deprecated since 2.10 use {@link JsonFactoryBuilder#configure(JsonFactory.Feature, boolean)} instead 655 */ 656 @Deprecated enable(JsonFactory.Feature f)657 public JsonFactory enable(JsonFactory.Feature f) { 658 _factoryFeatures |= f.getMask(); 659 return this; 660 } 661 662 /** 663 * Method for disabling specified parser features 664 * (check {@link JsonFactory.Feature} for list of features) 665 * 666 * @deprecated since 2.10 use {@link JsonFactoryBuilder#configure(JsonFactory.Feature, boolean)} instead 667 */ 668 @Deprecated disable(JsonFactory.Feature f)669 public JsonFactory disable(JsonFactory.Feature f) { 670 _factoryFeatures &= ~f.getMask(); 671 return this; 672 } 673 674 /** 675 * Checked whether specified parser feature is enabled. 676 */ isEnabled(JsonFactory.Feature f)677 public final boolean isEnabled(JsonFactory.Feature f) { 678 return (_factoryFeatures & f.getMask()) != 0; 679 } 680 681 @Override getParserFeatures()682 public final int getParserFeatures() { 683 return _parserFeatures; 684 } 685 686 @Override getGeneratorFeatures()687 public final int getGeneratorFeatures() { 688 return _generatorFeatures; 689 } 690 691 // MUST be overridden by sub-classes that support format-specific parser features 692 @Override getFormatParserFeatures()693 public int getFormatParserFeatures() { 694 return 0; 695 } 696 697 // MUST be overridden by sub-classes that support format-specific generator features 698 @Override getFormatGeneratorFeatures()699 public int getFormatGeneratorFeatures() { 700 return 0; 701 } 702 703 /* 704 /********************************************************** 705 /* Configuration, parser configuration 706 /********************************************************** 707 */ 708 709 /** 710 * Method for enabling or disabling specified parser feature 711 * (check {@link JsonParser.Feature} for list of features) 712 */ configure(JsonParser.Feature f, boolean state)713 public final JsonFactory configure(JsonParser.Feature f, boolean state) { 714 return state ? enable(f) : disable(f); 715 } 716 717 /** 718 * Method for enabling specified parser feature 719 * (check {@link JsonParser.Feature} for list of features) 720 */ enable(JsonParser.Feature f)721 public JsonFactory enable(JsonParser.Feature f) { 722 _parserFeatures |= f.getMask(); 723 return this; 724 } 725 726 /** 727 * Method for disabling specified parser features 728 * (check {@link JsonParser.Feature} for list of features) 729 */ disable(JsonParser.Feature f)730 public JsonFactory disable(JsonParser.Feature f) { 731 _parserFeatures &= ~f.getMask(); 732 return this; 733 } 734 735 /** 736 * Checked whether specified parser feature is enabled. 737 */ 738 @Override isEnabled(JsonParser.Feature f)739 public final boolean isEnabled(JsonParser.Feature f) { 740 return (_parserFeatures & f.getMask()) != 0; 741 } 742 743 /** 744 * @since 2.10 745 */ isEnabled(StreamReadFeature f)746 public final boolean isEnabled(StreamReadFeature f) { 747 return (_parserFeatures & f.mappedFeature().getMask()) != 0; 748 } 749 750 /** 751 * Method for getting currently configured input decorator (if any; 752 * there is no default decorator). 753 */ getInputDecorator()754 public InputDecorator getInputDecorator() { 755 return _inputDecorator; 756 } 757 758 /** 759 * Method for overriding currently configured input decorator 760 * 761 * @deprecated Since 2.10 use {@link JsonFactoryBuilder#inputDecorator(InputDecorator)} instead 762 */ 763 @Deprecated setInputDecorator(InputDecorator d)764 public JsonFactory setInputDecorator(InputDecorator d) { 765 _inputDecorator = d; 766 return this; 767 } 768 769 /* 770 /********************************************************** 771 /* Configuration, generator settings 772 /********************************************************** 773 */ 774 775 /** 776 * Method for enabling or disabling specified generator feature 777 * (check {@link JsonGenerator.Feature} for list of features) 778 */ configure(JsonGenerator.Feature f, boolean state)779 public final JsonFactory configure(JsonGenerator.Feature f, boolean state) { 780 return state ? enable(f) : disable(f); 781 } 782 783 /** 784 * Method for enabling specified generator features 785 * (check {@link JsonGenerator.Feature} for list of features) 786 */ enable(JsonGenerator.Feature f)787 public JsonFactory enable(JsonGenerator.Feature f) { 788 _generatorFeatures |= f.getMask(); 789 return this; 790 } 791 792 /** 793 * Method for disabling specified generator feature 794 * (check {@link JsonGenerator.Feature} for list of features) 795 */ disable(JsonGenerator.Feature f)796 public JsonFactory disable(JsonGenerator.Feature f) { 797 _generatorFeatures &= ~f.getMask(); 798 return this; 799 } 800 801 /** 802 * Check whether specified generator feature is enabled. 803 */ 804 @Override isEnabled(JsonGenerator.Feature f)805 public final boolean isEnabled(JsonGenerator.Feature f) { 806 return (_generatorFeatures & f.getMask()) != 0; 807 } 808 809 /** 810 * @since 2.10 811 */ isEnabled(StreamWriteFeature f)812 public final boolean isEnabled(StreamWriteFeature f) { 813 return (_generatorFeatures & f.mappedFeature().getMask()) != 0; 814 } 815 816 /** 817 * Method for accessing custom escapes factory uses for {@link JsonGenerator}s 818 * it creates. 819 */ getCharacterEscapes()820 public CharacterEscapes getCharacterEscapes() { return _characterEscapes; } 821 822 /** 823 * Method for defining custom escapes factory uses for {@link JsonGenerator}s 824 * it creates. 825 */ setCharacterEscapes(CharacterEscapes esc)826 public JsonFactory setCharacterEscapes(CharacterEscapes esc) { 827 _characterEscapes = esc; 828 return this; 829 } 830 831 /** 832 * Method for getting currently configured output decorator (if any; 833 * there is no default decorator). 834 */ getOutputDecorator()835 public OutputDecorator getOutputDecorator() { 836 return _outputDecorator; 837 } 838 839 /** 840 * Method for overriding currently configured output decorator 841 * 842 * @deprecated Since 2.10 use {@link JsonFactoryBuilder#inputDecorator(InputDecorator)} instead 843 */ 844 @Deprecated setOutputDecorator(OutputDecorator d)845 public JsonFactory setOutputDecorator(OutputDecorator d) { 846 _outputDecorator = d; 847 return this; 848 } 849 850 /** 851 * Method that allows overriding String used for separating root-level 852 * JSON values (default is single space character) 853 * 854 * @param sep Separator to use, if any; null means that no separator is 855 * automatically added 856 * 857 * @since 2.1 858 */ setRootValueSeparator(String sep)859 public JsonFactory setRootValueSeparator(String sep) { 860 _rootValueSeparator = (sep == null) ? null : new SerializedString(sep); 861 return this; 862 } 863 864 /** 865 * @since 2.1 866 */ getRootValueSeparator()867 public String getRootValueSeparator() { 868 return (_rootValueSeparator == null) ? null : _rootValueSeparator.getValue(); 869 } 870 871 /* 872 /********************************************************** 873 /* Configuration, other 874 /********************************************************** 875 */ 876 877 /** 878 * Method for associating a {@link ObjectCodec} (typically 879 * a <code>com.fasterxml.jackson.databind.ObjectMapper</code>) 880 * with this factory (and more importantly, parsers and generators 881 * it constructs). This is needed to use data-binding methods 882 * of {@link JsonParser} and {@link JsonGenerator} instances. 883 */ setCodec(ObjectCodec oc)884 public JsonFactory setCodec(ObjectCodec oc) { 885 _objectCodec = oc; 886 return this; 887 } 888 getCodec()889 public ObjectCodec getCodec() { return _objectCodec; } 890 891 /* 892 /********************************************************** 893 /* Parser factories, traditional (blocking) I/O sources 894 /********************************************************** 895 */ 896 897 /** 898 * Method for constructing JSON parser instance to parse 899 * contents of specified file. 900 * 901 *<p> 902 * Encoding is auto-detected from contents according to JSON 903 * specification recommended mechanism. Json specification 904 * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, 905 * so auto-detection implemented only for this charsets. 906 * For other charsets use {@link #createParser(java.io.Reader)}. 907 * 908 *<p> 909 * Underlying input stream (needed for reading contents) 910 * will be <b>owned</b> (and managed, i.e. closed as need be) by 911 * the parser, since caller has no access to it. 912 * 913 * @param f File that contains JSON content to parse 914 * 915 * @since 2.1 916 */ 917 @Override createParser(File f)918 public JsonParser createParser(File f) throws IOException, JsonParseException { 919 // true, since we create InputStream from File 920 IOContext ctxt = _createContext(f, true); 921 InputStream in = new FileInputStream(f); 922 return _createParser(_decorate(in, ctxt), ctxt); 923 } 924 925 /** 926 * Method for constructing JSON parser instance to parse 927 * contents of resource reference by given URL. 928 * 929 *<p> 930 * Encoding is auto-detected from contents according to JSON 931 * specification recommended mechanism. Json specification 932 * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, 933 * so auto-detection implemented only for this charsets. 934 * For other charsets use {@link #createParser(java.io.Reader)}. 935 * 936 *<p> 937 * Underlying input stream (needed for reading contents) 938 * will be <b>owned</b> (and managed, i.e. closed as need be) by 939 * the parser, since caller has no access to it. 940 * 941 * @param url URL pointing to resource that contains JSON content to parse 942 * 943 * @since 2.1 944 */ 945 @Override createParser(URL url)946 public JsonParser createParser(URL url) throws IOException, JsonParseException { 947 // true, since we create InputStream from URL 948 IOContext ctxt = _createContext(url, true); 949 InputStream in = _optimizedStreamFromURL(url); 950 return _createParser(_decorate(in, ctxt), ctxt); 951 } 952 953 /** 954 * Method for constructing JSON parser instance to parse 955 * the contents accessed via specified input stream. 956 *<p> 957 * The input stream will <b>not be owned</b> by 958 * the parser, it will still be managed (i.e. closed if 959 * end-of-stream is reacher, or parser close method called) 960 * if (and only if) {@link com.fasterxml.jackson.core.StreamReadFeature#AUTO_CLOSE_SOURCE} 961 * is enabled. 962 *<p> 963 * 964 * Note: no encoding argument is taken since it can always be 965 * auto-detected as suggested by JSON RFC. Json specification 966 * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, 967 * so auto-detection implemented only for this charsets. 968 * For other charsets use {@link #createParser(java.io.Reader)}. 969 * 970 * @param in InputStream to use for reading JSON content to parse 971 * 972 * @since 2.1 973 */ 974 @Override createParser(InputStream in)975 public JsonParser createParser(InputStream in) throws IOException, JsonParseException { 976 IOContext ctxt = _createContext(in, false); 977 return _createParser(_decorate(in, ctxt), ctxt); 978 } 979 980 /** 981 * Method for constructing parser for parsing 982 * the contents accessed via specified Reader. 983 <p> 984 * The read stream will <b>not be owned</b> by 985 * the parser, it will still be managed (i.e. closed if 986 * end-of-stream is reacher, or parser close method called) 987 * if (and only if) {@link com.fasterxml.jackson.core.StreamReadFeature#AUTO_CLOSE_SOURCE} 988 * is enabled. 989 * 990 * @param r Reader to use for reading JSON content to parse 991 * 992 * @since 2.1 993 */ 994 @Override createParser(Reader r)995 public JsonParser createParser(Reader r) throws IOException, JsonParseException { 996 // false -> we do NOT own Reader (did not create it) 997 IOContext ctxt = _createContext(r, false); 998 return _createParser(_decorate(r, ctxt), ctxt); 999 } 1000 1001 /** 1002 * Method for constructing parser for parsing 1003 * the contents of given byte array. 1004 * 1005 * @since 2.1 1006 */ 1007 @Override createParser(byte[] data)1008 public JsonParser createParser(byte[] data) throws IOException, JsonParseException { 1009 IOContext ctxt = _createContext(data, true); 1010 if (_inputDecorator != null) { 1011 InputStream in = _inputDecorator.decorate(ctxt, data, 0, data.length); 1012 if (in != null) { 1013 return _createParser(in, ctxt); 1014 } 1015 } 1016 return _createParser(data, 0, data.length, ctxt); 1017 } 1018 1019 /** 1020 * Method for constructing parser for parsing 1021 * the contents of given byte array. 1022 * 1023 * @param data Buffer that contains data to parse 1024 * @param offset Offset of the first data byte within buffer 1025 * @param len Length of contents to parse within buffer 1026 * 1027 * @since 2.1 1028 */ 1029 @Override createParser(byte[] data, int offset, int len)1030 public JsonParser createParser(byte[] data, int offset, int len) throws IOException, JsonParseException { 1031 IOContext ctxt = _createContext(data, true); 1032 // [JACKSON-512]: allow wrapping with InputDecorator 1033 if (_inputDecorator != null) { 1034 InputStream in = _inputDecorator.decorate(ctxt, data, offset, len); 1035 if (in != null) { 1036 return _createParser(in, ctxt); 1037 } 1038 } 1039 return _createParser(data, offset, len, ctxt); 1040 } 1041 1042 /** 1043 * Method for constructing parser for parsing 1044 * contents of given String. 1045 * 1046 * @since 2.1 1047 */ 1048 @Override createParser(String content)1049 public JsonParser createParser(String content) throws IOException, JsonParseException { 1050 final int strLen = content.length(); 1051 // Actually, let's use this for medium-sized content, up to 64kB chunk (32kb char) 1052 if ((_inputDecorator != null) || (strLen > 0x8000) || !canUseCharArrays()) { 1053 // easier to just wrap in a Reader than extend InputDecorator; or, if content 1054 // is too long for us to copy it over 1055 return createParser(new StringReader(content)); 1056 } 1057 IOContext ctxt = _createContext(content, true); 1058 char[] buf = ctxt.allocTokenBuffer(strLen); 1059 content.getChars(0, strLen, buf, 0); 1060 return _createParser(buf, 0, strLen, ctxt, true); 1061 } 1062 1063 /** 1064 * Method for constructing parser for parsing 1065 * contents of given char array. 1066 * 1067 * @since 2.4 1068 */ 1069 @Override createParser(char[] content)1070 public JsonParser createParser(char[] content) throws IOException { 1071 return createParser(content, 0, content.length); 1072 } 1073 1074 /** 1075 * Method for constructing parser for parsing contents of given char array. 1076 * 1077 * @since 2.4 1078 */ 1079 @Override createParser(char[] content, int offset, int len)1080 public JsonParser createParser(char[] content, int offset, int len) throws IOException { 1081 if (_inputDecorator != null) { // easier to just wrap in a Reader than extend InputDecorator 1082 return createParser(new CharArrayReader(content, offset, len)); 1083 } 1084 return _createParser(content, offset, len, _createContext(content, true), 1085 // important: buffer is NOT recyclable, as it's from caller 1086 false); 1087 } 1088 1089 /** 1090 * Optional method for constructing parser for reading contents from specified {@link DataInput} 1091 * instance. 1092 *<p> 1093 * If this factory does not support {@link DataInput} as source, 1094 * will throw {@link UnsupportedOperationException} 1095 * 1096 * @since 2.8 1097 */ 1098 @Override createParser(DataInput in)1099 public JsonParser createParser(DataInput in) throws IOException { 1100 IOContext ctxt = _createContext(in, false); 1101 return _createParser(_decorate(in, ctxt), ctxt); 1102 } 1103 1104 /* 1105 /********************************************************** 1106 /* Parser factories, non-blocking (async) sources 1107 /********************************************************** 1108 */ 1109 1110 /** 1111 * Optional method for constructing parser for non-blocking parsing 1112 * via {@link com.fasterxml.jackson.core.async.ByteArrayFeeder} 1113 * interface (accessed using {@link JsonParser#getNonBlockingInputFeeder()} 1114 * from constructed instance). 1115 *<p> 1116 * If this factory does not support non-blocking parsing (either at all, 1117 * or from byte array), 1118 * will throw {@link UnsupportedOperationException}. 1119 *<p> 1120 * Note that JSON-backed factory only supports parsing of UTF-8 encoded JSON content 1121 * (and US-ASCII since it is proper subset); other encodings are not supported 1122 * at this point. 1123 * 1124 * @since 2.9 1125 */ 1126 @Override createNonBlockingByteArrayParser()1127 public JsonParser createNonBlockingByteArrayParser() throws IOException 1128 { 1129 // 17-May-2017, tatu: Need to take care not to accidentally create JSON parser 1130 // for non-JSON input: 1131 _requireJSONFactory("Non-blocking source not (yet?) supported for this format (%s)"); 1132 IOContext ctxt = _createNonBlockingContext(null); 1133 ByteQuadsCanonicalizer can = _byteSymbolCanonicalizer.makeChild(_factoryFeatures); 1134 return new NonBlockingJsonParser(ctxt, _parserFeatures, can); 1135 } 1136 1137 /* 1138 /********************************************************** 1139 /* Generator factories 1140 /********************************************************** 1141 */ 1142 1143 /** 1144 * Method for constructing JSON generator for writing JSON content 1145 * using specified output stream. 1146 * Encoding to use must be specified, and needs to be one of available 1147 * types (as per JSON specification). 1148 *<p> 1149 * Underlying stream <b>is NOT owned</b> by the generator constructed, 1150 * so that generator will NOT close the output stream when 1151 * {@link JsonGenerator#close} is called (unless auto-closing 1152 * feature, 1153 * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} 1154 * is enabled). 1155 * Using application needs to close it explicitly if this is the case. 1156 *<p> 1157 * Note: there are formats that use fixed encoding (like most binary data formats) 1158 * and that ignore passed in encoding. 1159 * 1160 * @param out OutputStream to use for writing JSON content 1161 * @param enc Character encoding to use 1162 * 1163 * @since 2.1 1164 */ 1165 @Override createGenerator(OutputStream out, JsonEncoding enc)1166 public JsonGenerator createGenerator(OutputStream out, JsonEncoding enc) 1167 throws IOException 1168 { 1169 // false -> we won't manage the stream unless explicitly directed to 1170 IOContext ctxt = _createContext(out, false); 1171 ctxt.setEncoding(enc); 1172 if (enc == JsonEncoding.UTF8) { 1173 return _createUTF8Generator(_decorate(out, ctxt), ctxt); 1174 } 1175 Writer w = _createWriter(out, enc, ctxt); 1176 return _createGenerator(_decorate(w, ctxt), ctxt); 1177 } 1178 1179 /** 1180 * Convenience method for constructing generator that uses default 1181 * encoding of the format (UTF-8 for JSON and most other data formats). 1182 *<p> 1183 * Note: there are formats that use fixed encoding (like most binary data formats). 1184 * 1185 * @since 2.1 1186 */ 1187 @Override createGenerator(OutputStream out)1188 public JsonGenerator createGenerator(OutputStream out) throws IOException { 1189 return createGenerator(out, JsonEncoding.UTF8); 1190 } 1191 1192 /** 1193 * Method for constructing JSON generator for writing JSON content 1194 * using specified Writer. 1195 *<p> 1196 * Underlying stream <b>is NOT owned</b> by the generator constructed, 1197 * so that generator will NOT close the Reader when 1198 * {@link JsonGenerator#close} is called (unless auto-closing 1199 * feature, 1200 * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} is enabled). 1201 * Using application needs to close it explicitly. 1202 * 1203 * @since 2.1 1204 * 1205 * @param w Writer to use for writing JSON content 1206 */ 1207 @Override createGenerator(Writer w)1208 public JsonGenerator createGenerator(Writer w) throws IOException { 1209 IOContext ctxt = _createContext(w, false); 1210 return _createGenerator(_decorate(w, ctxt), ctxt); 1211 } 1212 1213 /** 1214 * Method for constructing JSON generator for writing JSON content 1215 * to specified file, overwriting contents it might have (or creating 1216 * it if such file does not yet exist). 1217 * Encoding to use must be specified, and needs to be one of available 1218 * types (as per JSON specification). 1219 *<p> 1220 * Underlying stream <b>is owned</b> by the generator constructed, 1221 * i.e. generator will handle closing of file when 1222 * {@link JsonGenerator#close} is called. 1223 * 1224 * @param f File to write contents to 1225 * @param enc Character encoding to use 1226 * 1227 * @since 2.1 1228 */ 1229 @Override createGenerator(File f, JsonEncoding enc)1230 public JsonGenerator createGenerator(File f, JsonEncoding enc) throws IOException 1231 { 1232 OutputStream out = new FileOutputStream(f); 1233 // true -> yes, we have to manage the stream since we created it 1234 IOContext ctxt = _createContext(out, true); 1235 ctxt.setEncoding(enc); 1236 if (enc == JsonEncoding.UTF8) { 1237 return _createUTF8Generator(_decorate(out, ctxt), ctxt); 1238 } 1239 Writer w = _createWriter(out, enc, ctxt); 1240 return _createGenerator(_decorate(w, ctxt), ctxt); 1241 } 1242 1243 /** 1244 * Method for constructing generator for writing content using specified 1245 * {@link DataOutput} instance. 1246 * 1247 * @since 2.8 1248 */ 1249 @Override createGenerator(DataOutput out, JsonEncoding enc)1250 public JsonGenerator createGenerator(DataOutput out, JsonEncoding enc) throws IOException { 1251 return createGenerator(_createDataOutputWrapper(out), enc); 1252 } 1253 1254 /** 1255 * Convenience method for constructing generator that uses default 1256 * encoding of the format (UTF-8 for JSON and most other data formats). 1257 *<p> 1258 * Note: there are formats that use fixed encoding (like most binary data formats). 1259 * 1260 * @since 2.8 1261 */ 1262 @Override createGenerator(DataOutput out)1263 public JsonGenerator createGenerator(DataOutput out) throws IOException { 1264 return createGenerator(_createDataOutputWrapper(out), JsonEncoding.UTF8); 1265 } 1266 1267 /* 1268 /********************************************************** 1269 /* Deprecated parser factory methods: to be removed from 3.x 1270 /********************************************************** 1271 */ 1272 1273 /** 1274 * Method for constructing JSON parser instance to parse 1275 * contents of specified file. 1276 *<p> 1277 * Encoding is auto-detected from contents according to JSON 1278 * specification recommended mechanism. Json specification 1279 * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, 1280 * so auto-detection implemented only for this charsets. 1281 * For other charsets use {@link #createParser(java.io.Reader)}. 1282 * 1283 *<p> 1284 * Underlying input stream (needed for reading contents) 1285 * will be <b>owned</b> (and managed, i.e. closed as need be) by 1286 * the parser, since caller has no access to it. 1287 * 1288 * @param f File that contains JSON content to parse 1289 * 1290 * @deprecated Since 2.2, use {@link #createParser(File)} instead. 1291 */ 1292 @Deprecated createJsonParser(File f)1293 public JsonParser createJsonParser(File f) throws IOException, JsonParseException { 1294 return createParser(f); 1295 } 1296 1297 /** 1298 * Method for constructing JSON parser instance to parse 1299 * contents of resource reference by given URL. 1300 * 1301 *<p> 1302 * Encoding is auto-detected from contents according to JSON 1303 * specification recommended mechanism. Json specification 1304 * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, 1305 * so auto-detection implemented only for this charsets. 1306 * For other charsets use {@link #createParser(java.io.Reader)}. 1307 * 1308 *<p> 1309 * Underlying input stream (needed for reading contents) 1310 * will be <b>owned</b> (and managed, i.e. closed as need be) by 1311 * the parser, since caller has no access to it. 1312 * 1313 * @param url URL pointing to resource that contains JSON content to parse 1314 * 1315 * @deprecated Since 2.2, use {@link #createParser(URL)} instead. 1316 */ 1317 @Deprecated createJsonParser(URL url)1318 public JsonParser createJsonParser(URL url) throws IOException, JsonParseException { 1319 return createParser(url); 1320 } 1321 1322 /** 1323 * Method for constructing JSON parser instance to parse 1324 * the contents accessed via specified input stream. 1325 *<p> 1326 * The input stream will <b>not be owned</b> by 1327 * the parser, it will still be managed (i.e. closed if 1328 * end-of-stream is reacher, or parser close method called) 1329 * if (and only if) {@link com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} 1330 * is enabled. 1331 *<p> 1332 * 1333 * Note: no encoding argument is taken since it can always be 1334 * auto-detected as suggested by JSON RFC. Json specification 1335 * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, 1336 * so auto-detection implemented only for this charsets. 1337 * For other charsets use {@link #createParser(java.io.Reader)}. 1338 * 1339 * @param in InputStream to use for reading JSON content to parse 1340 * 1341 * @deprecated Since 2.2, use {@link #createParser(InputStream)} instead. 1342 */ 1343 @Deprecated createJsonParser(InputStream in)1344 public JsonParser createJsonParser(InputStream in) throws IOException, JsonParseException { 1345 return createParser(in); 1346 } 1347 1348 /** 1349 * Method for constructing parser for parsing 1350 * the contents accessed via specified Reader. 1351 <p> 1352 * The read stream will <b>not be owned</b> by 1353 * the parser, it will still be managed (i.e. closed if 1354 * end-of-stream is reacher, or parser close method called) 1355 * if (and only if) {@link com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} 1356 * is enabled. 1357 * 1358 * @param r Reader to use for reading JSON content to parse 1359 * 1360 * @deprecated Since 2.2, use {@link #createParser(Reader)} instead. 1361 */ 1362 @Deprecated createJsonParser(Reader r)1363 public JsonParser createJsonParser(Reader r) throws IOException, JsonParseException { 1364 return createParser(r); 1365 } 1366 1367 /** 1368 * Method for constructing parser for parsing the contents of given byte array. 1369 * 1370 * @deprecated Since 2.2, use {@link #createParser(byte[])} instead. 1371 */ 1372 @Deprecated createJsonParser(byte[] data)1373 public JsonParser createJsonParser(byte[] data) throws IOException, JsonParseException { 1374 return createParser(data); 1375 } 1376 1377 /** 1378 * Method for constructing parser for parsing 1379 * the contents of given byte array. 1380 * 1381 * @param data Buffer that contains data to parse 1382 * @param offset Offset of the first data byte within buffer 1383 * @param len Length of contents to parse within buffer 1384 * 1385 * @deprecated Since 2.2, use {@link #createParser(byte[],int,int)} instead. 1386 */ 1387 @Deprecated createJsonParser(byte[] data, int offset, int len)1388 public JsonParser createJsonParser(byte[] data, int offset, int len) throws IOException, JsonParseException { 1389 return createParser(data, offset, len); 1390 } 1391 1392 /** 1393 * Method for constructing parser for parsing 1394 * contents of given String. 1395 * 1396 * @deprecated Since 2.2, use {@link #createParser(String)} instead. 1397 */ 1398 @Deprecated createJsonParser(String content)1399 public JsonParser createJsonParser(String content) throws IOException, JsonParseException { 1400 return createParser(content); 1401 } 1402 1403 /* 1404 /********************************************************** 1405 /* Deprecated generator factory methods: to be removed from 3.x 1406 /********************************************************** 1407 */ 1408 1409 /** 1410 * Method for constructing JSON generator for writing JSON content 1411 * using specified output stream. 1412 * Encoding to use must be specified, and needs to be one of available 1413 * types (as per JSON specification). 1414 *<p> 1415 * Underlying stream <b>is NOT owned</b> by the generator constructed, 1416 * so that generator will NOT close the output stream when 1417 * {@link JsonGenerator#close} is called (unless auto-closing 1418 * feature, 1419 * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} 1420 * is enabled). 1421 * Using application needs to close it explicitly if this is the case. 1422 *<p> 1423 * Note: there are formats that use fixed encoding (like most binary data formats) 1424 * and that ignore passed in encoding. 1425 * 1426 * @param out OutputStream to use for writing JSON content 1427 * @param enc Character encoding to use 1428 * 1429 * @deprecated Since 2.2, use {@link #createGenerator(OutputStream, JsonEncoding)} instead. 1430 */ 1431 @Deprecated createJsonGenerator(OutputStream out, JsonEncoding enc)1432 public JsonGenerator createJsonGenerator(OutputStream out, JsonEncoding enc) throws IOException { 1433 return createGenerator(out, enc); 1434 } 1435 1436 /** 1437 * Method for constructing JSON generator for writing JSON content 1438 * using specified Writer. 1439 *<p> 1440 * Underlying stream <b>is NOT owned</b> by the generator constructed, 1441 * so that generator will NOT close the Reader when 1442 * {@link JsonGenerator#close} is called (unless auto-closing 1443 * feature, 1444 * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} is enabled). 1445 * Using application needs to close it explicitly. 1446 * 1447 * @param out Writer to use for writing JSON content 1448 * 1449 * @deprecated Since 2.2, use {@link #createGenerator(Writer)} instead. 1450 */ 1451 @Deprecated createJsonGenerator(Writer out)1452 public JsonGenerator createJsonGenerator(Writer out) throws IOException { 1453 return createGenerator(out); 1454 } 1455 1456 /** 1457 * Convenience method for constructing generator that uses default 1458 * encoding of the format (UTF-8 for JSON and most other data formats). 1459 *<p> 1460 * Note: there are formats that use fixed encoding (like most binary data formats). 1461 * 1462 * @deprecated Since 2.2, use {@link #createGenerator(OutputStream)} instead. 1463 */ 1464 @Deprecated createJsonGenerator(OutputStream out)1465 public JsonGenerator createJsonGenerator(OutputStream out) throws IOException { 1466 return createGenerator(out, JsonEncoding.UTF8); 1467 } 1468 1469 /* 1470 /********************************************************** 1471 /* Factory methods used by factory for creating parser instances, 1472 /* overridable by sub-classes 1473 /********************************************************** 1474 */ 1475 1476 /** 1477 * Overridable factory method that actually instantiates desired parser 1478 * given {@link InputStream} and context object. 1479 *<p> 1480 * This method is specifically designed to remain 1481 * compatible between minor versions so that sub-classes can count 1482 * on it being called as expected. That is, it is part of official 1483 * interface from sub-class perspective, although not a public 1484 * method available to users of factory implementations. 1485 * 1486 * @since 2.1 1487 */ _createParser(InputStream in, IOContext ctxt)1488 protected JsonParser _createParser(InputStream in, IOContext ctxt) throws IOException { 1489 // As per [JACKSON-259], may want to fully disable canonicalization: 1490 return new ByteSourceJsonBootstrapper(ctxt, in).constructParser(_parserFeatures, 1491 _objectCodec, _byteSymbolCanonicalizer, _rootCharSymbols, _factoryFeatures); 1492 } 1493 1494 /** 1495 * Overridable factory method that actually instantiates parser 1496 * using given {@link Reader} object for reading content. 1497 *<p> 1498 * This method is specifically designed to remain 1499 * compatible between minor versions so that sub-classes can count 1500 * on it being called as expected. That is, it is part of official 1501 * interface from sub-class perspective, although not a public 1502 * method available to users of factory implementations. 1503 * 1504 * @since 2.1 1505 */ _createParser(Reader r, IOContext ctxt)1506 protected JsonParser _createParser(Reader r, IOContext ctxt) throws IOException { 1507 return new ReaderBasedJsonParser(ctxt, _parserFeatures, r, _objectCodec, 1508 _rootCharSymbols.makeChild(_factoryFeatures)); 1509 } 1510 1511 /** 1512 * Overridable factory method that actually instantiates parser 1513 * using given <code>char[]</code> object for accessing content. 1514 * 1515 * @since 2.4 1516 */ _createParser(char[] data, int offset, int len, IOContext ctxt, boolean recyclable)1517 protected JsonParser _createParser(char[] data, int offset, int len, IOContext ctxt, 1518 boolean recyclable) throws IOException { 1519 return new ReaderBasedJsonParser(ctxt, _parserFeatures, null, _objectCodec, 1520 _rootCharSymbols.makeChild(_factoryFeatures), 1521 data, offset, offset+len, recyclable); 1522 } 1523 1524 /** 1525 * Overridable factory method that actually instantiates parser 1526 * using given {@link Reader} object for reading content 1527 * passed as raw byte array. 1528 *<p> 1529 * This method is specifically designed to remain 1530 * compatible between minor versions so that sub-classes can count 1531 * on it being called as expected. That is, it is part of official 1532 * interface from sub-class perspective, although not a public 1533 * method available to users of factory implementations. 1534 */ _createParser(byte[] data, int offset, int len, IOContext ctxt)1535 protected JsonParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException 1536 { 1537 return new ByteSourceJsonBootstrapper(ctxt, data, offset, len).constructParser(_parserFeatures, 1538 _objectCodec, _byteSymbolCanonicalizer, _rootCharSymbols, _factoryFeatures); 1539 } 1540 1541 /** 1542 * Optional factory method, expected to be overridden 1543 * 1544 * @since 2.8 1545 */ _createParser(DataInput input, IOContext ctxt)1546 protected JsonParser _createParser(DataInput input, IOContext ctxt) throws IOException 1547 { 1548 // 13-May-2016, tatu: Need to take care not to accidentally create JSON parser for 1549 // non-JSON input. 1550 _requireJSONFactory("InputData source not (yet?) supported for this format (%s)"); 1551 // Also: while we can't do full bootstrapping (due to read-ahead limitations), should 1552 // at least handle possible UTF-8 BOM 1553 int firstByte = ByteSourceJsonBootstrapper.skipUTF8BOM(input); 1554 ByteQuadsCanonicalizer can = _byteSymbolCanonicalizer.makeChild(_factoryFeatures); 1555 return new UTF8DataInputJsonParser(ctxt, _parserFeatures, input, 1556 _objectCodec, can, firstByte); 1557 } 1558 1559 /* 1560 /********************************************************** 1561 /* Factory methods used by factory for creating generator instances, 1562 /* overridable by sub-classes 1563 /********************************************************** 1564 */ 1565 1566 /** 1567 * Overridable factory method that actually instantiates generator for 1568 * given {@link Writer} and context object. 1569 *<p> 1570 * This method is specifically designed to remain 1571 * compatible between minor versions so that sub-classes can count 1572 * on it being called as expected. That is, it is part of official 1573 * interface from sub-class perspective, although not a public 1574 * method available to users of factory implementations. 1575 */ _createGenerator(Writer out, IOContext ctxt)1576 protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException 1577 { 1578 WriterBasedJsonGenerator gen = new WriterBasedJsonGenerator(ctxt, 1579 _generatorFeatures, _objectCodec, out, _quoteChar); 1580 if (_maximumNonEscapedChar > 0) { 1581 gen.setHighestNonEscapedChar(_maximumNonEscapedChar); 1582 } 1583 if (_characterEscapes != null) { 1584 gen.setCharacterEscapes(_characterEscapes); 1585 } 1586 SerializableString rootSep = _rootValueSeparator; 1587 if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) { 1588 gen.setRootValueSeparator(rootSep); 1589 } 1590 return gen; 1591 } 1592 1593 /** 1594 * Overridable factory method that actually instantiates generator for 1595 * given {@link OutputStream} and context object, using UTF-8 encoding. 1596 *<p> 1597 * This method is specifically designed to remain 1598 * compatible between minor versions so that sub-classes can count 1599 * on it being called as expected. That is, it is part of official 1600 * interface from sub-class perspective, although not a public 1601 * method available to users of factory implementations. 1602 */ _createUTF8Generator(OutputStream out, IOContext ctxt)1603 protected JsonGenerator _createUTF8Generator(OutputStream out, IOContext ctxt) throws IOException { 1604 UTF8JsonGenerator gen = new UTF8JsonGenerator(ctxt, 1605 _generatorFeatures, _objectCodec, out, _quoteChar); 1606 if (_maximumNonEscapedChar > 0) { 1607 gen.setHighestNonEscapedChar(_maximumNonEscapedChar); 1608 } 1609 if (_characterEscapes != null) { 1610 gen.setCharacterEscapes(_characterEscapes); 1611 } 1612 SerializableString rootSep = _rootValueSeparator; 1613 if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) { 1614 gen.setRootValueSeparator(rootSep); 1615 } 1616 return gen; 1617 } 1618 _createWriter(OutputStream out, JsonEncoding enc, IOContext ctxt)1619 protected Writer _createWriter(OutputStream out, JsonEncoding enc, IOContext ctxt) throws IOException 1620 { 1621 // note: this should not get called any more (caller checks, dispatches) 1622 if (enc == JsonEncoding.UTF8) { // We have optimized writer for UTF-8 1623 return new UTF8Writer(ctxt, out); 1624 } 1625 // not optimal, but should do unless we really care about UTF-16/32 encoding speed 1626 return new OutputStreamWriter(out, enc.getJavaName()); 1627 } 1628 1629 /* 1630 /********************************************************** 1631 /* Internal factory methods, decorator handling 1632 /********************************************************** 1633 */ 1634 1635 /** 1636 * @since 2.4 1637 */ _decorate(InputStream in, IOContext ctxt)1638 protected final InputStream _decorate(InputStream in, IOContext ctxt) throws IOException { 1639 if (_inputDecorator != null) { 1640 InputStream in2 = _inputDecorator.decorate(ctxt, in); 1641 if (in2 != null) { 1642 return in2; 1643 } 1644 } 1645 return in; 1646 } 1647 1648 /** 1649 * @since 2.4 1650 */ _decorate(Reader in, IOContext ctxt)1651 protected final Reader _decorate(Reader in, IOContext ctxt) throws IOException { 1652 if (_inputDecorator != null) { 1653 Reader in2 = _inputDecorator.decorate(ctxt, in); 1654 if (in2 != null) { 1655 return in2; 1656 } 1657 } 1658 return in; 1659 } 1660 1661 /** 1662 * @since 2.8 1663 */ _decorate(DataInput in, IOContext ctxt)1664 protected final DataInput _decorate(DataInput in, IOContext ctxt) throws IOException { 1665 if (_inputDecorator != null) { 1666 DataInput in2 = _inputDecorator.decorate(ctxt, in); 1667 if (in2 != null) { 1668 return in2; 1669 } 1670 } 1671 return in; 1672 } 1673 1674 /** 1675 * @since 2.4 1676 */ _decorate(OutputStream out, IOContext ctxt)1677 protected final OutputStream _decorate(OutputStream out, IOContext ctxt) throws IOException { 1678 if (_outputDecorator != null) { 1679 OutputStream out2 = _outputDecorator.decorate(ctxt, out); 1680 if (out2 != null) { 1681 return out2; 1682 } 1683 } 1684 return out; 1685 } 1686 1687 /** 1688 * @since 2.4 1689 */ _decorate(Writer out, IOContext ctxt)1690 protected final Writer _decorate(Writer out, IOContext ctxt) throws IOException { 1691 if (_outputDecorator != null) { 1692 Writer out2 = _outputDecorator.decorate(ctxt, out); 1693 if (out2 != null) { 1694 return out2; 1695 } 1696 } 1697 return out; 1698 } 1699 1700 /* 1701 /********************************************************** 1702 /* Internal factory methods, other 1703 /********************************************************** 1704 */ 1705 1706 /** 1707 * Method used by factory to create buffer recycler instances 1708 * for parsers and generators. 1709 *<p> 1710 * Note: only public to give access for <code>ObjectMapper</code> 1711 */ _getBufferRecycler()1712 public BufferRecycler _getBufferRecycler() 1713 { 1714 /* 23-Apr-2015, tatu: Let's allow disabling of buffer recycling 1715 * scheme, for cases where it is considered harmful (possibly 1716 * on Android, for example) 1717 */ 1718 if (Feature.USE_THREAD_LOCAL_FOR_BUFFER_RECYCLING.enabledIn(_factoryFeatures)) { 1719 return BufferRecyclers.getBufferRecycler(); 1720 } 1721 return new BufferRecycler(); 1722 } 1723 1724 /** 1725 * Overridable factory method that actually instantiates desired 1726 * context object. 1727 */ _createContext(Object srcRef, boolean resourceManaged)1728 protected IOContext _createContext(Object srcRef, boolean resourceManaged) { 1729 return new IOContext(_getBufferRecycler(), srcRef, resourceManaged); 1730 } 1731 1732 /** 1733 * Overridable factory method that actually instantiates desired 1734 * context object for async (non-blocking) parsing 1735 * 1736 * @since 2.9.7 1737 */ _createNonBlockingContext(Object srcRef)1738 protected IOContext _createNonBlockingContext(Object srcRef) { 1739 // [jackson-core#479]: allow recycling for non-blocking parser again 1740 // now that access is thread-safe 1741 return new IOContext(_getBufferRecycler(), srcRef, false); 1742 } 1743 1744 /* 1745 /********************************************************** 1746 /* Internal helper methods 1747 /********************************************************** 1748 */ 1749 1750 /** 1751 * Helper method called to work around the problem of this class both defining 1752 * general API for constructing parsers+generators AND implementing the API 1753 * for JSON handling. Problem here is that when adding new functionality 1754 * via factory methods, it is not possible to leave these methods abstract 1755 * (because we are implementing them for JSON); but there is risk that 1756 * sub-classes do not override them all (plus older version can not implement). 1757 * So a work-around is to add a check to ensure that factory is still one 1758 * used for JSON; and if not, make base implementation of a factory method fail. 1759 * 1760 * @since 2.9 1761 */ _requireJSONFactory(String msg)1762 private final void _requireJSONFactory(String msg) { 1763 if (!_isJSONFactory()) { 1764 throw new UnsupportedOperationException(String.format(msg, getFormatName())); 1765 } 1766 } 1767 _isJSONFactory()1768 private final boolean _isJSONFactory() { 1769 // NOTE: since we only really care about whether this is standard JSON-backed factory, 1770 // or its sub-class / delegated to one, no need to check for equality, identity is enough 1771 return getFormatName() == FORMAT_NAME_JSON; 1772 } 1773 } 1774