1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
|
package com.fasterxml.jackson.dataformat.yaml;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.regex.Pattern;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.DumperOptions.ScalarStyle;
import org.yaml.snakeyaml.emitter.Emitter;
import org.yaml.snakeyaml.events.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.base.GeneratorBase;
import com.fasterxml.jackson.core.json.JsonWriteContext;
import com.fasterxml.jackson.core.io.IOContext;
public class YAMLGenerator extends GeneratorBase
{
/**
* Enumeration that defines all togglable features for YAML generators
*/
public enum Feature // implements FormatFeature // for 2.7
{
/**
* Whether we are to write an explicit document start marker ("---")
* or not.
*
* @since 2.3
*/
WRITE_DOC_START_MARKER(true),
/**
* Whether to use YAML native Object Id construct for indicating type (true);
* or "generic" Object Id mechanism (false). Former works better for systems that
* are YAML-centric; latter may be better choice for interoperability, when
* converting between formats or accepting other formats.
*
* @since 2.5
*/
USE_NATIVE_OBJECT_ID(true),
/**
* Whether to use YAML native Type Id construct for indicating type (true);
* or "generic" type property (false). Former works better for systems that
* are YAML-centric; latter may be better choice for interoperability, when
* converting between formats or accepting other formats.
*
* @since 2.5
*/
USE_NATIVE_TYPE_ID(true),
/**
* Do we try to force so-called canonical output or not.
*/
CANONICAL_OUTPUT(false),
/**
* Options passed to SnakeYAML that determines whether longer textual content
* gets automatically split into multiple lines or not.
*<p>
* Feature is enabled by default to conform to SnakeYAML defaults as well as
* backwards compatibility with 2.5 and earlier versions.
*
* @since 2.6
*/
SPLIT_LINES(true),
/**
* Whether strings will be rendered without quotes (true) or
* with quotes (false, default).
*<p>
* Minimized quote usage makes for more human readable output; however, content is
* limited to printable characters according to the rules of
* <a href="http://www.yaml.org/spec/1.2/spec.html#style/block/literal">literal block style</a>.
*
* @since 2.7
*/
MINIMIZE_QUOTES(false),
/**
* Whether numbers stored as strings will be rendered with quotes (true) or
* without quotes (false, default) when MINIMIZE_QUOTES is enabled.
*<p>
* Minimized quote usage makes for more human readable output; however, content is
* limited to printable characters according to the rules of
* <a href="http://www.yaml.org/spec/1.2/spec.html#style/block/literal">literal block style</a>.
*
* @since 2.8.2
*/
ALWAYS_QUOTE_NUMBERS_AS_STRINGS(false)
;
protected final boolean _defaultState;
protected final int _mask;
/**
* Method that calculates bit set (flags) of all features that
* are enabled by default.
*/
public static int collectDefaults()
{
int flags = 0;
for (Feature f : values()) {
if (f.enabledByDefault()) {
flags |= f.getMask();
}
}
return flags;
}
private Feature(boolean defaultState) {
_defaultState = defaultState;
_mask = (1 << ordinal());
}
public boolean enabledByDefault() { return _defaultState; }
public boolean enabledIn(int flags) { return (flags & _mask) != 0; }
public int getMask() { return _mask; }
}
/*
/**********************************************************
/* Internal constants
/**********************************************************
*/
protected final static long MIN_INT_AS_LONG = (long) Integer.MIN_VALUE;
protected final static long MAX_INT_AS_LONG = (long) Integer.MAX_VALUE;
protected final static Pattern PLAIN_NUMBER_P = Pattern.compile("[0-9]*(\\.[0-9]*)?");
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
final protected IOContext _ioContext;
/**
* Bit flag composed of bits that indicate which
* {@link YAMLGenerator.Feature}s
* are enabled.
*/
protected int _formatFeatures;
protected Writer _writer;
protected DumperOptions _outputOptions;
// for field names, leave out quotes
private final static DumperOptions.ScalarStyle STYLE_NAME = DumperOptions.ScalarStyle.PLAIN;
// numbers, booleans, should use implicit
private final static DumperOptions.ScalarStyle STYLE_SCALAR = DumperOptions.ScalarStyle.PLAIN;
// Strings quoted for fun
private final static DumperOptions.ScalarStyle STYLE_QUOTED = DumperOptions.ScalarStyle.DOUBLE_QUOTED;
// Strings in literal (block) style
private final static DumperOptions.ScalarStyle STYLE_LITERAL = DumperOptions.ScalarStyle.LITERAL;
// Which flow style to use for Base64? Maybe basic quoted?
private final static DumperOptions.ScalarStyle STYLE_BASE64 = DumperOptions.ScalarStyle.DOUBLE_QUOTED;
private final static DumperOptions.ScalarStyle STYLE_PLAIN = DumperOptions.ScalarStyle.PLAIN;
/*
/**********************************************************
/* Output state
/**********************************************************
*/
protected Emitter _emitter;
/**
* YAML supports native Object identifiers, so databinder may indicate
* need to output one.
*/
protected String _objectId;
/**
* YAML supports native Type identifiers, so databinder may indicate
* need to output one.
*/
protected String _typeId;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
public YAMLGenerator(IOContext ctxt, int jsonFeatures, int yamlFeatures,
ObjectCodec codec, Writer out,
org.yaml.snakeyaml.DumperOptions.Version version)
throws IOException
{
super(jsonFeatures, codec);
_ioContext = ctxt;
_formatFeatures = yamlFeatures;
_writer = out;
_outputOptions = buildDumperOptions(jsonFeatures, yamlFeatures, version);
_emitter = new Emitter(_writer, _outputOptions);
// should we start output now, or try to defer?
_emitter.emit(new StreamStartEvent(null, null));
Map<String,String> noTags = Collections.emptyMap();
boolean startMarker = Feature.WRITE_DOC_START_MARKER.enabledIn(yamlFeatures);
_emitter.emit(new DocumentStartEvent(null, null, startMarker,
version, // for 1.10 was: ((version == null) ? null : version.getArray()),
noTags));
}
protected DumperOptions buildDumperOptions(int jsonFeatures, int yamlFeatures, org.yaml.snakeyaml.DumperOptions.Version version)
{
DumperOptions opt = new DumperOptions();
// would we want canonical?
if (Feature.CANONICAL_OUTPUT.enabledIn(_formatFeatures)) {
opt.setCanonical(true);
} else {
opt.setCanonical(false);
// if not, MUST specify flow styles
opt.setDefaultFlowStyle(FlowStyle.BLOCK);
}
// [dataformat#35]: split-lines for text blocks?
opt.setSplitLines(Feature.SPLIT_LINES.enabledIn(_formatFeatures));
return opt;
}
/*
/**********************************************************
/* Versioned
/**********************************************************
*/
@Override
public Version version() {
return PackageVersion.VERSION;
}
/*
/**********************************************************
/* Overridden methods, configuration
/**********************************************************
*/
/**
* Not sure what to do here; could reset indentation to some value maybe?
*/
@Override
public YAMLGenerator useDefaultPrettyPrinter()
{
return this;
}
/**
* Not sure what to do here; will always indent, but uses
* YAML-specific settings etc.
*/
@Override
public YAMLGenerator setPrettyPrinter(PrettyPrinter pp) {
return this;
}
@Override
public Object getOutputTarget() {
return _writer;
}
/**
* SnakeYAML does not expose buffered content amount, so we can only return
* <code>-1</code> from here
*/
@Override
public int getOutputBuffered() {
return -1;
}
@Override
public int getFormatFeatures() {
return _formatFeatures;
}
@Override
public JsonGenerator overrideFormatFeatures(int values, int mask) {
_formatFeatures = (_formatFeatures & ~mask) | (values & mask);
return this;
}
@Override
public boolean canUseSchema(FormatSchema schema) {
return false;
}
@Override
public boolean canWriteFormattedNumbers() { return true; }
//@Override public void setSchema(FormatSchema schema)
/*
/**********************************************************
/* Extended API, configuration
/**********************************************************
*/
public YAMLGenerator enable(Feature f) {
_formatFeatures |= f.getMask();
return this;
}
public YAMLGenerator disable(Feature f) {
_formatFeatures &= ~f.getMask();
return this;
}
public final boolean isEnabled(Feature f) {
return (_formatFeatures & f.getMask()) != 0;
}
public YAMLGenerator configure(Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
/*
/**********************************************************************
/* Overridden methods; writing field names
/**********************************************************************
*/
/* And then methods overridden to make final, streamline some
* aspects...
*/
@Override
public final void writeFieldName(String name) throws IOException
{
if (_writeContext.writeFieldName(name) == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
_writeFieldName(name);
}
@Override
public final void writeFieldName(SerializableString name)
throws IOException
{
// Object is a value, need to verify it's allowed
if (_writeContext.writeFieldName(name.getValue()) == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
_writeFieldName(name.getValue());
}
@Override
public final void writeStringField(String fieldName, String value)
throws IOException
{
if (_writeContext.writeFieldName(fieldName) == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
_writeFieldName(fieldName);
writeString(value);
}
private final void _writeFieldName(String name)
throws IOException
{
_writeScalar(name, "string", STYLE_NAME);
}
/*
/**********************************************************
/* Public API: low-level I/O
/**********************************************************
*/
@Override
public final void flush() throws IOException
{
_writer.flush();
}
@Override
public void close() throws IOException
{
if (!isClosed()) {
_emitter.emit(new DocumentEndEvent(null, null, false));
_emitter.emit(new StreamEndEvent(null, null));
super.close();
_writer.close();
}
}
/*
/**********************************************************
/* Public API: structural output
/**********************************************************
*/
@Override
public final void writeStartArray() throws IOException
{
_verifyValueWrite("start an array");
_writeContext = _writeContext.createChildArrayContext();
DumperOptions.FlowStyle style = _outputOptions.getDefaultFlowStyle();
String yamlTag = _typeId;
boolean implicit = (yamlTag == null);
String anchor = _objectId;
if (anchor != null) {
_objectId = null;
}
_emitter.emit(new SequenceStartEvent(anchor, yamlTag,
implicit, null, null, style));
}
@Override
public final void writeEndArray() throws IOException
{
if (!_writeContext.inArray()) {
_reportError("Current context not Array but "+_writeContext.typeDesc());
}
// just to make sure we don't "leak" type ids
_typeId = null;
_writeContext = _writeContext.getParent();
_emitter.emit(new SequenceEndEvent(null, null));
}
@Override
public final void writeStartObject() throws IOException
{
_verifyValueWrite("start an object");
_writeContext = _writeContext.createChildObjectContext();
DumperOptions.FlowStyle style = _outputOptions.getDefaultFlowStyle();
String yamlTag = _typeId;
boolean implicit = (yamlTag == null);
String anchor = _objectId;
if (anchor != null) {
_objectId = null;
}
_emitter.emit(new MappingStartEvent(anchor, yamlTag,
implicit, null, null, style));
}
@Override
public final void writeEndObject() throws IOException
{
if (!_writeContext.inObject()) {
_reportError("Current context not Object but "+_writeContext.typeDesc());
}
// just to make sure we don't "leak" type ids
_typeId = null;
_writeContext = _writeContext.getParent();
_emitter.emit(new MappingEndEvent(null, null));
}
/*
/**********************************************************
/* Output method implementations, textual
/**********************************************************
*/
@Override
public void writeString(String text) throws IOException,JsonGenerationException
{
if (text == null) {
writeNull();
return;
}
_verifyValueWrite("write String value");
DumperOptions.ScalarStyle style = STYLE_QUOTED;
if (Feature.MINIMIZE_QUOTES.enabledIn(_formatFeatures) && !isBooleanContent(text)) {
// If this string could be interpreted as a number, it must be quoted.
if (Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS.enabledIn(_formatFeatures)
&& PLAIN_NUMBER_P.matcher(text).matches()) {
style = STYLE_QUOTED;
} else if (text.indexOf('\n') >= 0) {
style = STYLE_LITERAL;
} else {
style = STYLE_PLAIN;
}
}
_writeScalar(text, "string", style);
}
private boolean isBooleanContent(String text) {
return text.equals("true") || text.equals("false");
}
@Override
public void writeString(char[] text, int offset, int len) throws IOException
{
writeString(new String(text, offset, len));
}
@Override
public final void writeString(SerializableString sstr)
throws IOException
{
writeString(sstr.toString());
}
@Override
public void writeRawUTF8String(byte[] text, int offset, int len)
throws IOException
{
_reportUnsupportedOperation();
}
@Override
public final void writeUTF8String(byte[] text, int offset, int len)
throws IOException
{
writeString(new String(text, offset, len, "UTF-8"));
}
/*
/**********************************************************
/* Output method implementations, unprocessed ("raw")
/**********************************************************
*/
@Override
public void writeRaw(String text) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(String text, int offset, int len) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(char[] text, int offset, int len) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(char c) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRawValue(String text) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRawValue(String text, int offset, int len) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRawValue(char[] text, int offset, int len) throws IOException {
_reportUnsupportedOperation();
}
/*
/**********************************************************
/* Output method implementations, base64-encoded binary
/**********************************************************
*/
@Override
public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException
{
if (data == null) {
writeNull();
return;
}
_verifyValueWrite("write Binary value");
// ok, better just Base64 encode as a String...
if (offset > 0 || (offset+len) != data.length) {
data = Arrays.copyOfRange(data, offset, offset+len);
}
String encoded = b64variant.encode(data);
_writeScalar(encoded, "byte[]", STYLE_BASE64);
}
/*
/**********************************************************
/* Output method implementations, scalars
/**********************************************************
*/
@Override
public void writeBoolean(boolean state) throws IOException
{
_verifyValueWrite("write boolean value");
_writeScalar(state ? "true" : "false", "bool", STYLE_SCALAR);
}
@Override
public void writeNumber(int i) throws IOException
{
_verifyValueWrite("write number");
_writeScalar(String.valueOf(i), "int", STYLE_SCALAR);
}
@Override
public void writeNumber(long l) throws IOException
{
// First: maybe 32 bits is enough?
if (l <= MAX_INT_AS_LONG && l >= MIN_INT_AS_LONG) {
writeNumber((int) l);
return;
}
_verifyValueWrite("write number");
_writeScalar(String.valueOf(l), "long", STYLE_SCALAR);
}
@Override
public void writeNumber(BigInteger v) throws IOException
{
if (v == null) {
writeNull();
return;
}
_verifyValueWrite("write number");
_writeScalar(String.valueOf(v.toString()), "java.math.BigInteger", STYLE_SCALAR);
}
@Override
public void writeNumber(double d) throws IOException
{
_verifyValueWrite("write number");
_writeScalar(String.valueOf(d), "double", STYLE_SCALAR);
}
@Override
public void writeNumber(float f) throws IOException
{
_verifyValueWrite("write number");
_writeScalar(String.valueOf(f), "float", STYLE_SCALAR);
}
@Override
public void writeNumber(BigDecimal dec) throws IOException
{
if (dec == null) {
writeNull();
return;
}
_verifyValueWrite("write number");
String str = isEnabled(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN) ? dec.toPlainString() : dec.toString();
_writeScalar(str, "java.math.BigDecimal", STYLE_SCALAR);
}
@Override
public void writeNumber(String encodedValue) throws IOException,JsonGenerationException, UnsupportedOperationException
{
if (encodedValue == null) {
writeNull();
return;
}
_verifyValueWrite("write number");
_writeScalar(encodedValue, "number", STYLE_SCALAR);
}
@Override
public void writeNull() throws IOException
{
_verifyValueWrite("write null value");
// no real type for this, is there?
_writeScalar("null", "object", STYLE_SCALAR);
}
/*
/**********************************************************
/* Public API, write methods, Native Ids
/**********************************************************
*/
@Override
public boolean canWriteObjectId() {
// yes, YAML does support Native Type Ids!
// 10-Sep-2014, tatu: Except as per [#23] might not want to...
return Feature.USE_NATIVE_OBJECT_ID.enabledIn(_formatFeatures);
}
@Override
public boolean canWriteTypeId() {
// yes, YAML does support Native Type Ids!
// 10-Sep-2014, tatu: Except as per [#22] might not want to...
return Feature.USE_NATIVE_TYPE_ID.enabledIn(_formatFeatures);
}
@Override
public void writeTypeId(Object id)
throws IOException
{
// should we verify there's no preceding type id?
_typeId = String.valueOf(id);
}
@Override
public void writeObjectRef(Object id)
throws IOException
{
_verifyValueWrite("write Object reference");
AliasEvent evt = new AliasEvent(String.valueOf(id), null, null);
_emitter.emit(evt);
}
@Override
public void writeObjectId(Object id)
throws IOException
{
// should we verify there's no preceding id?
_objectId = String.valueOf(id);
}
/*
/**********************************************************
/* Implementations for methods from base class
/**********************************************************
*/
@Override
protected final void _verifyValueWrite(String typeMsg)
throws IOException
{
int status = _writeContext.writeValue();
if (status == JsonWriteContext.STATUS_EXPECT_NAME) {
_reportError("Can not "+typeMsg+", expecting field name");
}
}
@Override
protected void _releaseBuffers() {
// nothing special to do...
}
/*
/**********************************************************
/* Internal methods
/**********************************************************
*/
// Implicit means that (type) tags won't be shown, right?
private final static ImplicitTuple DEFAULT_IMPLICIT = new ImplicitTuple(true, true);
protected void _writeScalar(String value, String type, DumperOptions.ScalarStyle style) throws IOException
{
_emitter.emit(_scalarEvent(value, style));
}
protected ScalarEvent _scalarEvent(String value, DumperOptions.ScalarStyle style)
{
String yamlTag = _typeId;
if (yamlTag != null) {
_typeId = null;
}
String anchor = _objectId;
if (anchor != null) {
_objectId = null;
}
return new ScalarEvent(anchor, yamlTag, DEFAULT_IMPLICIT, value,
null, null, style);
}
}
|