blob: 08037aa71412734dc0e6be61e641f9845f60d28e [file] [log] [blame]
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001/* Jackson JSON-processor.
2 *
3 * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi
Tatu Salorantaf15531c2011-12-22 23:00:40 -08004 */
5package com.fasterxml.jackson.core;
6
7import java.io.*;
8import java.lang.ref.SoftReference;
9import java.net.URL;
10
11import com.fasterxml.jackson.core.format.InputAccessor;
12import com.fasterxml.jackson.core.format.MatchStrength;
13import com.fasterxml.jackson.core.io.*;
Tatu07351902012-01-19 13:12:13 -080014import com.fasterxml.jackson.core.json.*;
Cowtowncoder3a00c862015-02-04 22:30:30 -080015import com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer;
Tatu Salorantaf15531c2011-12-22 23:00:40 -080016import com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer;
17import com.fasterxml.jackson.core.util.BufferRecycler;
Tatu Salorantae6dfc692012-09-28 15:34:05 -070018import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
Tatu Salorantaf15531c2011-12-22 23:00:40 -080019
20/**
21 * The main factory class of Jackson package, used to configure and
22 * construct reader (aka parser, {@link JsonParser})
23 * and writer (aka generator, {@link JsonGenerator})
24 * instances.
25 *<p>
26 * Factory instances are thread-safe and reusable after configuration
27 * (if any). Typically applications and services use only a single
28 * globally shared factory instance, unless they need differently
29 * configured factories. Factory reuse is important if efficiency matters;
30 * most recycling of expensive construct is done on per-factory basis.
31 *<p>
32 * Creation of a factory instance is a light-weight operation,
33 * and since there is no need for pluggable alternative implementations
34 * (as there is no "standard" JSON processor API to implement),
35 * the default constructor is used for constructing factory
36 * instances.
37 *
38 * @author Tatu Saloranta
39 */
Tatu Salorantae92d04f2013-07-24 22:58:08 -070040@SuppressWarnings("resource")
Tatu Saloranta95f76a42012-10-05 13:04:23 -070041public class JsonFactory
42 implements Versioned,
43 java.io.Serializable // since 2.1 (for Android, mostly)
Tatu Salorantaf15531c2011-12-22 23:00:40 -080044{
Tatu Salorantadccffbe2015-02-05 21:17:57 -080045 private static final long serialVersionUID = 1; // since 2.6.0
Tatu Saloranta95f76a42012-10-05 13:04:23 -070046
Tatu Saloranta7b796a82013-04-27 10:18:30 -070047 /*
48 /**********************************************************
49 /* Helper types
50 /**********************************************************
Tatu Salorantaf15531c2011-12-22 23:00:40 -080051 */
Tatu Salorantae92d04f2013-07-24 22:58:08 -070052
Tatu07351902012-01-19 13:12:13 -080053 /**
54 * Enumeration that defines all on/off features that can only be
55 * changed for {@link JsonFactory}.
56 */
57 public enum Feature {
58
59 // // // Symbol handling (interning etc)
60
61 /**
62 * Feature that determines whether JSON object field names are
63 * to be canonicalized using {@link String#intern} or not:
64 * if enabled, all field names will be intern()ed (and caller
65 * can count on this being true for all such names); if disabled,
66 * no intern()ing is done. There may still be basic
67 * canonicalization (that is, same String will be used to represent
68 * all identical object property names for a single document).
69 *<p>
70 * Note: this setting only has effect if
71 * {@link #CANONICALIZE_FIELD_NAMES} is true -- otherwise no
72 * canonicalization of any sort is done.
73 *<p>
74 * This setting is enabled by default.
75 */
76 INTERN_FIELD_NAMES(true),
77
78 /**
79 * Feature that determines whether JSON object field names are
80 * to be canonicalized (details of how canonicalization is done
81 * then further specified by
82 * {@link #INTERN_FIELD_NAMES}).
83 *<p>
84 * This setting is enabled by default.
85 */
Tatu Saloranta383bc8f2014-05-24 00:47:07 -070086 CANONICALIZE_FIELD_NAMES(true),
87
88 /**
89 * Feature that determines what happens if we encounter a case in symbol
90 * handling where number of hash collisions exceeds a safety threshold
91 * -- which almost certainly means a denial-of-service attack via generated
92 * duplicate hash codes.
93 * If feature is enabled, an {@link IllegalStateException} is
94 * thrown to indicate the suspected denial-of-service attack; if disabled, processing continues but
95 * canonicalization (and thereby <code>intern()</code>ing) is disabled) as protective
96 * measure.
97 *<p>
98 * This setting is enabled by default.
99 *
100 * @since 2.4
101 */
102 FAIL_ON_SYMBOL_HASH_OVERFLOW(true),
Tatu07351902012-01-19 13:12:13 -0800103
Tatu Saloranta8891c0c2015-04-23 22:47:05 -0700104 /**
105 * Feature that determines whether we will use {@link BufferRecycler} with
106 * {@link ThreadLocal} and {@link SoftReference}, for efficient reuse of
107 * underlying input/output buffers.
108 * This usually makes sense on normal J2SE/J2EE server-side processing;
109 * but may not make sense on platforms where {@link SoftReference} handling
110 * is broken (like Android), or if there are retention issues due to
111 * {@link ThreadLocal} (see
112 * <a href="https://github.com/FasterXML/jackson-core/issues/189">Issue #189</a>
113 * for a possible case)
114 *
115 * @since 2.6
116 */
117 USE_THREAD_LOCAL_FOR_BUFFER_RECYCLING(true)
118
Tatu07351902012-01-19 13:12:13 -0800119 ;
120
121 /**
122 * Whether feature is enabled or disabled by default.
123 */
124 private final boolean _defaultState;
125
126 /**
127 * Method that calculates bit set (flags) of all features that
128 * are enabled by default.
129 */
Tatu Salorantae15b9a82014-01-24 21:01:04 -0800130 public static int collectDefaults() {
Tatu07351902012-01-19 13:12:13 -0800131 int flags = 0;
132 for (Feature f : values()) {
Tatu Salorantae15b9a82014-01-24 21:01:04 -0800133 if (f.enabledByDefault()) { flags |= f.getMask(); }
Tatu07351902012-01-19 13:12:13 -0800134 }
135 return flags;
136 }
137
Tatu Salorantae15b9a82014-01-24 21:01:04 -0800138 private Feature(boolean defaultState) { _defaultState = defaultState; }
Tatu07351902012-01-19 13:12:13 -0800139
140 public boolean enabledByDefault() { return _defaultState; }
Tatu07351902012-01-19 13:12:13 -0800141 public boolean enabledIn(int flags) { return (flags & getMask()) != 0; }
Tatu07351902012-01-19 13:12:13 -0800142 public int getMask() { return (1 << ordinal()); }
Tatu Saloranta7b796a82013-04-27 10:18:30 -0700143 }
144
145 /*
146 /**********************************************************
147 /* Constants
148 /**********************************************************
149 */
150
151 /**
152 * Name used to identify JSON format
153 * (and returned by {@link #getFormatName()}
154 */
155 public final static String FORMAT_NAME_JSON = "JSON";
156
157 /**
158 * Bitfield (set of flags) of all factory features that are enabled by default.
159 */
160 protected final static int DEFAULT_FACTORY_FEATURE_FLAGS = JsonFactory.Feature.collectDefaults();
161
162 /**
163 * Bitfield (set of flags) of all parser features that are enabled
164 * by default.
165 */
166 protected final static int DEFAULT_PARSER_FEATURE_FLAGS = JsonParser.Feature.collectDefaults();
167
168 /**
169 * Bitfield (set of flags) of all generator features that are enabled
170 * by default.
171 */
172 protected final static int DEFAULT_GENERATOR_FEATURE_FLAGS = JsonGenerator.Feature.collectDefaults();
173
174 private final static SerializableString DEFAULT_ROOT_VALUE_SEPARATOR = DefaultPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR;
175
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800176 /*
177 /**********************************************************
178 /* Buffer, symbol table management
179 /**********************************************************
180 */
181
182 /**
Tatu Saloranta10c3ec82012-09-05 19:38:49 -0700183 * This <code>ThreadLocal</code> contains a {@link java.lang.ref.SoftReference}
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800184 * to a {@link BufferRecycler} used to provide a low-cost
185 * buffer recycling between reader and writer instances.
186 */
187 final protected static ThreadLocal<SoftReference<BufferRecycler>> _recyclerRef
188 = new ThreadLocal<SoftReference<BufferRecycler>>();
189
190 /**
191 * Each factory comes equipped with a shared root symbol table.
192 * It should not be linked back to the original blueprint, to
193 * avoid contents from leaking between factories.
194 */
Tatu Saloranta95f76a42012-10-05 13:04:23 -0700195 protected final transient CharsToNameCanonicalizer _rootCharSymbols = CharsToNameCanonicalizer.createRoot();
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800196
197 /**
198 * Alternative to the basic symbol table, some stream-based
199 * parsers use different name canonicalization method.
200 *<p>
201 * TODO: should clean up this; looks messy having 2 alternatives
202 * with not very clear differences.
Tatu Salorantadccffbe2015-02-05 21:17:57 -0800203 *
204 * @since 2.6.0
205 */
206 protected final transient ByteQuadsCanonicalizer _byteSymbolCanonicalizer = ByteQuadsCanonicalizer.createRoot();
207
208 /**
209 * Earlier byte-based symbol table; replaced with 2.6 with a new implementation.
210 * Left in for version 2.6.0: will be removed in 2.7 or later.
211 *
212 * @deprecated Since 2.6.0, only use {@link #_byteSymbolCanonicalizer}
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800213 */
Tatu Saloranta4bcd7312015-02-05 21:20:57 -0800214 @Deprecated
Tatu Saloranta43f91be2015-02-06 16:03:08 -0800215 protected final transient com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer _rootByteSymbols
216 = com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer.createRoot();
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800217
218 /*
219 /**********************************************************
220 /* Configuration
221 /**********************************************************
222 */
223
224 /**
225 * Object that implements conversion functionality between
226 * Java objects and JSON content. For base JsonFactory implementation
227 * usually not set by default, but can be explicitly set.
228 * Sub-classes (like @link org.codehaus.jackson.map.MappingJsonFactory}
229 * usually provide an implementation.
230 */
231 protected ObjectCodec _objectCodec;
232
233 /**
Tatu07351902012-01-19 13:12:13 -0800234 * Currently enabled factory features.
235 */
236 protected int _factoryFeatures = DEFAULT_FACTORY_FEATURE_FLAGS;
237
238 /**
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800239 * Currently enabled parser features.
240 */
241 protected int _parserFeatures = DEFAULT_PARSER_FEATURE_FLAGS;
242
243 /**
244 * Currently enabled generator features.
245 */
246 protected int _generatorFeatures = DEFAULT_GENERATOR_FEATURE_FLAGS;
247
248 /**
249 * Definition of custom character escapes to use for generators created
250 * by this factory, if any. If null, standard data format specific
251 * escapes are used.
252 */
253 protected CharacterEscapes _characterEscapes;
254
255 /**
256 * Optional helper object that may decorate input sources, to do
257 * additional processing on input during parsing.
258 */
259 protected InputDecorator _inputDecorator;
260
261 /**
262 * Optional helper object that may decorate output object, to do
263 * additional processing on output during content generation.
264 */
265 protected OutputDecorator _outputDecorator;
Tatu Salorantae6dfc692012-09-28 15:34:05 -0700266
267 /**
268 * Separator used between root-level values, if any; null indicates
269 * "do not add separator".
270 * Default separator is a single space character.
271 *
272 * @since 2.1
273 */
274 protected SerializableString _rootValueSeparator = DEFAULT_ROOT_VALUE_SEPARATOR;
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800275
276 /*
277 /**********************************************************
278 /* Construction
279 /**********************************************************
280 */
281
282 /**
283 * Default constructor used to create factory instances.
284 * Creation of a factory instance is a light-weight operation,
285 * but it is still a good idea to reuse limited number of
286 * factory instances (and quite often just a single instance):
287 * factories are used as context for storing some reused
288 * processing objects (such as symbol tables parsers use)
289 * and this reuse only works within context of a single
290 * factory instance.
291 */
Gonçalo Silva2bba5dd2014-01-25 17:06:21 +0000292 public JsonFactory() { this(null); }
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800293
294 public JsonFactory(ObjectCodec oc) { _objectCodec = oc; }
295
Tatu Saloranta378ecdc2012-08-04 16:27:27 -0700296 /**
Tatu Saloranta7b796a82013-04-27 10:18:30 -0700297 * Constructor used when copy()ing a factory instance.
298 *
299 * @since 2.2.1
300 */
301 protected JsonFactory(JsonFactory src, ObjectCodec codec)
302 {
303 _objectCodec = null;
304 _factoryFeatures = src._factoryFeatures;
305 _parserFeatures = src._parserFeatures;
306 _generatorFeatures = src._generatorFeatures;
307 _characterEscapes = src._characterEscapes;
308 _inputDecorator = src._inputDecorator;
309 _outputDecorator = src._outputDecorator;
310 _rootValueSeparator = src._rootValueSeparator;
311
312 /* 27-Apr-2013, tatu: How about symbol table; should we try to
313 * reuse shared symbol tables? Could be more efficient that way;
314 * although can slightly add to concurrency overhead.
315 */
316 }
317
318 /**
Tatu Saloranta378ecdc2012-08-04 16:27:27 -0700319 * Method for constructing a new {@link JsonFactory} that has
320 * the same settings as this instance, but is otherwise
321 * independent (i.e. nothing is actually shared, symbol tables
322 * are separate).
323 * Note that {@link ObjectCodec} reference is not copied but is
324 * set to null; caller typically needs to set it after calling
Tatu Saloranta7b796a82013-04-27 10:18:30 -0700325 * this method. Reason for this is that the codec is used for
326 * callbacks, and assumption is that there is strict 1-to-1
327 * mapping between codec, factory. Caller has to, then, explicitly
328 * set codec after making the copy.
Tatu Saloranta378ecdc2012-08-04 16:27:27 -0700329 *
330 * @since 2.1
331 */
332 public JsonFactory copy()
333 {
334 _checkInvalidCopy(JsonFactory.class);
Tatu Saloranta7b796a82013-04-27 10:18:30 -0700335 // as per above, do clear ObjectCodec
336 return new JsonFactory(this, null);
Tatu Saloranta378ecdc2012-08-04 16:27:27 -0700337 }
Tatu Saloranta7b796a82013-04-27 10:18:30 -0700338
Tatu Saloranta378ecdc2012-08-04 16:27:27 -0700339 /**
340 * @since 2.1
341 * @param exp
342 */
343 protected void _checkInvalidCopy(Class<?> exp)
344 {
345 if (getClass() != exp) {
346 throw new IllegalStateException("Failed copy(): "+getClass().getName()
347 +" (version: "+version()+") does not override copy(); it has to");
348 }
349 }
Tatu Saloranta95f76a42012-10-05 13:04:23 -0700350
351 /*
352 /**********************************************************
353 /* Serializable overrides
354 /**********************************************************
355 */
356
357 /**
358 * Method that we need to override to actually make restoration go
359 * through constructors etc.
360 * Also: must be overridden by sub-classes as well.
361 */
362 protected Object readResolve() {
Tatu Salorantaf7741c52013-04-27 11:06:30 -0700363 return new JsonFactory(this, _objectCodec);
Tatu Saloranta95f76a42012-10-05 13:04:23 -0700364 }
Tatu Salorantaa9e5c9f2013-08-28 19:39:59 -0700365
366 /*
367 /**********************************************************
368 /* Capability introspection
369 /**********************************************************
370 */
371
372 /**
373 * Introspection method that higher-level functionality may call
374 * to see whether underlying data format requires a stable ordering
375 * of object properties or not.
376 * This is usually used for determining
377 * whether to force a stable ordering (like alphabetic ordering by name)
378 * if no ordering if explicitly specified.
379 *<p>
380 * Default implementation returns <code>false</code> as JSON does NOT
381 * require stable ordering. Formats that require ordering include positional
382 * textual formats like <code>CSV</code>, and schema-based binary formats
383 * like <code>Avro</code>.
384 *
385 * @since 2.3
386 */
Tatu475a99b2014-04-22 14:32:50 -0700387 public boolean requiresPropertyOrdering() { return false; }
Tatu Salorantab8835442013-09-14 12:12:57 -0700388
389 /**
390 * Introspection method that higher-level functionality may call
391 * to see whether underlying data format can read and write binary
392 * data natively; that is, embeded it as-is without using encodings
393 * such as Base64.
394 *<p>
395 * Default implementation returns <code>false</code> as JSON does not
396 * support native access: all binary content must use Base64 encoding.
397 * Most binary formats (like Smile and Avro) support native binary content.
398 *
399 * @since 2.3
400 */
Tatu475a99b2014-04-22 14:32:50 -0700401 public boolean canHandleBinaryNatively() { return false; }
Tatu Salorantab8835442013-09-14 12:12:57 -0700402
Tatu475a99b2014-04-22 14:32:50 -0700403 /**
404 * Introspection method that can be used by base factory to check
405 * whether access using <code>char[]</code> is something that actual
406 * parser implementations can take advantage of, over having to
407 * use {@link java.io.Reader}. Sub-types are expected to override
408 * definition; default implementation (suitable for JSON) alleges
409 * that optimization are possible; and thereby is likely to try
410 * to access {@link java.lang.String} content by first copying it into
411 * recyclable intermediate buffer.
412 *
413 * @since 2.4
414 */
415 public boolean canUseCharArrays() { return true; }
Cowtowncoder2e262b92015-05-27 17:32:17 -0700416
417 /**
418 * Method for accessing kind of {@link FormatFeature} that a parser
419 * {@link JsonParser} produced by this factory would accept, if any;
420 * <code>null</code> returned if none.
421 *
422 * @since 2.6
423 */
424 public Class<? extends FormatFeature> getFormatReadFeatureType() {
425 return null;
426 }
427
428 /**
429 * Method for accessing kind of {@link FormatFeature} that a parser
430 * {@link JsonGenerator} produced by this factory would accept, if any;
431 * <code>null</code> returned if none.
432 *
433 * @since 2.6
434 */
435 public Class<? extends FormatFeature> getFormatWriteFeatureType() {
436 return null;
437 }
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800438 /*
439 /**********************************************************
Cowtowncoder2e262b92015-05-27 17:32:17 -0700440 /* Format detection functionality
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800441 /**********************************************************
442 */
443
444 /**
Tatu Saloranta1bdf0262012-08-24 14:43:17 -0700445 * Method that can be used to quickly check whether given schema
446 * is something that parsers and/or generators constructed by this
447 * factory could use. Note that this means possible use, at the level
448 * of data format (i.e. schema is for same data format as parsers and
449 * generators this factory constructs); individual schema instances
450 * may have further usage restrictions.
451 *
452 * @since 2.1
453 */
454 public boolean canUseSchema(FormatSchema schema) {
455 String ourFormat = getFormatName();
456 return (ourFormat != null) && ourFormat.equals(schema.getSchemaType());
457 }
458
459 /**
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800460 * Method that returns short textual id identifying format
461 * this factory supports.
462 *<p>
463 * Note: sub-classes should override this method; default
464 * implementation will return null for all sub-classes
465 */
466 public String getFormatName()
467 {
468 /* Somewhat nasty check: since we can't make this abstract
469 * (due to backwards compatibility concerns), need to prevent
470 * format name "leakage"
471 */
472 if (getClass() == JsonFactory.class) {
473 return FORMAT_NAME_JSON;
474 }
475 return null;
476 }
477
Cowtowncoder2e262b92015-05-27 17:32:17 -0700478 /**
479 * Convenience method for trying to determine whether input via given accessor
480 * is of format type supported by this factory.
481 */
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800482 public MatchStrength hasFormat(InputAccessor acc) throws IOException
483 {
484 // since we can't keep this abstract, only implement for "vanilla" instance
485 if (getClass() == JsonFactory.class) {
486 return hasJSONFormat(acc);
487 }
488 return null;
489 }
490
Tatu Salorantaad2df5f2012-08-22 20:55:49 -0700491 /**
492 * Method that can be called to determine if a custom
493 * {@link ObjectCodec} is needed for binding data parsed
494 * using {@link JsonParser} constructed by this factory
495 * (which typically also implies the same for serialization
496 * with {@link JsonGenerator}).
497 *
498 * @return True if custom codec is needed with parsers and
499 * generators created by this factory; false if a general
500 * {@link ObjectCodec} is enough
501 *
502 * @since 2.1
503 */
504 public boolean requiresCustomCodec() {
505 return false;
506 }
507
508 /**
509 * Helper method that can be called to determine if content accessed
510 * using given accessor seems to be JSON content.
511 */
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800512 protected MatchStrength hasJSONFormat(InputAccessor acc) throws IOException
513 {
514 return ByteSourceJsonBootstrapper.hasJSONFormat(acc);
Tatu Salorantaad2df5f2012-08-22 20:55:49 -0700515 }
516
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800517 /*
518 /**********************************************************
519 /* Versioned
520 /**********************************************************
521 */
522
Tatu Saloranta68d79dd2013-01-10 21:13:46 -0800523 @Override
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800524 public Version version() {
Tatu Saloranta68d79dd2013-01-10 21:13:46 -0800525 return PackageVersion.VERSION;
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800526 }
527
528 /*
529 /**********************************************************
Tatu07351902012-01-19 13:12:13 -0800530 /* Configuration, factory features
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800531 /**********************************************************
532 */
533
534 /**
535 * Method for enabling or disabling specified parser feature
536 * (check {@link JsonParser.Feature} for list of features)
537 */
Tatu07351902012-01-19 13:12:13 -0800538 public final JsonFactory configure(JsonFactory.Feature f, boolean state) {
539 return state ? enable(f) : disable(f);
540 }
541
542 /**
543 * Method for enabling specified parser feature
544 * (check {@link JsonFactory.Feature} for list of features)
545 */
546 public JsonFactory enable(JsonFactory.Feature f) {
547 _factoryFeatures |= f.getMask();
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800548 return this;
549 }
550
551 /**
Tatu07351902012-01-19 13:12:13 -0800552 * Method for disabling specified parser features
553 * (check {@link JsonFactory.Feature} for list of features)
554 */
555 public JsonFactory disable(JsonFactory.Feature f) {
556 _factoryFeatures &= ~f.getMask();
557 return this;
558 }
559
560 /**
561 * Checked whether specified parser feature is enabled.
562 */
563 public final boolean isEnabled(JsonFactory.Feature f) {
564 return (_factoryFeatures & f.getMask()) != 0;
565 }
566
567 /*
568 /**********************************************************
569 /* Configuration, parser configuration
570 /**********************************************************
571 */
572
573 /**
574 * Method for enabling or disabling specified parser feature
575 * (check {@link JsonParser.Feature} for list of features)
576 */
577 public final JsonFactory configure(JsonParser.Feature f, boolean state) {
578 return state ? enable(f) : disable(f);
579 }
580
581 /**
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800582 * Method for enabling specified parser feature
583 * (check {@link JsonParser.Feature} for list of features)
584 */
585 public JsonFactory enable(JsonParser.Feature f) {
586 _parserFeatures |= f.getMask();
587 return this;
588 }
589
590 /**
591 * Method for disabling specified parser features
592 * (check {@link JsonParser.Feature} for list of features)
593 */
594 public JsonFactory disable(JsonParser.Feature f) {
595 _parserFeatures &= ~f.getMask();
596 return this;
597 }
598
599 /**
600 * Checked whether specified parser feature is enabled.
601 */
602 public final boolean isEnabled(JsonParser.Feature f) {
603 return (_parserFeatures & f.getMask()) != 0;
604 }
605
606 /**
607 * Method for getting currently configured input decorator (if any;
608 * there is no default decorator).
609 */
610 public InputDecorator getInputDecorator() {
611 return _inputDecorator;
612 }
613
614 /**
615 * Method for overriding currently configured input decorator
616 */
617 public JsonFactory setInputDecorator(InputDecorator d) {
618 _inputDecorator = d;
619 return this;
620 }
621
622 /*
623 /**********************************************************
624 /* Configuration, generator settings
625 /**********************************************************
626 */
627
628 /**
629 * Method for enabling or disabling specified generator feature
630 * (check {@link JsonGenerator.Feature} for list of features)
631 */
632 public final JsonFactory configure(JsonGenerator.Feature f, boolean state) {
Tatu07351902012-01-19 13:12:13 -0800633 return state ? enable(f) : disable(f);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800634 }
635
636
637 /**
638 * Method for enabling specified generator features
639 * (check {@link JsonGenerator.Feature} for list of features)
640 */
641 public JsonFactory enable(JsonGenerator.Feature f) {
642 _generatorFeatures |= f.getMask();
643 return this;
644 }
645
646 /**
647 * Method for disabling specified generator feature
648 * (check {@link JsonGenerator.Feature} for list of features)
649 */
650 public JsonFactory disable(JsonGenerator.Feature f) {
651 _generatorFeatures &= ~f.getMask();
652 return this;
653 }
654
655 /**
656 * Check whether specified generator feature is enabled.
657 */
658 public final boolean isEnabled(JsonGenerator.Feature f) {
659 return (_generatorFeatures & f.getMask()) != 0;
660 }
661
662 /**
663 * Method for accessing custom escapes factory uses for {@link JsonGenerator}s
664 * it creates.
665 */
Tatu Saloranta32e4e912014-01-26 19:59:28 -0800666 public CharacterEscapes getCharacterEscapes() { return _characterEscapes; }
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800667
668 /**
669 * Method for defining custom escapes factory uses for {@link JsonGenerator}s
670 * it creates.
671 */
672 public JsonFactory setCharacterEscapes(CharacterEscapes esc) {
673 _characterEscapes = esc;
674 return this;
675 }
676
677 /**
678 * Method for getting currently configured output decorator (if any;
679 * there is no default decorator).
680 */
681 public OutputDecorator getOutputDecorator() {
682 return _outputDecorator;
683 }
684
685 /**
686 * Method for overriding currently configured output decorator
687 */
688 public JsonFactory setOutputDecorator(OutputDecorator d) {
689 _outputDecorator = d;
690 return this;
691 }
Tatu Salorantae6dfc692012-09-28 15:34:05 -0700692
693 /**
694 * Method that allows overriding String used for separating root-level
695 * JSON values (default is single space character)
696 *
697 * @param sep Separator to use, if any; null means that no separator is
698 * automatically added
699 *
700 * @since 2.1
701 */
702 public JsonFactory setRootValueSeparator(String sep) {
703 _rootValueSeparator = (sep == null) ? null : new SerializedString(sep);
704 return this;
705 }
706
707 /**
708 * @since 2.1
709 */
710 public String getRootValueSeparator() {
711 return (_rootValueSeparator == null) ? null : _rootValueSeparator.getValue();
712 }
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800713
714 /*
715 /**********************************************************
716 /* Configuration, other
717 /**********************************************************
718 */
719
720 /**
721 * Method for associating a {@link ObjectCodec} (typically
Tatu Salorantad77350e2011-12-22 23:13:13 -0800722 * a <code>com.fasterxml.jackson.databind.ObjectMapper</code>)
723 * with this factory (and more importantly, parsers and generators
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800724 * it constructs). This is needed to use data-binding methods
725 * of {@link JsonParser} and {@link JsonGenerator} instances.
726 */
727 public JsonFactory setCodec(ObjectCodec oc) {
728 _objectCodec = oc;
729 return this;
730 }
731
732 public ObjectCodec getCodec() { return _objectCodec; }
733
734 /*
735 /**********************************************************
Tatu Salorantafeaabd12012-07-22 23:03:41 -0700736 /* Parser factories (new ones, as per [Issue-25])
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800737 /**********************************************************
738 */
739
740 /**
741 * Method for constructing JSON parser instance to parse
742 * contents of specified file. Encoding is auto-detected
743 * from contents according to JSON specification recommended
744 * mechanism.
745 *<p>
746 * Underlying input stream (needed for reading contents)
747 * will be <b>owned</b> (and managed, i.e. closed as need be) by
748 * the parser, since caller has no access to it.
749 *
750 * @param f File that contains JSON content to parse
Tatu Salorantafeaabd12012-07-22 23:03:41 -0700751 *
752 * @since 2.1
753 */
Tatu Saloranta32e4e912014-01-26 19:59:28 -0800754 public JsonParser createParser(File f) throws IOException, JsonParseException {
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800755 // true, since we create InputStream from File
756 IOContext ctxt = _createContext(f, true);
757 InputStream in = new FileInputStream(f);
Tatu Saloranta896000f2014-04-19 12:53:40 -0700758 return _createParser(_decorate(in, ctxt), ctxt);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800759 }
760
761 /**
762 * Method for constructing JSON parser instance to parse
763 * contents of resource reference by given URL.
764 * Encoding is auto-detected
765 * from contents according to JSON specification recommended
766 * mechanism.
767 *<p>
768 * Underlying input stream (needed for reading contents)
769 * will be <b>owned</b> (and managed, i.e. closed as need be) by
770 * the parser, since caller has no access to it.
771 *
772 * @param url URL pointing to resource that contains JSON content to parse
Tatu Saloranta68194922012-11-15 20:34:29 -0800773 *
774 * @since 2.1
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800775 */
Tatu Saloranta32e4e912014-01-26 19:59:28 -0800776 public JsonParser createParser(URL url) throws IOException, JsonParseException {
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800777 // true, since we create InputStream from URL
778 IOContext ctxt = _createContext(url, true);
779 InputStream in = _optimizedStreamFromURL(url);
Tatu Saloranta896000f2014-04-19 12:53:40 -0700780 return _createParser(_decorate(in, ctxt), ctxt);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800781 }
782
783 /**
784 * Method for constructing JSON parser instance to parse
785 * the contents accessed via specified input stream.
786 *<p>
787 * The input stream will <b>not be owned</b> by
788 * the parser, it will still be managed (i.e. closed if
789 * end-of-stream is reacher, or parser close method called)
790 * if (and only if) {@link com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE}
791 * is enabled.
792 *<p>
793 * Note: no encoding argument is taken since it can always be
Tatu Salorantafeaabd12012-07-22 23:03:41 -0700794 * auto-detected as suggested by JSON RFC.
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800795 *
796 * @param in InputStream to use for reading JSON content to parse
Tatu Saloranta68194922012-11-15 20:34:29 -0800797 *
798 * @since 2.1
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800799 */
Tatu Saloranta32e4e912014-01-26 19:59:28 -0800800 public JsonParser createParser(InputStream in) throws IOException, JsonParseException {
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800801 IOContext ctxt = _createContext(in, false);
Tatu Saloranta896000f2014-04-19 12:53:40 -0700802 return _createParser(_decorate(in, ctxt), ctxt);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800803 }
Tatu Saloranta896000f2014-04-19 12:53:40 -0700804
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800805 /**
806 * Method for constructing parser for parsing
807 * the contents accessed via specified Reader.
808 <p>
809 * The read stream will <b>not be owned</b> by
810 * the parser, it will still be managed (i.e. closed if
811 * end-of-stream is reacher, or parser close method called)
812 * if (and only if) {@link com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE}
813 * is enabled.
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800814 *
815 * @param r Reader to use for reading JSON content to parse
Tatu Saloranta68194922012-11-15 20:34:29 -0800816 *
817 * @since 2.1
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800818 */
Tatu Saloranta32e4e912014-01-26 19:59:28 -0800819 public JsonParser createParser(Reader r) throws IOException, JsonParseException {
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800820 // false -> we do NOT own Reader (did not create it)
821 IOContext ctxt = _createContext(r, false);
Tatu Saloranta896000f2014-04-19 12:53:40 -0700822 return _createParser(_decorate(r, ctxt), ctxt);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800823 }
824
825 /**
826 * Method for constructing parser for parsing
827 * the contents of given byte array.
Tatu Saloranta68194922012-11-15 20:34:29 -0800828 *
829 * @since 2.1
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800830 */
Tatu Saloranta32e4e912014-01-26 19:59:28 -0800831 public JsonParser createParser(byte[] data) throws IOException, JsonParseException {
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800832 IOContext ctxt = _createContext(data, true);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800833 if (_inputDecorator != null) {
834 InputStream in = _inputDecorator.decorate(ctxt, data, 0, data.length);
835 if (in != null) {
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -0700836 return _createParser(in, ctxt);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800837 }
838 }
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -0700839 return _createParser(data, 0, data.length, ctxt);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800840 }
841
842 /**
843 * Method for constructing parser for parsing
844 * the contents of given byte array.
845 *
846 * @param data Buffer that contains data to parse
847 * @param offset Offset of the first data byte within buffer
848 * @param len Length of contents to parse within buffer
Tatu Saloranta68194922012-11-15 20:34:29 -0800849 *
850 * @since 2.1
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800851 */
Tatu Saloranta32e4e912014-01-26 19:59:28 -0800852 public JsonParser createParser(byte[] data, int offset, int len) throws IOException, JsonParseException {
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800853 IOContext ctxt = _createContext(data, true);
854 // [JACKSON-512]: allow wrapping with InputDecorator
855 if (_inputDecorator != null) {
856 InputStream in = _inputDecorator.decorate(ctxt, data, offset, len);
857 if (in != null) {
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -0700858 return _createParser(in, ctxt);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800859 }
860 }
Tatu Saloranta68194922012-11-15 20:34:29 -0800861 return _createParser(data, offset, len, ctxt);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800862 }
863
864 /**
865 * Method for constructing parser for parsing
866 * contents of given String.
Tatu Saloranta68194922012-11-15 20:34:29 -0800867 *
868 * @since 2.1
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800869 */
Tatu Saloranta32e4e912014-01-26 19:59:28 -0800870 public JsonParser createParser(String content) throws IOException, JsonParseException {
Tatu64aa9d22014-04-18 14:07:38 -0700871 final int strLen = content.length();
872 // Actually, let's use this for medium-sized content, up to 64kB chunk (32kb char)
Tatu475a99b2014-04-22 14:32:50 -0700873 if (_inputDecorator != null || strLen > 0x8000 || !canUseCharArrays()) {
Tatu64aa9d22014-04-18 14:07:38 -0700874 // easier to just wrap in a Reader than extend InputDecorator; or, if content
875 // is too long for us to copy it over
876 return createParser(new StringReader(content));
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800877 }
Tatu64aa9d22014-04-18 14:07:38 -0700878 IOContext ctxt = _createContext(content, true);
Tatu Saloranta84dc1842014-04-18 21:07:57 -0700879 char[] buf = ctxt.allocTokenBuffer(strLen);
Tatu64aa9d22014-04-18 14:07:38 -0700880 content.getChars(0, strLen, buf, 0);
881 return _createParser(buf, 0, strLen, ctxt, true);
882 }
883
884 /**
885 * Method for constructing parser for parsing
886 * contents of given char array.
887 *
888 * @since 2.4
889 */
890 public JsonParser createParser(char[] content) throws IOException {
891 return createParser(content, 0, content.length);
892 }
893
894 /**
Tatu Saloranta896000f2014-04-19 12:53:40 -0700895 * Method for constructing parser for parsing contents of given char array.
Tatu64aa9d22014-04-18 14:07:38 -0700896 *
897 * @since 2.4
898 */
899 public JsonParser createParser(char[] content, int offset, int len) throws IOException {
900 if (_inputDecorator != null) { // easier to just wrap in a Reader than extend InputDecorator
901 return createParser(new CharArrayReader(content, offset, len));
902 }
Tatu Saloranta896000f2014-04-19 12:53:40 -0700903 return _createParser(content, offset, len, _createContext(content, true),
904 // important: buffer is NOT recyclable, as it's from caller
905 false);
Tatu Salorantaf15531c2011-12-22 23:00:40 -0800906 }
907
908 /*
909 /**********************************************************
Tatu Saloranta68194922012-11-15 20:34:29 -0800910 /* Parser factories (old ones, as per [Issue-25])
911 /**********************************************************
912 */
913
914 /**
915 * Method for constructing JSON parser instance to parse
916 * contents of specified file. Encoding is auto-detected
917 * from contents according to JSON specification recommended
918 * mechanism.
919 *<p>
920 * Underlying input stream (needed for reading contents)
921 * will be <b>owned</b> (and managed, i.e. closed as need be) by
922 * the parser, since caller has no access to it.
Tatu Saloranta68194922012-11-15 20:34:29 -0800923 *
924 * @param f File that contains JSON content to parse
925 *
926 * @deprecated Since 2.2, use {@link #createParser(File)} instead.
927 */
928 @Deprecated
Tatu Salorantaefc23672013-12-30 19:09:39 -0800929 public JsonParser createJsonParser(File f) throws IOException, JsonParseException {
Tatu Saloranta68194922012-11-15 20:34:29 -0800930 return createParser(f);
931 }
932
933 /**
934 * Method for constructing JSON parser instance to parse
935 * contents of resource reference by given URL.
936 * Encoding is auto-detected
937 * from contents according to JSON specification recommended
938 * mechanism.
939 *<p>
940 * Underlying input stream (needed for reading contents)
941 * will be <b>owned</b> (and managed, i.e. closed as need be) by
942 * the parser, since caller has no access to it.
Tatu Saloranta68194922012-11-15 20:34:29 -0800943 *
944 * @param url URL pointing to resource that contains JSON content to parse
945 *
946 * @deprecated Since 2.2, use {@link #createParser(URL)} instead.
947 */
948 @Deprecated
Tatu Salorantaefc23672013-12-30 19:09:39 -0800949 public JsonParser createJsonParser(URL url) throws IOException, JsonParseException {
Tatu Saloranta68194922012-11-15 20:34:29 -0800950 return createParser(url);
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.JsonParser.Feature#AUTO_CLOSE_SOURCE}
961 * is enabled.
962 *<p>
963 * Note: no encoding argument is taken since it can always be
964 * auto-detected as suggested by JSON RFC.
Tatu Saloranta68194922012-11-15 20:34:29 -0800965 *
966 * @param in InputStream to use for reading JSON content to parse
967 *
968 * @deprecated Since 2.2, use {@link #createParser(InputStream)} instead.
969 */
970 @Deprecated
Tatu Salorantaefc23672013-12-30 19:09:39 -0800971 public JsonParser createJsonParser(InputStream in) throws IOException, JsonParseException {
Tatu Saloranta68194922012-11-15 20:34:29 -0800972 return createParser(in);
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.JsonParser.Feature#AUTO_CLOSE_SOURCE}
983 * is enabled.
Tatu Saloranta68194922012-11-15 20:34:29 -0800984 *
985 * @param r Reader to use for reading JSON content to parse
986 *
987 * @deprecated Since 2.2, use {@link #createParser(Reader)} instead.
988 */
989 @Deprecated
Tatu Salorantaefc23672013-12-30 19:09:39 -0800990 public JsonParser createJsonParser(Reader r) throws IOException, JsonParseException {
Tatu Saloranta68194922012-11-15 20:34:29 -0800991 return createParser(r);
992 }
993
994 /**
Tatu Salorantaefc23672013-12-30 19:09:39 -0800995 * Method for constructing parser for parsing the contents of given byte array.
Tatu Saloranta68194922012-11-15 20:34:29 -0800996 *
997 * @deprecated Since 2.2, use {@link #createParser(byte[])} instead.
998 */
999 @Deprecated
Tatu Salorantaefc23672013-12-30 19:09:39 -08001000 public JsonParser createJsonParser(byte[] data) throws IOException, JsonParseException {
Tatu Saloranta68194922012-11-15 20:34:29 -08001001 return createParser(data);
1002 }
1003
1004 /**
1005 * Method for constructing parser for parsing
1006 * the contents of given byte array.
Tatu Saloranta68194922012-11-15 20:34:29 -08001007 *
1008 * @param data Buffer that contains data to parse
1009 * @param offset Offset of the first data byte within buffer
1010 * @param len Length of contents to parse within buffer
1011 *
1012 * @deprecated Since 2.2, use {@link #createParser(byte[],int,int)} instead.
1013 */
1014 @Deprecated
Tatu Salorantaefc23672013-12-30 19:09:39 -08001015 public JsonParser createJsonParser(byte[] data, int offset, int len) throws IOException, JsonParseException {
Tatu Saloranta68194922012-11-15 20:34:29 -08001016 return createParser(data, offset, len);
1017 }
1018
1019 /**
1020 * Method for constructing parser for parsing
1021 * contents of given String.
1022 *
1023 * @deprecated Since 2.2, use {@link #createParser(String)} instead.
1024 */
1025 @Deprecated
Tatu Salorantaefc23672013-12-30 19:09:39 -08001026 public JsonParser createJsonParser(String content) throws IOException, JsonParseException {
Tatu Saloranta68194922012-11-15 20:34:29 -08001027 return createParser(content);
1028 }
1029
1030 /*
1031 /**********************************************************
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001032 /* Generator factories, new (as per [Issue-25]
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001033 /**********************************************************
1034 */
1035
1036 /**
1037 * Method for constructing JSON generator for writing JSON content
1038 * using specified output stream.
1039 * Encoding to use must be specified, and needs to be one of available
1040 * types (as per JSON specification).
1041 *<p>
1042 * Underlying stream <b>is NOT owned</b> by the generator constructed,
1043 * so that generator will NOT close the output stream when
1044 * {@link JsonGenerator#close} is called (unless auto-closing
1045 * feature,
1046 * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET}
1047 * is enabled).
1048 * Using application needs to close it explicitly if this is the case.
1049 *<p>
1050 * Note: there are formats that use fixed encoding (like most binary data formats)
1051 * and that ignore passed in encoding.
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001052 *
1053 * @param out OutputStream to use for writing JSON content
1054 * @param enc Character encoding to use
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001055 *
1056 * @since 2.1
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001057 */
1058 public JsonGenerator createGenerator(OutputStream out, JsonEncoding enc)
1059 throws IOException
1060 {
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001061 // false -> we won't manage the stream unless explicitly directed to
1062 IOContext ctxt = _createContext(out, false);
1063 ctxt.setEncoding(enc);
1064 if (enc == JsonEncoding.UTF8) {
Tatu Saloranta896000f2014-04-19 12:53:40 -07001065 return _createUTF8Generator(_decorate(out, ctxt), ctxt);
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001066 }
1067 Writer w = _createWriter(out, enc, ctxt);
Tatu Saloranta896000f2014-04-19 12:53:40 -07001068 return _createGenerator(_decorate(w, ctxt), ctxt);
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001069 }
1070
1071 /**
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001072 * Convenience method for constructing generator that uses default
1073 * encoding of the format (UTF-8 for JSON and most other data formats).
1074 *<p>
1075 * Note: there are formats that use fixed encoding (like most binary data formats).
1076 *
1077 * @since 2.1
1078 */
1079 public JsonGenerator createGenerator(OutputStream out) throws IOException {
1080 return createGenerator(out, JsonEncoding.UTF8);
1081 }
1082
1083 /**
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001084 * Method for constructing JSON generator for writing JSON content
1085 * using specified Writer.
1086 *<p>
1087 * Underlying stream <b>is NOT owned</b> by the generator constructed,
1088 * so that generator will NOT close the Reader when
1089 * {@link JsonGenerator#close} is called (unless auto-closing
1090 * feature,
1091 * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} is enabled).
1092 * Using application needs to close it explicitly.
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001093 *
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001094 * @since 2.1
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001095 *
Tatu Saloranta896000f2014-04-19 12:53:40 -07001096 * @param w Writer to use for writing JSON content
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001097 */
Tatu Saloranta896000f2014-04-19 12:53:40 -07001098 public JsonGenerator createGenerator(Writer w) throws IOException {
1099 IOContext ctxt = _createContext(w, false);
1100 return _createGenerator(_decorate(w, ctxt), ctxt);
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001101 }
1102
1103 /**
1104 * Method for constructing JSON generator for writing JSON content
1105 * to specified file, overwriting contents it might have (or creating
1106 * it if such file does not yet exist).
1107 * Encoding to use must be specified, and needs to be one of available
1108 * types (as per JSON specification).
1109 *<p>
1110 * Underlying stream <b>is owned</b> by the generator constructed,
1111 * i.e. generator will handle closing of file when
1112 * {@link JsonGenerator#close} is called.
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001113 *
1114 * @param f File to write contents to
1115 * @param enc Character encoding to use
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001116 *
1117 * @since 2.1
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001118 */
Tatu Salorantab0a2e192014-04-10 09:36:07 -07001119 public JsonGenerator createGenerator(File f, JsonEncoding enc) throws IOException
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001120 {
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001121 OutputStream out = new FileOutputStream(f);
1122 // true -> yes, we have to manage the stream since we created it
1123 IOContext ctxt = _createContext(out, true);
1124 ctxt.setEncoding(enc);
1125 if (enc == JsonEncoding.UTF8) {
Tatu Saloranta896000f2014-04-19 12:53:40 -07001126 return _createUTF8Generator(_decorate(out, ctxt), ctxt);
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001127 }
1128 Writer w = _createWriter(out, enc, ctxt);
Tatu Saloranta896000f2014-04-19 12:53:40 -07001129 return _createGenerator(_decorate(w, ctxt), ctxt);
Tatu Salorantafeaabd12012-07-22 23:03:41 -07001130 }
1131
1132 /*
1133 /**********************************************************
1134 /* Generator factories, old (as per [Issue-25]
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.
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001154 *
1155 * @param out OutputStream to use for writing JSON content
1156 * @param enc Character encoding to use
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001157 *
1158 * @deprecated Since 2.2, use {@link #createGenerator(OutputStream, JsonEncoding)} instead.
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001159 */
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001160 @Deprecated
Tatu Salorantab0a2e192014-04-10 09:36:07 -07001161 public JsonGenerator createJsonGenerator(OutputStream out, JsonEncoding enc) throws IOException {
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001162 return createGenerator(out, enc);
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001163 }
1164
1165 /**
1166 * Method for constructing JSON generator for writing JSON content
1167 * using specified Writer.
1168 *<p>
1169 * Underlying stream <b>is NOT owned</b> by the generator constructed,
1170 * so that generator will NOT close the Reader when
1171 * {@link JsonGenerator#close} is called (unless auto-closing
1172 * feature,
1173 * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} is enabled).
1174 * Using application needs to close it explicitly.
1175 *
1176 * @param out Writer to use for writing JSON content
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001177 *
1178 * @deprecated Since 2.2, use {@link #createGenerator(Writer)} instead.
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001179 */
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001180 @Deprecated
Tatu Salorantab0a2e192014-04-10 09:36:07 -07001181 public JsonGenerator createJsonGenerator(Writer out) throws IOException {
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001182 return createGenerator(out);
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001183 }
1184
1185 /**
1186 * Convenience method for constructing generator that uses default
1187 * encoding of the format (UTF-8 for JSON and most other data formats).
1188 *<p>
1189 * Note: there are formats that use fixed encoding (like most binary data formats).
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001190 *
1191 * @deprecated Since 2.2, use {@link #createGenerator(OutputStream)} instead.
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001192 */
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001193 @Deprecated
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001194 public JsonGenerator createJsonGenerator(OutputStream out) throws IOException {
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001195 return createGenerator(out, JsonEncoding.UTF8);
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001196 }
1197
1198 /**
1199 * Method for constructing JSON generator for writing JSON content
1200 * to specified file, overwriting contents it might have (or creating
1201 * it if such file does not yet exist).
1202 * Encoding to use must be specified, and needs to be one of available
1203 * types (as per JSON specification).
1204 *<p>
1205 * Underlying stream <b>is owned</b> by the generator constructed,
1206 * i.e. generator will handle closing of file when
1207 * {@link JsonGenerator#close} is called.
1208 *
1209 * @param f File to write contents to
1210 * @param enc Character encoding to use
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001211 *
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001212 * @deprecated Since 2.2, use {@link #createGenerator(File,JsonEncoding)} instead.
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001213 */
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001214 @Deprecated
Tatu Salorantab0a2e192014-04-10 09:36:07 -07001215 public JsonGenerator createJsonGenerator(File f, JsonEncoding enc) throws IOException {
Tatu Saloranta4ab04ce2012-11-15 20:42:16 -08001216 return createGenerator(f, enc);
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001217 }
1218
1219 /*
1220 /**********************************************************
1221 /* Factory methods used by factory for creating parser instances,
1222 /* overridable by sub-classes
1223 /**********************************************************
1224 */
1225
1226 /**
1227 * Overridable factory method that actually instantiates desired parser
1228 * given {@link InputStream} and context object.
1229 *<p>
1230 * This method is specifically designed to remain
1231 * compatible between minor versions so that sub-classes can count
1232 * on it being called as expected. That is, it is part of official
1233 * interface from sub-class perspective, although not a public
1234 * method available to users of factory implementations.
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -07001235 *
1236 * @since 2.1
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001237 */
Tatu Salorantab0a2e192014-04-10 09:36:07 -07001238 protected JsonParser _createParser(InputStream in, IOContext ctxt) throws IOException {
Tatu Saloranta68194922012-11-15 20:34:29 -08001239 // As per [JACKSON-259], may want to fully disable canonicalization:
1240 return new ByteSourceJsonBootstrapper(ctxt, in).constructParser(_parserFeatures,
Tatu Salorantadccffbe2015-02-05 21:17:57 -08001241 _objectCodec, _byteSymbolCanonicalizer, _rootCharSymbols, _factoryFeatures);
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -07001242 }
1243
1244 /**
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001245 * Overridable factory method that actually instantiates parser
1246 * using given {@link Reader} object for reading content.
1247 *<p>
1248 * This method is specifically designed to remain
1249 * compatible between minor versions so that sub-classes can count
1250 * on it being called as expected. That is, it is part of official
1251 * interface from sub-class perspective, although not a public
1252 * method available to users of factory implementations.
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -07001253 *
1254 * @since 2.1
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001255 */
Tatu Salorantab0a2e192014-04-10 09:36:07 -07001256 protected JsonParser _createParser(Reader r, IOContext ctxt) throws IOException {
Tatu Saloranta68194922012-11-15 20:34:29 -08001257 return new ReaderBasedJsonParser(ctxt, _parserFeatures, r, _objectCodec,
Tatu Saloranta0541b3b2014-05-23 20:20:46 -07001258 _rootCharSymbols.makeChild(_factoryFeatures));
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -07001259 }
1260
1261 /**
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001262 * Overridable factory method that actually instantiates parser
Tatu64aa9d22014-04-18 14:07:38 -07001263 * using given <code>char[]</code> object for accessing content.
1264 *
1265 * @since 2.4
1266 */
1267 protected JsonParser _createParser(char[] data, int offset, int len, IOContext ctxt,
1268 boolean recyclable) throws IOException {
1269 return new ReaderBasedJsonParser(ctxt, _parserFeatures, null, _objectCodec,
Tatu Saloranta0541b3b2014-05-23 20:20:46 -07001270 _rootCharSymbols.makeChild(_factoryFeatures),
1271 data, offset, offset+len, recyclable);
Tatu64aa9d22014-04-18 14:07:38 -07001272 }
1273
1274 /**
1275 * Overridable factory method that actually instantiates parser
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001276 * using given {@link Reader} object for reading content
1277 * passed as raw byte array.
1278 *<p>
1279 * This method is specifically designed to remain
1280 * compatible between minor versions so that sub-classes can count
1281 * on it being called as expected. That is, it is part of official
1282 * interface from sub-class perspective, although not a public
1283 * method available to users of factory implementations.
1284 */
Tatu64aa9d22014-04-18 14:07:38 -07001285 protected JsonParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001286 {
Tatu Saloranta68194922012-11-15 20:34:29 -08001287 return new ByteSourceJsonBootstrapper(ctxt, data, offset, len).constructParser(_parserFeatures,
Tatu Salorantadccffbe2015-02-05 21:17:57 -08001288 _objectCodec, _byteSymbolCanonicalizer, _rootCharSymbols, _factoryFeatures);
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -07001289 }
1290
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001291 /*
1292 /**********************************************************
1293 /* Factory methods used by factory for creating generator instances,
1294 /* overridable by sub-classes
1295 /**********************************************************
1296 */
1297
1298 /**
1299 * Overridable factory method that actually instantiates generator for
1300 * given {@link Writer} and context object.
1301 *<p>
1302 * This method is specifically designed to remain
1303 * compatible between minor versions so that sub-classes can count
1304 * on it being called as expected. That is, it is part of official
1305 * interface from sub-class perspective, although not a public
1306 * method available to users of factory implementations.
1307 */
Tatu Salorantaefc23672013-12-30 19:09:39 -08001308 protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -07001309 {
Tatu Salorantae6dfc692012-09-28 15:34:05 -07001310 WriterBasedJsonGenerator gen = new WriterBasedJsonGenerator(ctxt,
1311 _generatorFeatures, _objectCodec, out);
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001312 if (_characterEscapes != null) {
1313 gen.setCharacterEscapes(_characterEscapes);
1314 }
Tatu Salorantae6dfc692012-09-28 15:34:05 -07001315 SerializableString rootSep = _rootValueSeparator;
1316 if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) {
1317 gen.setRootValueSeparator(rootSep);
1318 }
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001319 return gen;
1320 }
1321
1322 /**
1323 * Overridable factory method that actually instantiates generator for
1324 * given {@link OutputStream} and context object, using UTF-8 encoding.
1325 *<p>
1326 * This method is specifically designed to remain
1327 * compatible between minor versions so that sub-classes can count
1328 * on it being called as expected. That is, it is part of official
1329 * interface from sub-class perspective, although not a public
1330 * method available to users of factory implementations.
1331 */
Tatu Salorantaeeb2fbd2012-05-28 22:00:08 -07001332 protected JsonGenerator _createUTF8Generator(OutputStream out, IOContext ctxt) throws IOException {
Tatu Salorantae6dfc692012-09-28 15:34:05 -07001333 UTF8JsonGenerator gen = new UTF8JsonGenerator(ctxt,
1334 _generatorFeatures, _objectCodec, out);
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001335 if (_characterEscapes != null) {
1336 gen.setCharacterEscapes(_characterEscapes);
1337 }
Tatu Salorantae6dfc692012-09-28 15:34:05 -07001338 SerializableString rootSep = _rootValueSeparator;
1339 if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) {
1340 gen.setRootValueSeparator(rootSep);
1341 }
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001342 return gen;
1343 }
1344
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001345 protected Writer _createWriter(OutputStream out, JsonEncoding enc, IOContext ctxt) throws IOException
1346 {
1347 // note: this should not get called any more (caller checks, dispatches)
1348 if (enc == JsonEncoding.UTF8) { // We have optimized writer for UTF-8
1349 return new UTF8Writer(ctxt, out);
1350 }
1351 // not optimal, but should do unless we really care about UTF-16/32 encoding speed
1352 return new OutputStreamWriter(out, enc.getJavaName());
1353 }
Tatu Saloranta896000f2014-04-19 12:53:40 -07001354
1355 /*
1356 /**********************************************************
1357 /* Internal factory methods, decorator handling
1358 /**********************************************************
1359 */
1360
1361 /**
1362 * @since 2.4
1363 */
1364 protected final InputStream _decorate(InputStream in, IOContext ctxt) throws IOException {
1365 if (_inputDecorator != null) {
1366 InputStream in2 = _inputDecorator.decorate(ctxt, in);
1367 if (in2 != null) {
1368 return in2;
1369 }
1370 }
1371 return in;
1372 }
1373
1374 /**
1375 * @since 2.4
1376 */
1377 protected final Reader _decorate(Reader in, IOContext ctxt) throws IOException {
1378 if (_inputDecorator != null) {
1379 Reader in2 = _inputDecorator.decorate(ctxt, in);
1380 if (in2 != null) {
1381 return in2;
1382 }
1383 }
1384 return in;
1385 }
1386
1387 /**
1388 * @since 2.4
1389 */
1390 protected final OutputStream _decorate(OutputStream out, IOContext ctxt) throws IOException {
1391 if (_outputDecorator != null) {
1392 OutputStream out2 = _outputDecorator.decorate(ctxt, out);
1393 if (out2 != null) {
1394 return out2;
1395 }
1396 }
1397 return out;
1398 }
1399
1400 /**
1401 * @since 2.4
1402 */
1403 protected final Writer _decorate(Writer out, IOContext ctxt) throws IOException {
1404 if (_outputDecorator != null) {
1405 Writer out2 = _outputDecorator.decorate(ctxt, out);
1406 if (out2 != null) {
1407 return out2;
1408 }
1409 }
1410 return out;
1411 }
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001412
1413 /*
1414 /**********************************************************
1415 /* Internal factory methods, other
1416 /**********************************************************
1417 */
1418
1419 /**
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001420 * Method used by factory to create buffer recycler instances
1421 * for parsers and generators.
1422 *<p>
1423 * Note: only public to give access for <code>ObjectMapper</code>
1424 */
1425 public BufferRecycler _getBufferRecycler()
1426 {
Tatu Saloranta8891c0c2015-04-23 22:47:05 -07001427 BufferRecycler br;
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001428
Tatu Saloranta8891c0c2015-04-23 22:47:05 -07001429 /* 23-Apr-2015, tatu: Let's allow disabling of buffer recycling
1430 * scheme, for cases where it is considered harmful (possibly
1431 * on Android, for example)
1432 */
1433 if (isEnabled(Feature.USE_THREAD_LOCAL_FOR_BUFFER_RECYCLING)) {
1434 SoftReference<BufferRecycler> ref = _recyclerRef.get();
1435 br = (ref == null) ? null : ref.get();
1436
1437 if (br == null) {
1438 br = new BufferRecycler();
1439 _recyclerRef.set(new SoftReference<BufferRecycler>(br));
1440 }
1441 } else {
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001442 br = new BufferRecycler();
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001443 }
1444 return br;
1445 }
1446
1447 /**
Tatu Saloranta896000f2014-04-19 12:53:40 -07001448 * Overridable factory method that actually instantiates desired
1449 * context object.
1450 */
1451 protected IOContext _createContext(Object srcRef, boolean resourceManaged) {
1452 return new IOContext(_getBufferRecycler(), srcRef, resourceManaged);
1453 }
1454
1455 /**
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001456 * Helper methods used for constructing an optimal stream for
1457 * parsers to use, when input is to be read from an URL.
1458 * This helps when reading file content via URL.
1459 */
Tatu Salorantaefc23672013-12-30 19:09:39 -08001460 protected InputStream _optimizedStreamFromURL(URL url) throws IOException {
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001461 if ("file".equals(url.getProtocol())) {
1462 /* Can not do this if the path refers
1463 * to a network drive on windows. This fixes the problem;
1464 * might not be needed on all platforms (NFS?), but should not
1465 * matter a lot: performance penalty of extra wrapping is more
1466 * relevant when accessing local file system.
1467 */
1468 String host = url.getHost();
1469 if (host == null || host.length() == 0) {
Tatu Saloranta61d5bdd2013-01-11 19:02:01 -08001470 // [Issue#48]: Let's try to avoid probs with URL encoded stuff
1471 String path = url.getPath();
1472 if (path.indexOf('%') < 0) {
1473 return new FileInputStream(url.getPath());
1474
1475 }
1476 // otherwise, let's fall through and let URL decoder do its magic
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001477 }
1478 }
1479 return url.openStream();
1480 }
1481}