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