pax_global_header00006660000000000000000000000064131474557060014526gustar00rootroot0000000000000052 comment=ddbc28e5ba75b6255c281319d8bfc1af5b5097d7 jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/000077500000000000000000000000001314745570600230345ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/.gitattributes000066400000000000000000000001371314745570600257300ustar00rootroot00000000000000# Do not merge `pom.xml` from older version, as it will typically conflict pom.xml merge=ours jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/.gitignore000066400000000000000000000002451314745570600250250ustar00rootroot00000000000000# use glob syntax. syntax: glob *.class *~ *.bak *.off *.old .DS_Store # building target # Eclipse .classpath .project .settings # IDEA *.iml *.ipr *.iws /target jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/.travis.yml000066400000000000000000000000441314745570600251430ustar00rootroot00000000000000language: java jdk: - oraclejdk7 jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/README.md000066400000000000000000000041221314745570600243120ustar00rootroot00000000000000# Overview This project contains [Jackson](http://wiki.fasterxml.com/JacksonHome) extension component for reading and writing [YAML](http://en.wikipedia.org/wiki/YAML) encoded data. [SnakeYAML](https://bitbucket.org/asomov/snakeyaml/) library is used for low-level YAML parsing. This project adds necessary abstractions on top to make things work with other Jackson functionality. Project is licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt). # Status [![Build Status](https://travis-ci.org/FasterXML/jackson-dataformat-yaml.svg?branch=master)](https://travis-ci.org/FasterXML/jackson-dataformat-yaml) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml/) [![Javadoc](https://javadoc-emblem.rhcloud.com/doc/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml/badge.svg)](http://www.javadoc.io/doc/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml) Module has been production ready since version 2.5. ## Maven dependency To use this extension on Maven-based projects, use following dependency: ```xml com.fasterxml.jackson.dataformat jackson-dataformat-yaml 2.8.3 ``` # Usage ## Simple usage Usage is as with basic `JsonFactory`; most commonly you will just construct a standard `ObjectMapper` with `com.fasterxml.jackson.dataformat.yaml.YAMLFactory`, like so: ```java ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); User user = mapper.readValue(yamlSource, User.class); ``` but you can also just use underlying `YAMLFactory` and parser it produces, for event-based processing: ```java YAMLFactory factory = new YAMLFactory(); JsonParser parser = factory.createJsonParser(yamlString); // don't be fooled by method name... while (parser.nextToken() != null) { // do something! } ``` # Documentation * [Wiki](../../wiki) contains links to Javadocs, external documentation jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/pom.xml000066400000000000000000000140261314745570600243540ustar00rootroot00000000000000 4.0.0 com.fasterxml.jackson jackson-parent 2.8 com.fasterxml.jackson.dataformat jackson-dataformat-yaml 2.8.10 bundle Jackson-dataformat-YAML Support for reading and writing YAML-encoded data via Jackson abstractions. https://github.com/FasterXML/jackson scm:git:git@github.com:FasterXML/jackson-dataformat-yaml.git scm:git:git@github.com:FasterXML/jackson-dataformat-yaml.git http://github.com/FasterXML/jackson-dataformat-yaml jackson-dataformat-yaml-2.8.10 2.8.10 com/fasterxml/jackson/dataformat/yaml ${project.groupId}.yaml 1.2.8 4.3.0 4.0.3 com.fasterxml.jackson.core jackson-core ${version.jackson.core} com.fasterxml.jackson.core jackson-databind ${version.jackson.core} provided org.yaml snakeyaml 1.17 com.fasterxml.jackson.core jackson-annotations test org.ops4j.pax.exam pax-exam-container-native ${pax.exam.version} test org.ops4j.pax.exam pax-exam-junit4 ${pax.exam.version} test org.ops4j.pax.exam pax-exam-link-mvn ${pax.exam.version} test org.ops4j.pax.url pax-url-aether 2.2.0 test org.apache.felix org.apache.felix.framework ${felix.version} test org.slf4j slf4j-log4j12 1.6.6 test com.google.code.maven-replacer-plugin replacer process-packageVersion generate-sources org.apache.maven.plugins maven-surefire-plugin com/fasterxml/jackson/dataformat/yaml/failing/*.java **/*Test.java **/Test*.java jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/profile-perf.sh000077500000000000000000000002211314745570600257600ustar00rootroot00000000000000#!/bin/sh java -Xmx64m -server \ -cp target/classes:target/test-classes:lib/\* \ -Xrunhprof:cpu=samples,depth=10,verbose=n,interval=2 \ $* jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/release-notes/000077500000000000000000000000001314745570600256025ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/release-notes/CREDITS000066400000000000000000000034531314745570600266270ustar00rootroot00000000000000Here are people who have contributed to development Jackson JSON process databind core component, version 2.x (version numbers in brackets indicate release in which the problem was fixed) (note: for older credits, check out release notes for 1.x versions) Tatu Saloranta, tatu.saloranta@iki.fi: author Shawn Smith: - Contributed [Issue-14]: Fix parsing of longs near MIN/MAX_INT, parsing of BigIntegers. (2.1.4) Łukasz Dywicki - Fixed #19: Change build to avoid OSGi dep to SnakeYAML (which is instead shaded in) (2.5.0) - Contributed #14: Fix parsing of longs near MIN/MAX_INT, parsing of BigIntegers. (2.1.4) Benson Margulies (benson-basis@github) - Fixed #27: OSGI bundle does not work due to shading (2.4.4) - Reported #30: `YamlFactory.writeValue(File, Object)` busted (2.4.5) - Contributed #50: Lack of SnakeYAML Resolver leaves some missing features (2.7.0) Ville Koskela (vjkoskela@github) - Requested #35: Add `YAMLGenerator.Feature.SPLIT_LINES` to allow controlling whether SnakeYAML splits longer text blocks with line breaks or not. (2.6.0) Geoff Bourne (itzg@github) - Contributed #38: Add MINIMIZE_QUOTES generator feature (2.7.0) Sebastian Herold (heroldus@github) - Reported #69: Problem to parse time values as string (2.7.7) James Baker (j-baker@github) - Reported, contributed fix for #70: UTF8Reader is unsafe if a Jackson-annotated class itself deserialises a Jackson-annotated class (2.7.8) Tanguy Leroux (tlrx@github) - Reported, contributed test, fix for #80: Fix UTF8Writer when used in same thread (2.7.9) Preston Gilchrist (prestongilchrist@github) - Contributed #65: Feature.MINIMIZE_QUOTES needs to write numbers as strings with quotes (2.8.2) Roland Huss (rhuss@github) - Reported #77, contributed fix: Boolean-like content of string must never be unquoted (2.8.4) jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/release-notes/VERSION000066400000000000000000000107121314745570600266530ustar00rootroot00000000000000Project: jackson-dataformat-yaml ------------------------------------------------------------------------ = Releases ------------------------------------------------------------------------ 2.8.10 (24-Aug-2017) 2.8.9 (12-Jun-2017) No changes since 2.8.8 2.8.8 (05-Apr-2017) #72: Multiple documents in a stream (requested by fabriziocucci@github, contributed by xiGUAwanOU@github) 2.8.7 (21-Feb-2017) 2.8.6 (12-Jan-2017) No changes since 2.8.5 2.8.5 (14-Nov-2016) - Update SnakeYAML dependency to 1.17 2.8.4 (14-Oct-2016) #77: Boolean-like content of string must never be unquoted (reported, contributed fix by Roland H) 2.8.3 (17-Sep-2016) No changes since 2.8.2 2.8.2 (30-Aug-2016) #65: Feature.MINIMIZE_QUOTES needs to write numbers as strings with quotes (contributed by Preston G) 2.8.1 (20-Jul-2016) No changes since 2.8.0. 2.8.0 (04-Jul-2016) #31: SnakeYAML is shaded and pulled in transitively #60: YAML serializer reports wrong exception (suggested by pmogren@github) 2.7.9 (not yet released) #80: Fix UTF8Writer when used in same thread (contributed by Tanguy L) 2.7.8 (26-Sep-2016) #70: `UTF8Reader` is unsafe if a Jackson-annotated class itself deserializes a Jackson-annotated class (reported by James B) 2.7.7 (27-Aug-2016) #69: Problem to parse time values as string (reported by Sebastian H) 2.7.6 (23-Jul-2016) 2.7.5 (11-Jun-2016) 2.7.4 (29-Apr-2016) No changes since 2.7.3 2.7.3 (16-Mar-2016) #59: Avoid exposing SnakeYAML exception types (wrap) 2.7.2 (27-Feb-2016) - Change build to produce JDK6-compatible jar, to allow use on JDK6 runtime 2.7.1 (02-Feb-2016) No changes since 2.7.0 2.7.0 (10-Jan-2016) #38: Add MINIMIZE_QUOTES generator feature (contributed by Geoff B, itzg@github) #48: null values aren't mapped to Jackson nulls (reported, contributed by Benson M) #50: Lack of SnakeYAML Resolver leaves some missing features (contributed by Benson M) 2.6.6 (05-Apr-2016) 2.6.5 (19-Jan-2016) 2.6.4 (07-Dec-2015) 2.6.3 (12-Oct-2015) 2.6.2 (15-Sep-2015) 2.6.1 (09-Aug-2015) No changes since 2.6.0. 2.6.0 (20-Jul-2015) #35: Add `YAMLGenerator.Feature.SPLIT_LINES` to allow controlling whether SnakeYAML splits longer text blocks with line breaks or not (requested by Ville K, vjkoskela@github) - Upgrade to SnakeYAML 1.15 2.5.3 (24-Apr-2015) 2.5.2 (29-Mar-2015) 2.5.1 (06-Feb-2015) No changes since 2.5.0 2.5.0 (01-Jan-2015) #19: Change build to avoid OSGi dep to SnakeYAML (which is instead shaded in) (Fixed by Łukasz D) #22: Add support for disabling use of YAML native Type Ids #23: Add support for disabling use of YAML native Type Ids - Added `YAMLMapper` for convenience 2.4.5 (13-Jan-2015) #30: `YamlFactory.writeValue(File, Object)` busted (reported by Benson M) 2.4.4 (24-Nov-2014) #27: OSGI bundle does not work due to shading (fix contributed by Benson M) 2.4.3 (04-Oct-2014) 2.4.2 (15-Aug-2014) 2.4.1 (17-Jun-2014) No changes since 2.4.0 2.4.0 (02-Jun-2014) #21: Improve handling of polymorphic types, native type ids (reported by Hal H) 2.3.3 (10-Apr-2014) 2.3.2 (01-Mar-2014) 2.3.1 (28-Dec-2013) No changes since 2.3.0. 2.3.0 (14-Nov-2013) #3: Support YAML-specific object ids ("anchors", "aliases"). #17: Support YAML-specific type ids ("tags") (requested by cemo@github) - Add support for `JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN` - Upgrade to SnakeYAML 1.12 2.2.2 (27-May-2013) No functional changes. 2.2.1 (03-May-2013) - Fixed problem with YamlFactory.copy() 2.2.0 (22-Apr-2013) New minor version; no functional changes. 2.1.3 (19-Jan-2013) - [Issue-10]: Avoid parsing scalars in non-plain flow styles (contributed by nkvoll@github) - [Issue-12]: Problems with 'YAMLFactory.createJsonGenerator(File)' 2.1.2 (04-Dec-2012) No functional changes. 2.1.1 (12-Nov-2012) No functional changes. 2.1.0 (08-Oct-2012) Another minor update on Jackson YAML format module Improvements: - [Issue-5]: Expose Aliases as JsonToken.STRING_VALUE tokens - [Issue-6]: Add a method in YAMLParser to detect Anchors: `getCurrentAnchor()` - [Issue-7]: Possible parsing problems with unquoted values with colons 2.0.5 (27-Jul-2012) - [Issue-4]: Regexp for detecting floating point numbers too permissive with dots (reported by Dan Sheehan) 2.0.4: skipped release (no changes) 2.0.3: skipped release (no changes) 2.0.2 (14-May-2012) Improvements: - 10-20% performance improvements based on profiling (most overhead in SnakeYaml, so limited possibilities) 2.0.0 (03-May-2012) Fixes: * [Issue-2] UUIDs not properly deserialized. jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/000077500000000000000000000000001314745570600236235ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/000077500000000000000000000000001314745570600245475ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/000077500000000000000000000000001314745570600254705ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/000077500000000000000000000000001314745570600262465ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/000077500000000000000000000000001314745570600302535ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/000077500000000000000000000000001314745570600317035ustar00rootroot00000000000000dataformat/000077500000000000000000000000001314745570600337465ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jacksonyaml/000077500000000000000000000000001314745570600347105ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformatJacksonYAMLParseException.java000066400000000000000000000006251314745570600425030ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; /** * @since 2.8 */ public class JacksonYAMLParseException extends JsonParseException { private static final long serialVersionUID = 1L; public JacksonYAMLParseException(JsonParser p, String msg, Exception e) { super(p, msg, e); } } PackageVersion.java.in000066400000000000000000000011071314745570600410600ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yamlpackage @package@; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.core.Versioned; import com.fasterxml.jackson.core.util.VersionUtil; /** * Automatically generated from PackageVersion.java.in during * packageVersion-generate execution of maven-replacer-plugin in * pom.xml. */ public final class PackageVersion implements Versioned { public final static Version VERSION = VersionUtil.parseVersion( "@projectversion@", "@projectgroupid@", "@projectartifactid@"); @Override public Version version() { return VERSION; } } UTF8Reader.java000066400000000000000000000414351314745570600374330ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.io.*; import java.lang.ref.SoftReference; /** * Optimized Reader that reads UTF-8 encoded content from an input stream. * In addition to doing (hopefully) optimal conversion, it can also take * array of "pre-read" (leftover) bytes; this is necessary when preliminary * stream/reader is trying to figure out underlying character encoding. */ public final class UTF8Reader extends Reader { private final static int DEFAULT_BUFFER_SIZE = 8000; /** * This ThreadLocal contains a {@link java.lang.ref.SoftRerefence} * to a byte array used for holding content to decode */ final protected static ThreadLocal> _bufferRecycler = new ThreadLocal>(); protected final byte[][] _bufferHolder; private InputStream _inputSource; private final boolean _autoClose; protected byte[] _inputBuffer; /** * Pointer to the next available byte (if any), iff less than * mByteBufferEnd */ protected int _inputPtr; /** * Pointed to the end marker, that is, position one after the last * valid available byte. */ protected int _inputEnd; /** * Decoded first character of a surrogate pair, if one needs to be buffered */ protected int _surrogate = -1; /** * Total read character count; used for error reporting purposes */ int _charCount = 0; /** * Total read byte count; used for error reporting purposes */ int _byteCount = 0; /* /********************************************************************** /* Life-cycle /********************************************************************** */ public UTF8Reader(InputStream in, boolean autoClose) { super((in == null) ? new Object() : in); _inputSource = in; _bufferHolder = _findBufferHolder(); byte[] buffer = _bufferHolder[0]; if (buffer == null) { buffer = new byte[DEFAULT_BUFFER_SIZE]; } else { _bufferHolder[0] = null; } _inputBuffer = buffer; _inputPtr = 0; _inputEnd = 0; _autoClose = autoClose; } public UTF8Reader(byte[] buf, int ptr, int len, boolean autoClose) { super(new Object()); _inputSource = null; _inputBuffer = buf; _inputPtr = ptr; _inputEnd = ptr+len; _autoClose = autoClose; _bufferHolder = null; } private static byte[][] _findBufferHolder() { byte[][] bufs = null; SoftReference ref = _bufferRecycler.get(); if (ref != null) { bufs = ref.get(); } if (bufs == null) { bufs = new byte[1][]; _bufferRecycler.set(new SoftReference(bufs)); } return bufs; } /* /********************************************************************** /* Reader API /********************************************************************** */ @Override public void close() throws IOException { InputStream in = _inputSource; if (in != null) { _inputSource = null; if (_autoClose) { in.close(); } } freeBuffers(); } private char[] _tmpBuffer = null; /** * Although this method is implemented by the base class, AND it should * never be called by Woodstox code, let's still implement it bit more * efficiently just in case */ @Override public int read() throws IOException { if (_tmpBuffer == null) { _tmpBuffer = new char[1]; } if (read(_tmpBuffer, 0, 1) < 1) { return -1; } return _tmpBuffer[0]; } @Override public int read(char[] cbuf) throws IOException { return read(cbuf, 0, cbuf.length); } @Override public int read(char[] cbuf, int start, int len) throws IOException { // Already EOF? if (_inputBuffer == null) { return -1; } len += start; int outPtr = start; // Ok, first; do we have a surrogate from last round? if (_surrogate >= 0) { cbuf[outPtr++] = (char) _surrogate; _surrogate = -1; // No need to load more, already got one char } else { /* To prevent unnecessary blocking (esp. with network streams), * we'll only require decoding of a single char */ int left = (_inputEnd - _inputPtr); /* So; only need to load more if we can't provide at least * one more character. We need not do thorough check here, * but let's check the common cases here: either completely * empty buffer (left == 0), or one with less than max. byte * count for a single char, and starting of a multi-byte * encoding (this leaves possibility of a 2/3-byte char * that is still fully accessible... but that can be checked * by the load method) */ if (left < 4) { // Need to load more? if (left < 1 || _inputBuffer[_inputPtr] < 0) { if (!loadMore(left)) { // (legal) EOF? return -1; } } } } final byte[] buf = _inputBuffer; int inPtr = _inputPtr; final int inBufLen = _inputEnd; main_loop: while (outPtr < len) { // At this point we have at least one byte available int c = (int) buf[inPtr++]; // Let's first do the quickie loop for common case; 7-bit ASCII if (c >= 0) { // ASCII? can probably loop, then cbuf[outPtr++] = (char) c; // ok since MSB is never on // Ok, how many such chars could we safely process without overruns? // (will combine 2 in-loop comparisons into just one) int outMax = (len - outPtr); // max output int inMax = (inBufLen - inPtr); // max input int inEnd = inPtr + ((inMax < outMax) ? inMax : outMax); ascii_loop: while (true) { if (inPtr >= inEnd) { break main_loop; } c = buf[inPtr++]; if (c < 0) { // or multi-byte break ascii_loop; } cbuf[outPtr++] = (char) c; } } int needed; // Ok; if we end here, we got multi-byte combination if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) c = (c & 0x1F); needed = 1; } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) c = (c & 0x0F); needed = 2; } else if ((c & 0xF8) == 0xF0) { // 4 bytes; double-char BS, with surrogates and all... c = (c & 0x0F); needed = 3; } else { reportInvalidInitial(c & 0xFF, outPtr-start); // never gets here... needed = 1; } /* Do we have enough bytes? If not, let's just push back the * byte and leave, since we have already gotten at least one * char decoded. This way we will only block (with read from * input stream) when absolutely necessary. */ if ((inBufLen - inPtr) < needed) { --inPtr; break main_loop; } int d = (int) buf[inPtr++]; if ((d & 0xC0) != 0x080) { reportInvalidOther(d & 0xFF, outPtr-start); } c = (c << 6) | (d & 0x3F); if (needed > 1) { // needed == 1 means 2 bytes total d = buf[inPtr++]; // 3rd byte if ((d & 0xC0) != 0x080) { reportInvalidOther(d & 0xFF, outPtr-start); } c = (c << 6) | (d & 0x3F); if (needed > 2) { // 4 bytes? (need surrogates) d = buf[inPtr++]; if ((d & 0xC0) != 0x080) { reportInvalidOther(d & 0xFF, outPtr-start); } c = (c << 6) | (d & 0x3F); /* Ugh. Need to mess with surrogates. Ok; let's inline them * there, then, if there's room: if only room for one, * need to save the surrogate for the rainy day... */ c -= 0x10000; // to normalize it starting with 0x0 cbuf[outPtr++] = (char) (0xD800 + (c >> 10)); // hmmh. can this ever be 0? (not legal, at least?) c = (0xDC00 | (c & 0x03FF)); // Room for second part? if (outPtr >= len) { // nope _surrogate = c; break main_loop; } // sure, let's fall back to normal processing: } // Otherwise, should we check that 3-byte chars are // legal ones (should not expand to surrogates? // For now, let's not... /* else { if (c >= 0xD800 && c < 0xE000) { reportInvalid(c, outPtr-start, "(a surrogate character) "); } } */ } cbuf[outPtr++] = (char) c; if (inPtr >= inBufLen) { break main_loop; } } _inputPtr = inPtr; len = outPtr - start; _charCount += len; return len; } /* /********************************************************************** /* Internal/package methods: /********************************************************************** */ protected final InputStream getStream() { return _inputSource; } /** * Method for reading as many bytes from the underlying stream as possible * (that fit in the buffer), to the beginning of the buffer. * * @return Number of bytes read, if any; -1 for end-of-input. */ protected final int readBytes() throws IOException { _inputPtr = 0; _inputEnd = 0; if (_inputSource != null) { int count = _inputSource.read(_inputBuffer, 0, _inputBuffer.length); if (count > 0) { _inputEnd = count; } return count; } return -1; } /** * Method for reading as many bytes from the underlying stream as possible * (that fit in the buffer considering offset), to the specified offset. * * @return Number of bytes read, if any; -1 to indicate none available * (that is, end of input) */ protected final int readBytesAt(int offset) throws IOException { // shouldn't modify mBytePtr, assumed to be 'offset' if (_inputSource != null) { int count = _inputSource.read(_inputBuffer, offset, _inputBuffer.length - offset); if (count > 0) { _inputEnd += count; } return count; } return -1; } /** * This method should be called along with (or instead of) normal * close. After calling this method, no further reads should be tried. * Method will try to recycle read buffers (if any). */ public final void freeBuffers() { if (_bufferHolder != null) { byte[] buf = _inputBuffer; if (buf != null) { _inputBuffer = null; _bufferHolder[0] = buf; } } } /* /********************************************************************** /* Internal methods /********************************************************************** */ private void reportInvalidInitial(int mask, int offset) throws IOException { // input (byte) ptr has been advanced by one, by now: int bytePos = _byteCount + _inputPtr - 1; int charPos = _charCount + offset + 1; throw new CharConversionException("Invalid UTF-8 start byte 0x"+Integer.toHexString(mask) +" (at char #"+charPos+", byte #"+bytePos+")"); } private void reportInvalidOther(int mask, int offset) throws IOException { int bytePos = _byteCount + _inputPtr - 1; int charPos = _charCount + offset; throw new CharConversionException("Invalid UTF-8 middle byte 0x"+Integer.toHexString(mask) +" (at char #"+charPos+", byte #"+bytePos+")"); } private void reportUnexpectedEOF(int gotBytes, int needed) throws IOException { int bytePos = _byteCount + gotBytes; int charPos = _charCount; throw new CharConversionException("Unexpected EOF in the middle of a multi-byte char: got " +gotBytes+", needed "+needed +", at char #"+charPos+", byte #"+bytePos+")"); } /* private void reportInvalid(int value, int offset, String msg) throws IOException { int bytePos = _byteCount + _inputPtr - 1; int charPos = _charCount + offset; throw new CharConversionException("Invalid UTF-8 character 0x"+Integer.toHexString(value)+msg +" at char #"+charPos+", byte #"+bytePos+")"); } */ /** * @param available Number of "unused" bytes in the input buffer * * @return True, if enough bytes were read to allow decoding of at least * one full character; false if EOF was encountered instead. */ private boolean loadMore(int available) throws IOException { _byteCount += (_inputEnd - available); // Bytes that need to be moved to the beginning of buffer? if (available > 0) { if (_inputPtr > 0) { // sanity check: can only move if we "own" buffers if (_bufferHolder == null) { throw new IllegalStateException("Internal error: need to move partially decoded character; buffer not modifiable"); } for (int i = 0; i < available; ++i) { _inputBuffer[i] = _inputBuffer[_inputPtr+i]; } _inputPtr = 0; _inputEnd = available; } } else { /* Ok; here we can actually reasonably expect an EOF, * so let's do a separate read right away: */ int count = readBytes(); if (count < 1) { freeBuffers(); // to help GC? if (count < 0) { // -1 return false; } // 0 count is no good; let's err out reportStrangeStream(); } } /* We now have at least one byte... and that allows us to * calculate exactly how many bytes we need! */ @SuppressWarnings("cast") int c = (int) _inputBuffer[_inputPtr]; if (c >= 0) { // single byte (ascii) char... cool, can return return true; } // Ok, a multi-byte char, let's check how many bytes we'll need: int needed; if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) needed = 2; } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) needed = 3; } else if ((c & 0xF8) == 0xF0) { // 4 bytes; double-char BS, with surrogates and all... needed = 4; } else { reportInvalidInitial(c & 0xFF, 0); // never gets here... but compiler whines without this: needed = 1; } /* And then we'll just need to load up to that many bytes; * if an EOF is hit, that'll be an error. But we need not do * actual decoding here, just load enough bytes. */ while ((_inputPtr + needed) > _inputEnd) { int count = readBytesAt(_inputEnd); if (count < 1) { if (count < 0) { // -1, EOF... no good! freeBuffers(); reportUnexpectedEOF(_inputEnd, needed); } // 0 count is no good; let's err out reportStrangeStream(); } } return true; } protected void reportBounds(char[] cbuf, int start, int len) throws IOException { throw new ArrayIndexOutOfBoundsException("read(buf,"+start+","+len+"), cbuf["+cbuf.length+"]"); } protected void reportStrangeStream() throws IOException { throw new IOException("Strange I/O stream, returned 0 bytes on read"); } } UTF8Writer.java000066400000000000000000000331171314745570600375030ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.io.*; import java.lang.ref.SoftReference; public final class UTF8Writer extends Writer { final static int SURR1_FIRST = 0xD800; final static int SURR1_LAST = 0xDBFF; final static int SURR2_FIRST = 0xDC00; final static int SURR2_LAST = 0xDFFF; private final static int DEFAULT_BUFFER_SIZE = 8000; /** * This ThreadLocal contains a {@link java.lang.ref.SoftRerefence} * to a byte array used for holding content to decode */ final protected static ThreadLocal> _bufferRecycler = new ThreadLocal>(); protected final byte[][] _bufferHolder; private OutputStream _out; private byte[] _outBuffer; private final int _outBufferEnd; private int _outPtr; /** * When outputting chars from BMP, surrogate pairs need to be coalesced. * To do this, both pairs must be known first; and since it is possible * pairs may be split, we need temporary storage for the first half */ int _surrogate = 0; public UTF8Writer(OutputStream out) { _out = out; _bufferHolder = _findBufferHolder(); byte[] buffer = _bufferHolder[0]; if (buffer == null) { buffer = new byte[DEFAULT_BUFFER_SIZE]; } else { _bufferHolder[0] = null; } _outBuffer = buffer; /* Max. expansion for a single char (in unmodified UTF-8) is * 4 bytes (or 3 depending on how you view it -- 4 when recombining * surrogate pairs) */ _outBufferEnd = _outBuffer.length - 4; _outPtr = 0; } private static byte[][] _findBufferHolder() { byte[][] bufs = null; SoftReference ref = _bufferRecycler.get(); if (ref != null) { bufs = ref.get(); } if (bufs == null) { bufs = new byte[1][]; _bufferRecycler.set(new SoftReference(bufs)); } return bufs; } @Override public Writer append(char c) throws IOException { write(c); return this; } @Override public void close() throws IOException { if (_out != null) { if (_outPtr > 0) { _out.write(_outBuffer, 0, _outPtr); _outPtr = 0; } OutputStream out = _out; _out = null; if (_bufferHolder != null) { byte[] buf = _outBuffer; if (buf != null) { _outBuffer = null; _bufferHolder[0] = buf; } } out.close(); /* Let's 'flush' orphan surrogate, no matter what; but only * after cleanly closing everything else. */ int code = _surrogate; _surrogate = 0; if (code > 0) { throwIllegal(code); } } } @Override public void flush() throws IOException { if (_out != null) { if (_outPtr > 0) { _out.write(_outBuffer, 0, _outPtr); _outPtr = 0; } _out.flush(); } } @Override public void write(char[] cbuf) throws IOException { write(cbuf, 0, cbuf.length); } @Override public void write(char[] cbuf, int off, int len) throws IOException { if (len < 2) { if (len == 1) { write(cbuf[off]); } return; } // First: do we have a leftover surrogate to deal with? if (_surrogate > 0) { char second = cbuf[off++]; --len; write(convertSurrogate(second)); // will have at least one more char } int outPtr = _outPtr; byte[] outBuf = _outBuffer; int outBufLast = _outBufferEnd; // has 4 'spare' bytes // All right; can just loop it nice and easy now: len += off; // len will now be the end of input buffer output_loop: for (; off < len; ) { /* First, let's ensure we can output at least 4 bytes * (longest UTF-8 encoded codepoint): */ if (outPtr >= outBufLast) { _out.write(outBuf, 0, outPtr); outPtr = 0; } int c = cbuf[off++]; // And then see if we have an Ascii char: if (c < 0x80) { // If so, can do a tight inner loop: outBuf[outPtr++] = (byte)c; // Let's calc how many ascii chars we can copy at most: int maxInCount = (len - off); int maxOutCount = (outBufLast - outPtr); if (maxInCount > maxOutCount) { maxInCount = maxOutCount; } maxInCount += off; ascii_loop: while (true) { if (off >= maxInCount) { // done with max. ascii seq continue output_loop; } c = cbuf[off++]; if (c >= 0x80) { break ascii_loop; } outBuf[outPtr++] = (byte) c; } } // Nope, multi-byte: if (c < 0x800) { // 2-byte outBuf[outPtr++] = (byte) (0xc0 | (c >> 6)); outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); } else { // 3 or 4 bytes // Surrogates? if (c < SURR1_FIRST || c > SURR2_LAST) { outBuf[outPtr++] = (byte) (0xe0 | (c >> 12)); outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); continue; } // Yup, a surrogate: if (c > SURR1_LAST) { // must be from first range _outPtr = outPtr; throwIllegal(c); } _surrogate = c; // and if so, followed by another from next range if (off >= len) { // unless we hit the end? break; } c = convertSurrogate(cbuf[off++]); if (c > 0x10FFFF) { // illegal in JSON as well as in XML _outPtr = outPtr; throwIllegal(c); } outBuf[outPtr++] = (byte) (0xf0 | (c >> 18)); outBuf[outPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f)); outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); } } _outPtr = outPtr; } @Override public void write(int c) throws IOException { // First; do we have a left over surrogate? if (_surrogate > 0) { c = convertSurrogate(c); // If not, do we start with a surrogate? } else if (c >= SURR1_FIRST && c <= SURR2_LAST) { // Illegal to get second part without first: if (c > SURR1_LAST) { throwIllegal(c); } // First part just needs to be held for now _surrogate = c; return; } if (_outPtr >= _outBufferEnd) { // let's require enough room, first _out.write(_outBuffer, 0, _outPtr); _outPtr = 0; } if (c < 0x80) { // ascii _outBuffer[_outPtr++] = (byte) c; } else { int ptr = _outPtr; if (c < 0x800) { // 2-byte _outBuffer[ptr++] = (byte) (0xc0 | (c >> 6)); _outBuffer[ptr++] = (byte) (0x80 | (c & 0x3f)); } else if (c <= 0xFFFF) { // 3 bytes _outBuffer[ptr++] = (byte) (0xe0 | (c >> 12)); _outBuffer[ptr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); _outBuffer[ptr++] = (byte) (0x80 | (c & 0x3f)); } else { // 4 bytes if (c > 0x10FFFF) { // illegal throwIllegal(c); } _outBuffer[ptr++] = (byte) (0xf0 | (c >> 18)); _outBuffer[ptr++] = (byte) (0x80 | ((c >> 12) & 0x3f)); _outBuffer[ptr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); _outBuffer[ptr++] = (byte) (0x80 | (c & 0x3f)); } _outPtr = ptr; } } @Override public void write(String str) throws IOException { write(str, 0, str.length()); } @Override public void write(String str, int off, int len) throws IOException { if (len < 2) { if (len == 1) { write(str.charAt(off)); } return; } // First: do we have a leftover surrogate to deal with? if (_surrogate > 0) { char second = str.charAt(off++); --len; write(convertSurrogate(second)); // will have at least one more char (case of 1 char was checked earlier on) } int outPtr = _outPtr; byte[] outBuf = _outBuffer; int outBufLast = _outBufferEnd; // has 4 'spare' bytes // All right; can just loop it nice and easy now: len += off; // len will now be the end of input buffer output_loop: for (; off < len; ) { /* First, let's ensure we can output at least 4 bytes * (longest UTF-8 encoded codepoint): */ if (outPtr >= outBufLast) { _out.write(outBuf, 0, outPtr); outPtr = 0; } int c = str.charAt(off++); // And then see if we have an Ascii char: if (c < 0x80) { // If so, can do a tight inner loop: outBuf[outPtr++] = (byte)c; // Let's calc how many ascii chars we can copy at most: int maxInCount = (len - off); int maxOutCount = (outBufLast - outPtr); if (maxInCount > maxOutCount) { maxInCount = maxOutCount; } maxInCount += off; ascii_loop: while (true) { if (off >= maxInCount) { // done with max. ascii seq continue output_loop; } c = str.charAt(off++); if (c >= 0x80) { break ascii_loop; } outBuf[outPtr++] = (byte) c; } } // Nope, multi-byte: if (c < 0x800) { // 2-byte outBuf[outPtr++] = (byte) (0xc0 | (c >> 6)); outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); } else { // 3 or 4 bytes // Surrogates? if (c < SURR1_FIRST || c > SURR2_LAST) { outBuf[outPtr++] = (byte) (0xe0 | (c >> 12)); outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); continue; } // Yup, a surrogate: if (c > SURR1_LAST) { // must be from first range _outPtr = outPtr; throwIllegal(c); } _surrogate = c; // and if so, followed by another from next range if (off >= len) { // unless we hit the end? break; } c = convertSurrogate(str.charAt(off++)); if (c > 0x10FFFF) { // illegal, as per RFC 4627 _outPtr = outPtr; throwIllegal(c); } outBuf[outPtr++] = (byte) (0xf0 | (c >> 18)); outBuf[outPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f)); outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); } } _outPtr = outPtr; } /* /********************************************************** /* Internal methods /********************************************************** */ /** * Method called to calculate UTF codepoint, from a surrogate pair. */ private int convertSurrogate(int secondPart) throws IOException { int firstPart = _surrogate; _surrogate = 0; // Ok, then, is the second part valid? if (secondPart < SURR2_FIRST || secondPart > SURR2_LAST) { throw new IOException("Broken surrogate pair: first char 0x"+Integer.toHexString(firstPart)+", second 0x"+Integer.toHexString(secondPart)+"; illegal combination"); } return 0x10000 + ((firstPart - SURR1_FIRST) << 10) + (secondPart - SURR2_FIRST); } private void throwIllegal(int code) throws IOException { if (code > 0x10FFFF) { // over max? throw new IOException("Illegal character point (0x"+Integer.toHexString(code)+") to output; max is 0x10FFFF as per RFC 4627"); } if (code >= SURR1_FIRST) { if (code <= SURR1_LAST) { // Unmatched first part (closing without second part?) throw new IOException("Unmatched first part of surrogate pair (0x"+Integer.toHexString(code)+")"); } throw new IOException("Unmatched second part of surrogate pair (0x"+Integer.toHexString(code)+")"); } // should we ever get this? throw new IOException("Illegal character point (0x"+Integer.toHexString(code)+") to output"); } } YAMLFactory.java000066400000000000000000000405131314745570600376500ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.io.*; import java.net.URL; import java.nio.charset.Charset; import org.yaml.snakeyaml.DumperOptions; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.format.InputAccessor; import com.fasterxml.jackson.core.format.MatchStrength; import com.fasterxml.jackson.core.io.IOContext; @SuppressWarnings("resource") public class YAMLFactory extends JsonFactory { private static final long serialVersionUID = 1L; /** * Name used to identify YAML format. * (and returned by {@link #getFormatName()} */ public final static String FORMAT_NAME_YAML = "YAML"; /** * Bitfield (set of flags) of all parser features that are enabled * by default. */ protected final static int DEFAULT_YAML_PARSER_FEATURE_FLAGS = YAMLParser.Feature.collectDefaults(); /** * Bitfield (set of flags) of all generator features that are enabled * by default. */ protected final static int DEFAULT_YAML_GENERATOR_FEATURE_FLAGS = YAMLGenerator.Feature.collectDefaults(); private final static byte UTF8_BOM_1 = (byte) 0xEF; private final static byte UTF8_BOM_2 = (byte) 0xBB; private final static byte UTF8_BOM_3 = (byte) 0xBF; /* /********************************************************************** /* Configuration /********************************************************************** */ protected int _yamlParserFeatures = DEFAULT_YAML_PARSER_FEATURE_FLAGS; protected int _yamlGeneratorFeatures = DEFAULT_YAML_GENERATOR_FEATURE_FLAGS; /* /********************************************************************** /* Factory construction, configuration /********************************************************************** */ protected DumperOptions.Version _version; /** * Default constructor used to create factory instances. * Creation of a factory instance is a light-weight operation, * but it is still a good idea to reuse limited number of * factory instances (and quite often just a single instance): * factories are used as context for storing some reused * processing objects (such as symbol tables parsers use) * and this reuse only works within context of a single * factory instance. */ public YAMLFactory() { this(null); } public YAMLFactory(ObjectCodec oc) { super(oc); _yamlParserFeatures = DEFAULT_YAML_PARSER_FEATURE_FLAGS; _yamlGeneratorFeatures = DEFAULT_YAML_GENERATOR_FEATURE_FLAGS; /* 26-Jul-2013, tatu: Seems like we should force output as 1.1 but * that adds version declaration which looks ugly... */ //_version = DumperOptions.Version.V1_1; _version = null; } /** * @since 2.2.1 */ public YAMLFactory(YAMLFactory src, ObjectCodec oc) { super(src, oc); _version = src._version; _yamlParserFeatures = src._yamlParserFeatures; _yamlGeneratorFeatures = src._yamlGeneratorFeatures; } @Override public YAMLFactory copy() { _checkInvalidCopy(YAMLFactory.class); return new YAMLFactory(this, null); } /* /********************************************************** /* Serializable overrides /********************************************************** */ /** * Method that we need to override to actually make restoration go * through constructors etc. * Also: must be overridden by sub-classes as well. */ @Override protected Object readResolve() { return new YAMLFactory(this, _objectCodec); } /* /********************************************************** /* Versioned /********************************************************** */ @Override public Version version() { return PackageVersion.VERSION; } /* /********************************************************** /* Capability introspection /********************************************************** */ // No, we can't make use of char[] optimizations @Override public boolean canUseCharArrays() { return false; } // Add these in 2.7: /* @Override public Class getFormatReadFeatureType() { return YAMLParser.Feature.class; } @Override public Class getFormatWriteFeatureType() { return YAMLGenerator.Feature.class; } */ /* /********************************************************** /* Format detection functionality /********************************************************** */ @Override public String getFormatName() { return FORMAT_NAME_YAML; } /** * Sub-classes need to override this method (as of 1.8) */ @Override public MatchStrength hasFormat(InputAccessor acc) throws IOException { /* Actually quite possible to do, thanks to (optional) "---" * indicator we may be getting... */ if (!acc.hasMoreBytes()) { return MatchStrength.INCONCLUSIVE; } byte b = acc.nextByte(); // Very first thing, a UTF-8 BOM? if (b == UTF8_BOM_1) { // yes, looks like UTF-8 BOM if (!acc.hasMoreBytes()) { return MatchStrength.INCONCLUSIVE; } if (acc.nextByte() != UTF8_BOM_2) { return MatchStrength.NO_MATCH; } if (!acc.hasMoreBytes()) { return MatchStrength.INCONCLUSIVE; } if (acc.nextByte() != UTF8_BOM_3) { return MatchStrength.NO_MATCH; } if (!acc.hasMoreBytes()) { return MatchStrength.INCONCLUSIVE; } b = acc.nextByte(); } // as far as I know, leading space is NOT allowed before "---" marker? if (b == '-' && (acc.hasMoreBytes() && acc.nextByte() == '-') && (acc.hasMoreBytes() && acc.nextByte() == '-')) { return MatchStrength.FULL_MATCH; } return MatchStrength.INCONCLUSIVE; } /* /********************************************************** /* Configuration, parser settings /********************************************************** */ /** * Method for enabling or disabling specified parser feature * (check {@link YAMLParser.Feature} for list of features) */ public final YAMLFactory configure(YAMLParser.Feature f, boolean state) { if (state) { enable(f); } else { disable(f); } return this; } /** * Method for enabling specified parser feature * (check {@link YAMLParser.Feature} for list of features) */ public YAMLFactory enable(YAMLParser.Feature f) { _yamlParserFeatures |= f.getMask(); return this; } /** * Method for disabling specified parser features * (check {@link YAMLParser.Feature} for list of features) */ public YAMLFactory disable(YAMLParser.Feature f) { _yamlParserFeatures &= ~f.getMask(); return this; } /** * Checked whether specified parser feature is enabled. */ public final boolean isEnabled(YAMLParser.Feature f) { return (_yamlParserFeatures & f.getMask()) != 0; } /* /********************************************************** /* Configuration, generator settings /********************************************************** */ /** * Method for enabling or disabling specified generator feature * (check {@link YAMLGenerator.Feature} for list of features) */ public final YAMLFactory configure(YAMLGenerator.Feature f, boolean state) { if (state) { enable(f); } else { disable(f); } return this; } /** * Method for enabling specified generator features * (check {@link YAMLGenerator.Feature} for list of features) */ public YAMLFactory enable(YAMLGenerator.Feature f) { _yamlGeneratorFeatures |= f.getMask(); return this; } /** * Method for disabling specified generator feature * (check {@link YAMLGenerator.Feature} for list of features) */ public YAMLFactory disable(YAMLGenerator.Feature f) { _yamlGeneratorFeatures &= ~f.getMask(); return this; } /** * Check whether specified generator feature is enabled. */ public final boolean isEnabled(YAMLGenerator.Feature f) { return (_yamlGeneratorFeatures & f.getMask()) != 0; } /* /********************************************************** /* Overridden parser factory methods (for 2.1) /********************************************************** */ @Override public YAMLParser createParser(String content) throws IOException { return createParser(new StringReader(content)); } @Override public YAMLParser createParser(File f) throws IOException { IOContext ctxt = _createContext(f, true); return _createParser(_decorate(new FileInputStream(f), ctxt), ctxt); } @Override public YAMLParser createParser(URL url) throws IOException { IOContext ctxt = _createContext(url, true); return _createParser(_decorate(_optimizedStreamFromURL(url), ctxt), ctxt); } @Override public YAMLParser createParser(InputStream in) throws IOException { IOContext ctxt = _createContext(in, false); return _createParser(_decorate(in, ctxt), ctxt); } @Override public YAMLParser createParser(Reader r) throws IOException { IOContext ctxt = _createContext(r, false); return _createParser(_decorate(r, ctxt), ctxt); } @Override // since 2.4 public YAMLParser createParser(char[] data) throws IOException { return createParser(new CharArrayReader(data, 0, data.length)); } @Override // since 2.4 public YAMLParser createParser(char[] data, int offset, int len) throws IOException { return createParser(new CharArrayReader(data, offset, len)); } @Override public YAMLParser createParser(byte[] data) throws IOException { IOContext ctxt = _createContext(data, true); // [JACKSON-512]: allow wrapping with InputDecorator if (_inputDecorator != null) { InputStream in = _inputDecorator.decorate(ctxt, data, 0, data.length); if (in != null) { return _createParser(in, ctxt); } } return _createParser(data, 0, data.length, ctxt); } @Override public YAMLParser createParser(byte[] data, int offset, int len) throws IOException { IOContext ctxt = _createContext(data, true); // [JACKSON-512]: allow wrapping with InputDecorator if (_inputDecorator != null) { InputStream in = _inputDecorator.decorate(ctxt, data, offset, len); if (in != null) { return _createParser(in, ctxt); } } return _createParser(data, offset, len, ctxt); } /* /********************************************************** /* Overridden generator factory methods (2.1) /********************************************************** */ @Override public YAMLGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException { // false -> we won't manage the stream unless explicitly directed to IOContext ctxt = _createContext(out, false); ctxt.setEncoding(enc); return _createGenerator(_createWriter(_decorate(out, ctxt), enc, ctxt), ctxt); } @Override public YAMLGenerator createGenerator(OutputStream out) throws IOException { // false -> we won't manage the stream unless explicitly directed to IOContext ctxt = _createContext(out, false); return _createGenerator(_createWriter(_decorate(out, ctxt), JsonEncoding.UTF8, ctxt), ctxt); } @Override public YAMLGenerator createGenerator(Writer out) throws IOException { IOContext ctxt = _createContext(out, false); return _createGenerator(_decorate(out, ctxt), ctxt); } @Override public JsonGenerator createGenerator(File f, JsonEncoding enc) throws IOException { OutputStream out = new FileOutputStream(f); // true -> yes, we have to manage the stream since we created it IOContext ctxt = _createContext(f, true); ctxt.setEncoding(enc); return _createGenerator(_createWriter(_decorate(out, ctxt), enc, ctxt), ctxt); } /* /****************************************************** /* Overridden internal factory methods /****************************************************** */ //protected IOContext _createContext(Object srcRef, boolean resourceManaged) @Override protected YAMLParser _createParser(InputStream in, IOContext ctxt) throws IOException { return new YAMLParser(ctxt, _getBufferRecycler(), _parserFeatures, _yamlParserFeatures, _objectCodec, _createReader(in, null, ctxt)); } @Override protected YAMLParser _createParser(Reader r, IOContext ctxt) throws IOException { return new YAMLParser(ctxt, _getBufferRecycler(), _parserFeatures, _yamlParserFeatures, _objectCodec, r); } // since 2.4 @Override protected YAMLParser _createParser(char[] data, int offset, int len, IOContext ctxt, boolean recyclable) throws IOException { return new YAMLParser(ctxt, _getBufferRecycler(), _parserFeatures, _yamlParserFeatures, _objectCodec, new CharArrayReader(data, offset, len)); } @Override protected YAMLParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException { return new YAMLParser(ctxt, _getBufferRecycler(), _parserFeatures, _yamlParserFeatures, _objectCodec, _createReader(data, offset, len, null, ctxt)); } @Override protected YAMLGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException { int feats = _yamlGeneratorFeatures; YAMLGenerator gen = new YAMLGenerator(ctxt, _generatorFeatures, feats, _objectCodec, out, _version); // any other initializations? No? return gen; } @Override protected YAMLGenerator _createUTF8Generator(OutputStream out, IOContext ctxt) throws IOException { // should never get called; ensure throw new IllegalStateException(); } @Override protected Writer _createWriter(OutputStream out, JsonEncoding enc, IOContext ctxt) throws IOException { if (enc == JsonEncoding.UTF8) { return new UTF8Writer(out); } return new OutputStreamWriter(out, enc.getJavaName()); } /* /********************************************************** /* Internal methods /********************************************************** */ protected final Charset UTF8 = Charset.forName("UTF-8"); protected Reader _createReader(InputStream in, JsonEncoding enc, IOContext ctxt) throws IOException { if (enc == null) { enc = JsonEncoding.UTF8; } // default to UTF-8 if encoding missing if (enc == JsonEncoding.UTF8) { boolean autoClose = ctxt.isResourceManaged() || isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE); return new UTF8Reader(in, autoClose); // return new InputStreamReader(in, UTF8); } return new InputStreamReader(in, enc.getJavaName()); } protected Reader _createReader(byte[] data, int offset, int len, JsonEncoding enc, IOContext ctxt) throws IOException { if (enc == null) { enc = JsonEncoding.UTF8; } // default to UTF-8 if encoding missing if (enc == null || enc == JsonEncoding.UTF8) { return new UTF8Reader(data, offset, len, true); } ByteArrayInputStream in = new ByteArrayInputStream(data, offset, len); return new InputStreamReader(in, enc.getJavaName()); } } YAMLGenerator.java000066400000000000000000000561041314745570600401720ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yamlpackage 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.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. *

* 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). *

* Minimized quote usage makes for more human readable output; however, content is * limited to printable characters according to the rules of * literal block style. * * @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. *

* Minimized quote usage makes for more human readable output; however, content is * limited to printable characters according to the rules of * literal block style. * * @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 Character STYLE_NAME = null; // numbers, booleans, should use implicit private final static Character STYLE_SCALAR = null; // Strings quoted for fun private final static Character STYLE_QUOTED = Character.valueOf('"'); // Strings in literal (block) style private final static Character STYLE_LITERAL = Character.valueOf('|'); // Which flow style to use for Base64? Maybe basic quoted? private final static Character STYLE_BASE64 = Character.valueOf('"'); private final static Character STYLE_PLAIN = null; /* /********************************************************** /* 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 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 * -1 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(); Boolean style = _outputOptions.getDefaultFlowStyle().getStyleBoolean(); 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(); Boolean style = _outputOptions.getDefaultFlowStyle().getStyleBoolean(); 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"); Character 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, Character style) throws IOException { _emitter.emit(_scalarEvent(value, style)); } protected ScalarEvent _scalarEvent(String value, Character 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); } } YAMLMapper.java000066400000000000000000000042211314745570600374610ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import com.fasterxml.jackson.databind.ObjectMapper; //import com.fasterxml.jackson.databind.ObjectMapper; /** * Convenience version of {@link ObjectMapper} which is configured * with {@link com.fasterxml.jackson.dataformat.yaml.YAMLFactory}. */ public class YAMLMapper extends ObjectMapper { private static final long serialVersionUID = 1L; public YAMLMapper() { this(new YAMLFactory()); } public YAMLMapper(YAMLFactory f) { super(f); } /** * @since 2.5 */ public YAMLMapper(YAMLMapper base) { super(base); } /** * @since 2.5 */ @Override public YAMLMapper copy() { _checkInvalidCopy(YAMLMapper.class); return new YAMLMapper(this); } /* /********************************************************************** /* Configuration /********************************************************************** */ public YAMLMapper configure(YAMLGenerator.Feature f, boolean state) { return state ? enable(f) : disable(f); } public YAMLMapper configure(YAMLParser.Feature f, boolean state) { return state ? enable(f) : disable(f); } public YAMLMapper enable(YAMLGenerator.Feature f) { ((YAMLFactory)_jsonFactory).enable(f); return this; } public YAMLMapper enable(YAMLParser.Feature f) { ((YAMLFactory)_jsonFactory).enable(f); return this; } public YAMLMapper disable(YAMLGenerator.Feature f) { ((YAMLFactory)_jsonFactory).disable(f); return this; } public YAMLMapper disable(YAMLParser.Feature f) { ((YAMLFactory)_jsonFactory).disable(f); return this; } /* /********************************************************************** /* Additional typed accessors /********************************************************************** */ /** * Overridden with more specific type, since factory we have * is always of type {@link YAMLFactory} */ @Override public final YAMLFactory getFactory() { return (YAMLFactory) _jsonFactory; } } YAMLParser.java000066400000000000000000000667101314745570600375040ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.regex.Pattern; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.events.*; import org.yaml.snakeyaml.nodes.NodeId; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.parser.ParserImpl; import org.yaml.snakeyaml.reader.StreamReader; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.base.ParserBase; import com.fasterxml.jackson.core.io.IOContext; import com.fasterxml.jackson.core.util.BufferRecycler; import com.fasterxml.jackson.core.util.ByteArrayBuilder; import org.yaml.snakeyaml.resolver.Resolver; /** * {@link JsonParser} implementation used to expose YAML documents * in form that allows other Jackson functionality to process YAML content, * such as binding POJOs to and from it, and building tree representations. */ public class YAMLParser extends ParserBase { /** * Enumeration that defines all togglable features for YAML parsers. */ public enum Feature // implements FormatFeature // in 2.7 { ; final boolean _defaultState; 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; } } // note: does NOT include '0', handled separately // private final static Pattern PATTERN_INT = Pattern.compile("-?[1-9][0-9]*"); /** * We will use pattern that is bit stricter than YAML definition, * but we will still allow things like extra '_' in there. */ private final static Pattern PATTERN_FLOAT = Pattern.compile( "[-+]?([0-9][0-9_]*)?\\.[0-9]*([eE][-+][0-9]+)?"); /* /********************************************************************** /* Configuration /********************************************************************** */ /** * Codec used for data binding when (if) requested. */ protected ObjectCodec _objectCodec; protected int _formatFeatures; /* /********************************************************************** /* Input sources /********************************************************************** */ /** * Need to keep track of underlying {@link Reader} to be able to * auto-close it (if required to) */ protected final Reader _reader; protected final ParserImpl _yamlParser; protected final Resolver _yamlResolver = new Resolver(); /* /********************************************************************** /* State /********************************************************************** */ /** * Keep track of the last event read, to get access to Location info */ protected Event _lastEvent; /** * We need to keep track of text values. */ protected String _textValue; /** * Let's also have a local copy of the current field name */ protected String _currentFieldName; /** * Flag that is set when current token was derived from an Alias * (reference to another value's anchor) * * @since 2.1 */ protected boolean _currentIsAlias; /** * Anchor for the value that parser currently points to: in case of * structured types, value whose first token current token is. */ protected String _currentAnchor; /* /********************************************************************** /* Life-cycle /********************************************************************** */ public YAMLParser(IOContext ctxt, BufferRecycler br, int parserFeatures, int formatFeatures, ObjectCodec codec, Reader reader) { super(ctxt, parserFeatures); _objectCodec = codec; _formatFeatures = formatFeatures; _reader = reader; _yamlParser = new ParserImpl(new StreamReader(reader)); } @Override public ObjectCodec getCodec() { return _objectCodec; } @Override public void setCodec(ObjectCodec c) { _objectCodec = c; } /* /********************************************************** /* Extended YAML-specific API /********************************************************** */ /** * Method that can be used to check whether current token was * created from YAML Alias token (reference to an anchor). * * @since 2.1 */ public boolean isCurrentAlias() { return _currentIsAlias; } /** * Method that can be used to check if the current token has an * associated anchor (id to reference via Alias) * * @deprecated Since 2.3 (was added in 2.1) -- use {@link #getObjectId} instead */ @Deprecated public String getCurrentAnchor() { return _currentAnchor; } /* /********************************************************** /* Versioned /********************************************************** */ @Override public Version version() { return PackageVersion.VERSION; } /* /********************************************************** /* ParserBase method impls /********************************************************** */ @Override protected void _closeInput() throws IOException { _reader.close(); } /* /********************************************************** /* FormatFeature support /********************************************************** */ @Override public int getFormatFeatures() { return _formatFeatures; } @Override public JsonParser overrideFormatFeatures(int values, int mask) { _formatFeatures = (_formatFeatures & ~mask) | (values & mask); return this; } /* /*************************************************** /* Public API, configuration /*************************************************** */ /** * Method for enabling specified CSV feature * (check {@link Feature} for list of features) */ public JsonParser enable(YAMLParser.Feature f) { _formatFeatures |= f.getMask(); return this; } /** * Method for disabling specified CSV feature * (check {@link Feature} for list of features) */ public JsonParser disable(YAMLParser.Feature f) { _formatFeatures &= ~f.getMask(); return this; } /** * Method for enabling or disabling specified CSV feature * (check {@link Feature} for list of features) */ public JsonParser configure(YAMLParser.Feature f, boolean state) { if (state) { enable(f); } else { disable(f); } return this; } /** * Method for checking whether specified CSV {@link Feature} * is enabled. */ public boolean isEnabled(YAMLParser.Feature f) { return (_formatFeatures & f.getMask()) != 0; } // @Override public CsvSchema getSchema() /* /********************************************************** /* Location info /********************************************************** */ @Override public JsonLocation getTokenLocation() { if (_lastEvent == null) { return JsonLocation.NA; } return _locationFor(_lastEvent.getStartMark()); } @Override public JsonLocation getCurrentLocation() { // can assume we are at the end of token now... if (_lastEvent == null) { return JsonLocation.NA; } return _locationFor(_lastEvent.getEndMark()); } protected JsonLocation _locationFor(Mark m) { if (m == null) { return new JsonLocation(_ioContext.getSourceReference(), -1, -1, -1); } return new JsonLocation(_ioContext.getSourceReference(), -1, m.getLine() + 1, // from 0- to 1-based m.getColumn() + 1); // ditto } // Note: SHOULD override 'getTokenLineNr', 'getTokenColumnNr', but those are final in 2.0 /* /********************************************************** /* Parsing /********************************************************** */ @SuppressWarnings("deprecation") @Override public JsonToken nextToken() throws IOException { _currentIsAlias = false; _binaryValue = null; _currentAnchor = null; if (_closed) { return null; } while (true) { Event evt; try { evt = _yamlParser.getEvent(); } catch (org.yaml.snakeyaml.error.YAMLException e) { if (e instanceof org.yaml.snakeyaml.error.MarkedYAMLException) { throw com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.MarkedYAMLException.from (this, (org.yaml.snakeyaml.error.MarkedYAMLException) e); } throw com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.YAMLException.from(this, e); } // is null ok? Assume it is, for now, consider to be same as end-of-doc if (evt == null) { return (_currToken = null); } _lastEvent = evt; /* One complication: field names are only inferred from the * fact that we are in Object context... */ if (_parsingContext.inObject() && _currToken != JsonToken.FIELD_NAME) { if (!evt.is(Event.ID.Scalar)) { // end is fine if (evt.is(Event.ID.MappingEnd)) { if (!_parsingContext.inObject()) { // sanity check is optional, but let's do it for now _reportMismatchedEndMarker('}', ']'); } _parsingContext = _parsingContext.getParent(); return (_currToken = JsonToken.END_OBJECT); } _reportError("Expected a field name (Scalar value in YAML), got this instead: "+evt); } ScalarEvent scalar = (ScalarEvent) evt; String name = scalar.getValue(); _currentFieldName = name; _parsingContext.setCurrentName(name); _currentAnchor = scalar.getAnchor(); return (_currToken = JsonToken.FIELD_NAME); } // Ugh. Why not expose id, to be able to Switch? // scalar values are probably the commonest: if (evt.is(Event.ID.Scalar)) { JsonToken t = _decodeScalar((ScalarEvent) evt); _currToken = t; return t; } // followed by maps, then arrays if (evt.is(Event.ID.MappingStart)) { Mark m = evt.getStartMark(); MappingStartEvent map = (MappingStartEvent) evt; _currentAnchor = map.getAnchor(); _parsingContext = _parsingContext.createChildObjectContext(m.getLine(), m.getColumn()); return (_currToken = JsonToken.START_OBJECT); } if (evt.is(Event.ID.MappingEnd)) { // actually error; can not have map-end here _reportError("Not expecting END_OBJECT but a value"); } if (evt.is(Event.ID.SequenceStart)) { Mark m = evt.getStartMark(); _currentAnchor = ((NodeEvent)evt).getAnchor(); _parsingContext = _parsingContext.createChildArrayContext(m.getLine(), m.getColumn()); return (_currToken = JsonToken.START_ARRAY); } if (evt.is(Event.ID.SequenceEnd)) { if (!_parsingContext.inArray()) { // sanity check is optional, but let's do it for now _reportMismatchedEndMarker(']', '}'); } _parsingContext = _parsingContext.getParent(); return (_currToken = JsonToken.END_ARRAY); } // after this, less common tokens: if (evt.is(Event.ID.DocumentEnd)) { // [dataformat-yaml#72]: logical end of doc; fine. Two choices; either skip, // or return null as marker (but do NOT close). Earlier returned `null`, but // to allow multi-document reading should actually just skip. // return (_currToken = null); continue; } if (evt.is(Event.ID.DocumentStart)) { // DocumentStartEvent dd = (DocumentStartEvent) evt; // does this matter? Shouldn't, should it? continue; } if (evt.is(Event.ID.Alias)) { AliasEvent alias = (AliasEvent) evt; _currentIsAlias = true; _textValue = alias.getAnchor(); // for now, nothing to do: in future, maybe try to expose as ObjectIds? return (_currToken = JsonToken.VALUE_STRING); } if (evt.is(Event.ID.StreamEnd)) { // end-of-input; force closure close(); return (_currToken = null); } if (evt.is(Event.ID.StreamStart)) { // useless, skip continue; } } } protected JsonToken _decodeScalar(ScalarEvent scalar) { String value = scalar.getValue(); _textValue = value; // we may get an explicit tag, if so, use for corroborating... String typeTag = scalar.getTag(); final int len = value.length(); if (typeTag == null || typeTag.equals("!")) { // no, implicit Tag nodeTag = _yamlResolver.resolve(NodeId.scalar, value, scalar.getImplicit().canOmitTagInPlainScalar()); if (nodeTag == Tag.STR) { return JsonToken.VALUE_STRING; } if (nodeTag == Tag.INT) { return _decodeNumberScalar(value, len); } if (nodeTag == Tag.FLOAT) { _numTypesValid = 0; return JsonToken.VALUE_NUMBER_FLOAT; } if (nodeTag == Tag.BOOL) { Boolean B = _matchYAMLBoolean(value, len); if (B != null) { return B ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE; } } else if (nodeTag == Tag.NULL) { return JsonToken.VALUE_NULL; } else { // what to do with timestamp and binary and merge etc. return JsonToken.VALUE_STRING; } } else { // yes, got type tag if (typeTag.startsWith("tag:yaml.org,2002:")) { typeTag = typeTag.substring("tag:yaml.org,2002:".length()); if (typeTag.contains(",")) { typeTag = typeTag.split(",")[0]; } } // canonical values by YAML are actually 'y' and 'n'; but plenty more unofficial: if ("bool".equals(typeTag)) { // must be "true" or "false" Boolean B = _matchYAMLBoolean(value, len); if (B != null) { return B ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE; } } else if ("int".equals(typeTag)) { return _decodeNumberScalar(value, len); } else if ("float".equals(typeTag)) { _numTypesValid = 0; return JsonToken.VALUE_NUMBER_FLOAT; } else if ("null".equals(typeTag)) { return JsonToken.VALUE_NULL; } } // any way to figure out actual type? No? return JsonToken.VALUE_STRING; } protected Boolean _matchYAMLBoolean(String value, int len) { switch (len) { case 1: switch (value.charAt(0)) { case 'y': case 'Y': return Boolean.TRUE; case 'n': case 'N': return Boolean.FALSE; } break; case 2: if ("no".equalsIgnoreCase(value)) return Boolean.FALSE; if ("on".equalsIgnoreCase(value)) return Boolean.TRUE; break; case 3: if ("yes".equalsIgnoreCase(value)) return Boolean.TRUE; if ("off".equalsIgnoreCase(value)) return Boolean.FALSE; break; case 4: if ("true".equalsIgnoreCase(value)) return Boolean.TRUE; break; case 5: if ("false".equalsIgnoreCase(value)) return Boolean.FALSE; break; } return null; } protected JsonToken _decodeNumberScalar(String value, final int len) { if ("0".equals(value)) { // special case for regexp (can't take minus etc) _numberNegative = false; _numberInt = 0; _numTypesValid = NR_INT; return JsonToken.VALUE_NUMBER_INT; } /* 05-May-2012, tatu: Turns out this is a hot spot; so let's write it * out and avoid regexp overhead... */ //if (PATTERN_INT.matcher(value).matches()) { int i; if (value.charAt(0) == '-') { _numberNegative = true; i = 1; if (len == 1) { return null; } } else { _numberNegative = false; i = 0; } while (true) { int c = value.charAt(i); if (c > '9' || c < '0') { break; } if (++i == len) { _numTypesValid = 0; return JsonToken.VALUE_NUMBER_INT; } } if (PATTERN_FLOAT.matcher(value).matches()) { _numTypesValid = 0; return JsonToken.VALUE_NUMBER_FLOAT; } // 25-Aug-2016, tatu: If we can't actually match it to valid number, // consider String; better than claiming there's not toekn return JsonToken.VALUE_STRING; } /* /********************************************************** /* String value handling /********************************************************** */ // For now we do not store char[] representation... @Override public boolean hasTextCharacters() { return false; } @Override public String getText() throws IOException { if (_currToken == JsonToken.VALUE_STRING) { return _textValue; } if (_currToken == JsonToken.FIELD_NAME) { return _currentFieldName; } if (_currToken != null) { if (_currToken.isScalarValue()) { return _textValue; } return _currToken.asString(); } return null; } @Override public String getCurrentName() throws IOException { if (_currToken == JsonToken.FIELD_NAME) { return _currentFieldName; } return super.getCurrentName(); } @Override public char[] getTextCharacters() throws IOException { String text = getText(); return (text == null) ? null : text.toCharArray(); } @Override public int getTextLength() throws IOException { String text = getText(); return (text == null) ? 0 : text.length(); } @Override public int getTextOffset() throws IOException { return 0; } @Override // since 2.8 public int getText(Writer writer) throws IOException { String str = getText(); if (str == null) { return 0; } writer.write(str); return str.length(); } /* /********************************************************************** /* Binary (base64) /********************************************************************** */ @Override public Object getEmbeddedObject() throws IOException { return null; } // TODO: can remove from 2.9 or so (base impl added in 2.8) @SuppressWarnings("resource") @Override public byte[] getBinaryValue(Base64Variant variant) throws IOException { if (_binaryValue == null) { if (_currToken != JsonToken.VALUE_STRING) { _reportError("Current token ("+_currToken+") not VALUE_STRING, can not access as binary"); } ByteArrayBuilder builder = _getByteArrayBuilder(); _decodeBase64(getText(), builder, variant); _binaryValue = builder.toByteArray(); } return _binaryValue; } /* /********************************************************************** /* Number accessor overrides /********************************************************************** */ @Override protected void _parseNumericValue(int expType) throws IOException { // Int or float? if (_currToken == JsonToken.VALUE_NUMBER_INT) { int len = _textValue.length(); if (_numberNegative) { len--; } if (len <= 9) { // definitely fits in int _numberInt = Integer.parseInt(_textValue); _numTypesValid = NR_INT; return; } if (len <= 18) { // definitely fits AND is easy to parse using 2 int parse calls long l = Long.parseLong(_textValue); // [JACKSON-230] Could still fit in int, need to check if (len == 10) { if (_numberNegative) { if (l >= Integer.MIN_VALUE) { _numberInt = (int) l; _numTypesValid = NR_INT; return; } } else { if (l <= Integer.MAX_VALUE) { _numberInt = (int) l; _numTypesValid = NR_INT; return; } } } _numberLong = l; _numTypesValid = NR_LONG; return; } // !!! TODO: implement proper bounds checks; now we'll just use BigInteger for convenience try { BigInteger n = new BigInteger(_textValue); // Could still fit in a long, need to check if (len == 19 && n.bitLength() <= 63) { _numberLong = n.longValue(); _numTypesValid = NR_LONG; return; } _numberBigInt = n; _numTypesValid = NR_BIGINT; return; } catch (NumberFormatException nex) { // Can this ever occur? Due to overflow, maybe? _wrapError("Malformed numeric value '"+_textValue+"'", nex); } } if (_currToken == JsonToken.VALUE_NUMBER_FLOAT) { // related to [Issue-4]: strip out optional underscores, if any: String str = _cleanYamlDouble(_textValue); try { if (expType == NR_BIGDECIMAL) { _numberBigDecimal = new BigDecimal(str); _numTypesValid = NR_BIGDECIMAL; } else { // Otherwise double has to do _numberDouble = Double.parseDouble(str); _numTypesValid = NR_DOUBLE; } } catch (NumberFormatException nex) { // Can this ever occur? Due to overflow, maybe? _wrapError("Malformed numeric value '"+str+"'", nex); } return; } _reportError("Current token ("+_currToken+") not numeric, can not use numeric value accessors"); } @Override protected int _parseIntValue() throws IOException { if (_currToken == JsonToken.VALUE_NUMBER_INT) { int len = _textValue.length(); if (_numberNegative) { len--; } if (len <= 9) { // definitely fits in int _numTypesValid = NR_INT; return (_numberInt = Integer.parseInt(_textValue)); } } _parseNumericValue(NR_INT); if ((_numTypesValid & NR_INT) == 0) { convertNumberToInt(); } return _numberInt; } /* /********************************************************************** /* Native id (type id) access /********************************************************************** */ @Override public boolean canReadObjectId() { // yup return true; } @Override public boolean canReadTypeId() { return true; // yes, YAML got 'em } @Override public String getObjectId() throws IOException, JsonGenerationException { return _currentAnchor; } @Override public String getTypeId() throws IOException, JsonGenerationException { String tag; if (_lastEvent instanceof CollectionStartEvent) { tag = ((CollectionStartEvent) _lastEvent).getTag(); } else if (_lastEvent instanceof ScalarEvent) { tag = ((ScalarEvent) _lastEvent).getTag(); } else { return null; } if (tag != null) { /* 04-Aug-2013, tatu: Looks like YAML parser's expose these in... * somewhat exotic ways sometimes. So let's prepare to peel off * some wrappings: */ while (tag.startsWith("!")) { tag = tag.substring(1); } return tag; } return null; } /* /********************************************************************** /* Internal methods /********************************************************************** */ /** * Helper method used to clean up YAML floating-point value so it can be parsed * using standard JDK classes. * Currently this just means stripping out optional underscores. */ private String _cleanYamlDouble(String str) { final int len = str.length(); int ix = str.indexOf('_'); if (ix < 0 || len == 0) { return str; } StringBuilder sb = new StringBuilder(len); // first: do we have a leading plus sign to skip? int i = (str.charAt(0) == '+') ? 1 : 0; for (; i < len; ++i) { char c = str.charAt(i); if (c != '_') { sb.append(c); } } return sb.toString(); } } snakeyaml/000077500000000000000000000000001314745570600366745ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yamlerror/000077500000000000000000000000001314745570600400255ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yaml/snakeyamlMark.java000066400000000000000000000021051314745570600415600ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yaml/snakeyaml/errorpackage com.fasterxml.jackson.dataformat.yaml.snakeyaml.error; /** * Placeholder for shaded org.yaml.snakeyaml.error.Mark * * @since 2.8 (as non-shaded); earlier shaded in * * @deprecated Should use basic {@link com.fasterxml.jackson.core.JsonLocation} instead */ @Deprecated // since 2.8 public class Mark { protected final org.yaml.snakeyaml.error.Mark _source; protected Mark(org.yaml.snakeyaml.error.Mark src) { _source = src; } public static Mark from(org.yaml.snakeyaml.error.Mark src) { return (src == null) ? null : new Mark(src); } public String getName() { return _source.getName(); } public String get_snippet() { return _source.get_snippet(); } public String get_snippet(int indent, int max_length) { return _source.get_snippet(indent, max_length); } public int getColumn() { return _source.getColumn(); } public int getLine() { return _source.getLine(); } public int getIndex() { return _source.getIndex(); } } MarkedYAMLException.java000066400000000000000000000023621314745570600444400ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yaml/snakeyaml/errorpackage com.fasterxml.jackson.dataformat.yaml.snakeyaml.error; import com.fasterxml.jackson.core.JsonParser; /** * Replacement for formerly shaded exception type from SnakeYAML; included * in 2.8 solely for backwards compatibility: new code that relies on Jackson 2.8 * and alter should NOT use this type but only base type {@link YAMLException}. * * @deprecated Since 2.8 */ @Deprecated public class MarkedYAMLException extends YAMLException { private static final long serialVersionUID = 1L; protected final org.yaml.snakeyaml.error.MarkedYAMLException _source; protected MarkedYAMLException(JsonParser p, org.yaml.snakeyaml.error.MarkedYAMLException src) { super(p, src); _source = src; } public static MarkedYAMLException from(JsonParser p, org.yaml.snakeyaml.error.MarkedYAMLException src) { return new MarkedYAMLException(p, src); } public String getContext() { return _source.getContext(); } public Mark getContextMark() { return Mark.from(_source.getContextMark()); } public String getProblem() { return _source.getProblem(); } public Mark getProblemMark() { return Mark.from(_source.getProblemMark()); } } YAMLException.java000066400000000000000000000015711314745570600433150ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yaml/snakeyaml/errorpackage com.fasterxml.jackson.dataformat.yaml.snakeyaml.error; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.dataformat.yaml.JacksonYAMLParseException; /** * Replacement for formerly shaded exception type from SnakeYAML; included * in 2.8 solely for backwards compatibility: new code that relies on Jackson 2.8 * and alter should NOT use this type but only base type {@link YAMLException}. * * @deprecated Since 2.8 */ @Deprecated public class YAMLException extends JacksonYAMLParseException { private static final long serialVersionUID = 1L; public YAMLException(JsonParser p, org.yaml.snakeyaml.error.YAMLException src) { super(p, src.getMessage(), src); } public static YAMLException from(JsonParser p, org.yaml.snakeyaml.error.YAMLException src) { return new YAMLException(p, src); } } package-info.java000066400000000000000000000007651314745570600432240ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/java/com/fasterxml/jackson/dataformat/yaml/snakeyaml/error/** Replacement for shaded-in package that Jackson versions up to and including 2.7 had; with 2.8 (and later 2.x) we unfortunately fake to sort of fake formerly relocated types. This is needed to improve backwards compatibility with frameworks like DropWizard.

New code based on Jackson 2.8 and later should NOT use types in this package but instead rely on {@link com.fasterxml.jackson.dataformat.yaml.JacksonYAMLParseException} */ package com.fasterxml.jackson.dataformat.yaml.snakeyaml.error; jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/resources/000077500000000000000000000000001314745570600265615ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/resources/META-INF/000077500000000000000000000000001314745570600277215ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/resources/META-INF/LICENSE000066400000000000000000000004751314745570600307340ustar00rootroot00000000000000This copy of Jackson JSON processor YAML module is licensed under the Apache (Software) License, version 2.0 ("the License"). See the License for details about distribution rights, and the specific rights regarding derivate works. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/resources/META-INF/NOTICE000066400000000000000000000014711314745570600306300ustar00rootroot00000000000000# Jackson JSON processor Jackson is a high-performance, Free/Open Source JSON processing library. It was originally written by Tatu Saloranta (tatu.saloranta@iki.fi), and has been in development since 2007. It is currently developed by a community of developers, as well as supported commercially by FasterXML.com. ## Licensing Jackson core and extension components may be licensed under different licenses. To find the details that apply to this artifact see the accompanying LICENSE file. For more information, including possible other licensing options, contact FasterXML.com (http://fasterxml.com). ## Credits A list of contributors may be found from CREDITS file, which is included in some artifacts (usually source distributions); but is always available from the source code management (SCM) system project uses. jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/resources/META-INF/services/000077500000000000000000000000001314745570600315445ustar00rootroot00000000000000com.fasterxml.jackson.core.JsonFactory000066400000000000000000000000621314745570600410060ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/main/resources/META-INF/servicescom.fasterxml.jackson.dataformat.yaml.YAMLFactory jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/000077500000000000000000000000001314745570600246025ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/000077500000000000000000000000001314745570600255235ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/000077500000000000000000000000001314745570600263015ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/000077500000000000000000000000001314745570600303065ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/000077500000000000000000000000001314745570600317365ustar00rootroot00000000000000dataformat/000077500000000000000000000000001314745570600340015ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jacksonyaml/000077500000000000000000000000001314745570600347435ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformatDatabindAdvancedTest.java000066400000000000000000000125751314745570600416140ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; public class DatabindAdvancedTest extends ModuleTestBase { enum Size { SMALL, LARGE; } static class MediaItem { private MediaContent _content; private List _images; public MediaItem() { } public MediaItem(MediaContent c) { _content = c; } public void addPhoto(Image p) { if (_images == null) { _images = new ArrayList(); } _images.add(p); } public List getImages() { return _images; } public void setImages(List p) { _images = p; } public MediaContent getContent() { return _content; } public void setContent(MediaContent c) { _content = c; } } static class MediaContent { public enum Player { JAVA, FLASH; } private Player _player; private String _uri; private String _title; private int _width; private int _height; private String _format; private long _duration; private long _size; private int _bitrate; private List _persons; private String _copyright; public MediaContent() { } protected MediaContent(MediaContent src) { _player = src._player; _uri = src._uri; _title = src._title; _width = src._width; _height = src._height; _format = src._format; _duration = src._duration; _size = src._size; _bitrate = src._bitrate; _persons = src._persons; _copyright = src._copyright; } public void addPerson(String p) { if (_persons == null) { _persons = new ArrayList(); } _persons.add(p); } public Player getPlayer() { return _player; } public String getUri() { return _uri; } public String getTitle() { return _title; } public int getWidth() { return _width; } public int getHeight() { return _height; } public String getFormat() { return _format; } public long getDuration() { return _duration; } public long getSize() { return _size; } public int getBitrate() { return _bitrate; } public List getPersons() { return _persons; } public String getCopyright() { return _copyright; } public void setPlayer(Player p) { _player = p; } public void setUri(String u) { _uri = u; } public void setTitle(String t) { _title = t; } public void setWidth(int w) { _width = w; } public void setHeight(int h) { _height = h; } public void setFormat(String f) { _format = f; } public void setDuration(long d) { _duration = d; } public void setSize(long s) { _size = s; } public void setBitrate(int b) { _bitrate = b; } public void setPersons(List p) { _persons = p; } public void setCopyright(String c) { _copyright = c; } } static class Image { private String _uri; private String _title; private int _width; private int _height; private Size _size; public Image() {} public Image(String uri, String title, int w, int h, Size s) { _uri = uri; _title = title; _width = w; _height = h; _size = s; } public String getUri() { return _uri; } public String getTitle() { return _title; } public int getWidth() { return _width; } public int getHeight() { return _height; } public Size getSize() { return _size; } public void setUri(String u) { _uri = u; } public void setTitle(String t) { _title = t; } public void setWidth(int w) { _width = w; } public void setHeight(int h) { _height = h; } public void setSize(Size s) { _size = s; } } /* /********************************************************** /* Test methods /********************************************************** */ public void testBasic() throws Exception { ObjectMapper mapper = mapperForYAML(); String YAML = "---\n" +"content:\n" +" uri: 'http://javaone.com/keynote.mpg'\n" +" title: 'Javaone Keynote'\n" +" width: 640\n" +" height: 480\n" +" format: 'video/mpg4'\n" +" duration: 18000000\n" +" size: 58982400\n" +" bitrate: 262144\n" +" persons:\n" +" - 'Bill Gates'\n" +" - 'Steve Jobs'\n" +" player: 'JAVA'\n" +" copyright: 'None'\n" +"images:\n" +"- uri: 'http://javaone.com/keynote_large.jpg'\n" +" title: 'Javaone Keynote'\n" +" width: 1024\n" +" height: 768\n" +" size: 'LARGE'\n" +"- uri: 'http://javaone.com/keynote_small.jpg'\n" +" title: 'Javaone Keynote'\n" +" width: 320\n" +" height: 240\n" +" size: 'SMALL'\n" ; MediaItem item = mapper.readValue(YAML, MediaItem.class); assertNotNull(item); assertNotNull(item.getContent()); assertEquals(640, item.getContent().getWidth()); assertEquals(480, item.getContent().getHeight()); assertNotNull(item.getImages()); assertEquals(2, item.getImages().size()); assertEquals(Size.SMALL, item.getImages().get(1).getSize()); } } EventsTest.java000066400000000000000000000034451314745570600377200ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import com.fasterxml.jackson.core.*; /** * Tests that test low-level handling of events from YAML source */ public class EventsTest extends ModuleTestBase { public void testBasic() throws Exception { final String YAML = "string: 'text'\n" +"bool: true\n" +"bool2: false\n" +"null: null\n" +"i: 123\n" +"d: 1.25\n" ; YAMLFactory f = new YAMLFactory(); JsonParser p = f.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("text", p.getText()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertEquals("true", p.getText()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertToken(JsonToken.VALUE_FALSE, p.nextToken()); assertEquals("false", p.getText()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertEquals("null", p.getText()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals("123", p.getText()); assertEquals(123, p.getIntValue()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); assertEquals("1.25", p.getText()); assertEquals(1.25, p.getDoubleValue()); assertEquals(1, p.getIntValue()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); assertNull(p.nextToken()); assertNull(p.nextToken()); p.close(); } } ExceptionConversionTest.java000066400000000000000000000017701314745570600424570ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; /** * Tests to try to ensure that SnakeYAML exceptions are not leaked, * both because they are problematic on OSGi runtimes (depending on * whether shading is used) and because it is generally a bad idea * to leak implementation details. */ public class ExceptionConversionTest extends ModuleTestBase { public void testSimpleParsingLeakage() throws Exception { YAMLMapper mapper = mapperForYAML(); try { mapper.readTree("foo:\nbar: true\n baz: false"); fail("Should not pass with invalid YAML"); } catch (org.yaml.snakeyaml.scanner.ScannerException e) { fail("Internal exception type: "+e); } catch (JacksonYAMLParseException e) { // as of 2.8, this is the type to expect // (subtype of JsonParseException) verifyException(e, "mapping values are not allowed here"); } catch (Exception e) { fail("Unknown exception: "+e); } } } FormatDetectionTest.java000066400000000000000000000043131314745570600415360ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.format.DataFormatDetector; import com.fasterxml.jackson.core.format.DataFormatMatcher; import com.fasterxml.jackson.core.format.MatchStrength; public class FormatDetectionTest extends ModuleTestBase { /** * One nifty thing YAML has is the "---" start-doc indicator, which * makes it possible to auto-detect format... */ public void testFormatDetection() throws Exception { YAMLFactory yamlF = new YAMLFactory(); JsonFactory jsonF = new JsonFactory(); DataFormatDetector det = new DataFormatDetector(new JsonFactory[] { yamlF, jsonF }); // let's accept about any match; but only if no "solid match" found det = det.withMinimalMatch(MatchStrength.WEAK_MATCH).withOptimalMatch(MatchStrength.SOLID_MATCH); // First, give a JSON document... DataFormatMatcher match = det.findFormat("{ \"name\" : \"Bob\" }".getBytes("UTF-8")); assertNotNull(match); assertEquals(jsonF.getFormatName(), match.getMatchedFormatName()); // and verify we can parse it JsonParser p = match.createParserWithMatch(); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("name", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("Bob", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); // then YAML match = det.findFormat("---\nname: Bob\n".getBytes("UTF-8")); assertNotNull(match); assertEquals(yamlF.getFormatName(), match.getMatchedFormatName()); // and parsing p = match.createParserWithMatch(); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("name", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("Bob", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); } } ModuleTestBase.java000066400000000000000000000127511314745570600404740ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.io.IOException; import java.util.Arrays; import com.fasterxml.jackson.core.*; public abstract class ModuleTestBase extends junit.framework.TestCase { /** * Slightly modified sample class from Jackson tutorial ("JacksonInFiveMinutes") */ protected static class FiveMinuteUser { public enum Gender { MALE, FEMALE }; private Gender _gender; public String firstName, lastName; private boolean _isVerified; private byte[] _userImage; public FiveMinuteUser() { } public FiveMinuteUser(String first, String last, boolean verified, Gender g, byte[] data) { firstName = first; lastName = last; _isVerified = verified; _gender = g; _userImage = data; } public boolean isVerified() { return _isVerified; } public Gender getGender() { return _gender; } public byte[] getUserImage() { return _userImage; } public void setVerified(boolean b) { _isVerified = b; } public void setGender(Gender g) { _gender = g; } public void setUserImage(byte[] b) { _userImage = b; } @Override public boolean equals(Object o) { if (o == this) return true; if (o == null || o.getClass() != getClass()) return false; FiveMinuteUser other = (FiveMinuteUser) o; if (_isVerified != other._isVerified) return false; if (_gender != other._gender) return false; if (!firstName.equals(other.firstName)) return false; if (!lastName.equals(other.lastName)) return false; byte[] otherImage = other._userImage; if (otherImage.length != _userImage.length) return false; for (int i = 0, len = _userImage.length; i < len; ++i) { if (_userImage[i] != otherImage[i]) { return false; } } return true; } } protected ModuleTestBase() { } /* /********************************************************************** /* Helper methods, setup /********************************************************************** */ protected YAMLMapper mapperForYAML() { return new YAMLMapper(); } /* /********************************************************** /* Helper methods; low-level /********************************************************** */ public String quote(String str) { return '"'+str+'"'; } protected void assertToken(JsonToken expToken, JsonToken actToken) { if (actToken != expToken) { fail("Expected token "+expToken+", current token "+actToken); } } protected void assertToken(JsonToken expToken, JsonParser jp) { assertToken(expToken, jp.getCurrentToken()); } protected void assertType(Object ob, Class expType) { if (ob == null) { fail("Expected an object of type "+expType.getName()+", got null"); } Class cls = ob.getClass(); if (!expType.isAssignableFrom(cls)) { fail("Expected type "+expType.getName()+", got "+cls.getName()); } } protected void assertYAML(String expOrig, String actOrig) { String exp = trimDocMarker(expOrig).trim(); String act = trimDocMarker(actOrig).trim(); if (!exp.equals(act)) { // use std assert to show more accurately where differences are: assertEquals(expOrig, actOrig); } } /** * Method that gets textual contents of the current token using * available methods, and ensures results are consistent, before * returning them */ protected String getAndVerifyText(JsonParser jp) throws IOException, JsonParseException { // Ok, let's verify other accessors int actLen = jp.getTextLength(); char[] ch = jp.getTextCharacters(); String str2 = new String(ch, jp.getTextOffset(), actLen); String str = jp.getText(); if (str.length() != actLen) { fail("Internal problem (jp.token == "+jp.getCurrentToken()+"): jp.getText().length() ['"+str+"'] == "+str.length()+"; jp.getTextLength() == "+actLen); } assertEquals("String access via getText(), getTextXxx() must be the same", str, str2); return str; } protected void verifyFieldName(JsonParser jp, String expName) throws IOException { assertEquals(expName, jp.getText()); assertEquals(expName, jp.getCurrentName()); } protected void verifyIntValue(JsonParser jp, long expValue) throws IOException { // First, via textual assertEquals(String.valueOf(expValue), jp.getText()); } protected void verifyException(Throwable e, String... matches) { String msg = e.getMessage(); String lmsg = (msg == null) ? "" : msg.toLowerCase(); for (String match : matches) { String lmatch = match.toLowerCase(); if (lmsg.indexOf(lmatch) >= 0) { return; } } fail("Expected an exception with one of substrings ("+Arrays.asList(matches)+"): got one with message \""+msg+"\""); } protected static String trimDocMarker(String doc) { if (doc.startsWith("---")) { doc = doc.substring(3).trim(); } return doc; } } MultipleRootValuesTest.java000066400000000000000000000037511314745570600422730ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.util.Map; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.MappingIterator; public class MultipleRootValuesTest extends ModuleTestBase { private final YAMLMapper MAPPER = new YAMLMapper(); private final YAMLFactory YAML_F = MAPPER.getFactory(); public void testMultipleDocumentsViaParser() throws Exception { final String YAML = "num: 42\n" +"---\n" +"num: -42" ; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(42, p.getIntValue()); assertEquals(JsonParser.NumberType.INT, p.getNumberType()); assertEquals("42", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(-42, p.getIntValue()); assertEquals(JsonParser.NumberType.INT, p.getNumberType()); assertEquals("-42", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); } public void testMultipleDocumentsViaIterator() throws Exception { final String YAML = "num: 42\n" +"---\n" +"num: -42" ; MappingIterator> it = MAPPER.readerFor(new TypeReference>() { }).readValues(YAML); assertEquals(42, it.nextValue().get("num").intValue()); assertEquals(-42, it.nextValue().get("num").intValue()); it.close(); } } ObjectIdTest.java000066400000000000000000000124051314745570600401330ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.util.TokenBuffer; public class ObjectIdTest extends ModuleTestBase { @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id") static class Node { public String name; public Node next; public Node() { } public Node(String name) { this.name = name; } } @JsonIdentityInfo(generator=PrefixIdGenerator.class) static class NodeWithStringId { public String name; public NodeWithStringId next; public NodeWithStringId() { } public NodeWithStringId(String name) { this.name = name; } } static class PrefixIdGenerator extends ObjectIdGenerator { private static final long serialVersionUID = 1L; protected final Class _scope; protected transient int _nextValue; protected PrefixIdGenerator() { this(Object.class); } protected PrefixIdGenerator(Class scope) { _scope = scope; } @Override public final Class getScope() { return _scope; } @Override public boolean canUseFor(ObjectIdGenerator gen) { return (gen.getClass() == getClass()) && (gen.getScope() == _scope); } @Override public String generateId(Object forPojo) { return "id" + (_nextValue++); } @Override public ObjectIdGenerator forScope(Class scope) { return (_scope == scope) ? this : new PrefixIdGenerator(scope); } @Override public ObjectIdGenerator newForSerialization(Object context) { return new PrefixIdGenerator(_scope); } @Override public ObjectIdGenerator.IdKey key(Object key) { return new ObjectIdGenerator.IdKey(getClass(), _scope, key); } } /* /********************************************************** /* Test methods /********************************************************** */ private final static String SIMPLE_YAML_NATIVE = "---\n" +"&1 name: \"first\"\n" +"next:\n" +" &2 name: \"second\"\n" +" next: *1" ; private final static String SIMPLE_YAML_NATIVE_B = "---\n" +"&id1 name: \"first\"\n" +"next:\n" +" &id2 name: \"second\"\n" +" next: *id1" ; private final static String SIMPLE_YAML_NON_NATIVE = "---\n" +"'@id': 1\n" +"name: \"first\"\n" +"next:\n" +" '@id': 2\n" +" name: \"second\"\n" +" next: 1" ; private final ObjectMapper MAPPER = mapperForYAML(); public void testNativeSerialization() throws Exception { Node first = new Node("first"); Node second = new Node("second"); first.next = second; second.next = first; String yaml = MAPPER.writeValueAsString(first); assertYAML(SIMPLE_YAML_NATIVE, yaml); } // [dataformat-yaml#23] public void testNonNativeSerialization() throws Exception { YAMLMapper mapper = new YAMLMapper(); mapper.disable(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID); Node first = new Node("first"); Node second = new Node("second"); first.next = second; second.next = first; String yaml = mapper.writeValueAsString(first); assertYAML(SIMPLE_YAML_NON_NATIVE, yaml); } public void testBasicDeserialization() throws Exception { Node first = MAPPER.readValue(SIMPLE_YAML_NATIVE, Node.class); _verify(first); // Also with non-native Node second = MAPPER.readValue(SIMPLE_YAML_NON_NATIVE, Node.class); _verify(second); } // More complex example with string-prefixed id // [dataformat-yaml#45] public void testDeserializationIssue45() throws Exception { NodeWithStringId node = MAPPER.readValue(SIMPLE_YAML_NATIVE_B, NodeWithStringId.class); assertNotNull(node); assertEquals("first", node.name); assertNotNull(node.next); assertEquals("second", node.next.name); assertNotNull(node.next.next); assertSame(node, node.next.next); } public void testRoundtripWithBuffer() throws Exception { TokenBuffer tbuf = MAPPER.readValue(SIMPLE_YAML_NATIVE, TokenBuffer.class); assertNotNull(tbuf); Node first = MAPPER.readValue(tbuf.asParser(), Node.class); tbuf.close(); assertNotNull(first); _verify(first); } /* /********************************************************** /* Internal helper methods /********************************************************** */ private void _verify(Node n) { assertNotNull(n); assertEquals("first", n.name); assertNotNull(n.next); assertEquals("second", n.next.name); assertNotNull(n.next.next); assertSame(n, n.next.next); } } PolymorphicIdTest.java000066400000000000000000000051271314745570600412350ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import org.junit.Test; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; public class PolymorphicIdTest extends ModuleTestBase { static class Wrapper { public Nested nested; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = NestedImpl.class) }) static interface Nested { } @JsonTypeName("single") static class NestedImpl implements Nested { public String value; } @Test public void testPolymorphicType() throws Exception { // first, with value String YAML = "nested:\n" +" type: single\n" +" value: whatever"; ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); Wrapper top = mapper.readValue(YAML, Wrapper.class); assertNotNull(top); assertEquals(NestedImpl.class, top.nested.getClass()); assertEquals("whatever", ((NestedImpl) top.nested).value); // then without value YAML = "nested:\n" +" type: single"; top = mapper.readValue(YAML, Wrapper.class); assertNotNull(top); assertEquals(NestedImpl.class, top.nested.getClass()); assertNull("whatever", ((NestedImpl) top.nested).value); } @Test public void testNativePolymorphicType() throws Exception { String YAML = "nested: !single\n" +" value: foobar\n" ; ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); Wrapper top = mapper.readValue(YAML, Wrapper.class); assertNotNull(top); assertNotNull(top.nested); assertEquals(NestedImpl.class, top.nested.getClass()); assertEquals("foobar", ((NestedImpl) top.nested).value); YAML = "nested: !single { }\n"; top = mapper.readValue(YAML, Wrapper.class); assertNotNull(top); assertNotNull(top.nested); assertEquals(NestedImpl.class, top.nested.getClass()); // no value specified, empty // And third possibility; trickier, since YAML contains empty String, // and not Object; so we need to allow coercion ObjectReader r = mapper.readerFor(Wrapper.class) .with(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); YAML = "nested: !single\n"; top = r.readValue(YAML); assertNotNull(top); // and as a result, get null assertNull(top.nested); } } SimpleDatabindTest.java000066400000000000000000000104531314745570600413310ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.io.ByteArrayInputStream; import java.util.Map; import java.util.UUID; import org.junit.Assert; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; /** * Unit tests for checking functioning of the databinding * on top of YAML layer. */ public class SimpleDatabindTest extends ModuleTestBase { // to try to reproduce [Issue#15] static class EmptyBean { } static class Outer { public Name name; public int age; } static class Name { public String first, last; } /* /********************************************************** /* Test methods /********************************************************** */ public void testSimpleNested() throws Exception { final String YAML = "name:\n" +" first: Bob\n" +" last: De Burger\n" +"age: 28" ; ObjectMapper mapper = mapperForYAML(); // first, no doc marker Outer outer = mapper.readValue(YAML, Outer.class); assertNotNull(outer); assertNotNull(outer.name); assertEquals("Bob", outer.name.first); assertEquals("De Burger", outer.name.last); assertEquals(28, outer.age); // then with Outer outer2 = mapper.readValue("---\n"+YAML, Outer.class); assertNotNull(outer2); assertNotNull(outer2.name); assertEquals(outer.name.first, outer2.name.first); assertEquals(outer.name.last, outer2.name.last); assertEquals(outer.age, outer2.age); } public void testBasicUntyped() throws Exception { final String YAML = "template: Hello, %s!\n" +"database:\n" +" driverClass: org.h2.Driver\n" +" user: scott\n" +" password: tiger\n" +" extra: [1,2]" ; ObjectMapper mapper = mapperForYAML(); Map result = mapper.readValue(YAML, Map.class); // sanity check first: assertEquals(2, result.size()); // then literal comparison; easiest to just write as JSON... ObjectMapper jsonMapper = new ObjectMapper(); String json = jsonMapper.writeValueAsString(result); String EXP = "{\"template\":\"Hello, %s!\",\"database\":{" +"\"driverClass\":\"org.h2.Driver\",\"user\":\"scott\",\"password\":\"tiger\"," +"\"extra\":[1,2]}}"; assertEquals(EXP, json); } public void testBasicPOJO() throws Exception { ObjectMapper mapper = mapperForYAML(); final String YAML = "firstName: Billy\n" +"lastName: Baggins\n" +"gender: MALE\n" +"verified: true\n" +"userImage: AQIDBAU=" // [1,2,3,4,5] ; FiveMinuteUser user = mapper.readValue(YAML, FiveMinuteUser.class); assertEquals("Billy", user.firstName); assertEquals("Baggins", user.lastName); assertEquals(FiveMinuteUser.Gender.MALE, user.getGender()); assertTrue(user.isVerified()); byte[] data = user.getUserImage(); assertNotNull(data); Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4, 5 }, data); } public void testIssue1() throws Exception { ObjectMapper mapper = mapperForYAML(); final byte[] YAML = "firstName: Billy".getBytes("UTF-8"); FiveMinuteUser user = new FiveMinuteUser(); user.firstName = "Bubba"; mapper.readerForUpdating(user).readValue(new ByteArrayInputStream(YAML)); assertEquals("Billy", user.firstName); } // [Issue-2] public void testUUIDs() throws Exception { ObjectMapper mapper = mapperForYAML(); UUID uuid = new UUID(0, 0); String yaml = mapper.writeValueAsString(uuid); UUID result = mapper.readValue(yaml, UUID.class); assertEquals(uuid, result); } // [Issue#15] public void testEmptyBean() throws Exception { ObjectMapper mapper = mapperForYAML(); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); String yaml = mapper.writeValueAsString(new EmptyBean()); yaml = yaml.trim(); // let's be bit more robust; may or may not get doc marker if (yaml.startsWith("---")) { yaml = yaml.substring(3); } yaml = yaml.trim(); assertEquals("{}", yaml); } } SimpleGenerationTest.java000066400000000000000000000270231314745570600417170ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.io.*; import java.util.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; public class SimpleGenerationTest extends ModuleTestBase { public void testStreamingArray() throws Exception { YAMLFactory f = new YAMLFactory(); StringWriter w = new StringWriter(); JsonGenerator gen = f.createGenerator(w); gen.writeStartArray(); gen.writeNumber(3); gen.writeString("foobar"); gen.writeEndArray(); gen.close(); String yaml = w.toString(); // should probably parse? // note: 1.12 uses more compact notation; 1.10 has prefix yaml = trimDocMarker(yaml).trim(); assertEquals("- 3\n- \"foobar\"", yaml); } public void testStreamingObject() throws Exception { YAMLFactory f = new YAMLFactory(); StringWriter w = new StringWriter(); JsonGenerator gen = f.createGenerator(w); _writeBradDoc(gen); String yaml = w.toString(); // note: 1.12 uses more compact notation; 1.10 has prefix yaml = trimDocMarker(yaml).trim(); assertEquals("name: \"Brad\"\nage: 39", yaml); gen.close(); } public void testStreamingNested() throws Exception { YAMLFactory f = new YAMLFactory(); StringWriter w = new StringWriter(); JsonGenerator gen = f.createGenerator(w); gen.writeStartObject(); gen.writeFieldName("ob"); gen.writeStartArray(); gen.writeString("a"); gen.writeString("b"); gen.writeEndArray(); gen.writeEndObject(); gen.close(); String yaml = w.toString(); // note: 1.12 uses more compact notation; 1.10 has prefix yaml = trimDocMarker(yaml).trim(); BufferedReader br = new BufferedReader(new StringReader(yaml)); assertEquals("ob:", br.readLine()); /* 27-Jan-2015, tatu: Not 100% if those items ought to (or not) be indented. * SnakeYAML doesn't do that; yet some libs expect it. Strange. */ assertEquals("- \"a\"", br.readLine()); assertEquals("- \"b\"", br.readLine()); assertNull(br.readLine()); br.close(); } public void testBasicPOJO() throws Exception { ObjectMapper mapper = mapperForYAML(); FiveMinuteUser user = new FiveMinuteUser("Bob", "Dabolito", false, FiveMinuteUser.Gender.MALE, new byte[] { 1, 3, 13, 79 }); String yaml = mapper.writeValueAsString(user).trim(); String[] parts = yaml.split("\n"); boolean gotHeader = (parts.length == 6); if (!gotHeader) { // 1.10 has 6 as it has header assertEquals(5, parts.length); } // unify ordering, need to use TreeSets TreeSet exp = new TreeSet(); for (String part : parts) { exp.add(part.trim()); } Iterator it = exp.iterator(); if (gotHeader) { assertEquals("---", it.next()); } assertEquals("firstName: \"Bob\"", it.next()); assertEquals("gender: \"MALE\"", it.next()); assertEquals("lastName: \"Dabolito\"", it.next()); assertEquals("userImage: \"AQMNTw==\"", it.next()); assertEquals("verified: false", it.next()); } // Issue#12: public void testWithFile() throws Exception { File f = File.createTempFile("test", ".yml"); f.deleteOnExit(); ObjectMapper mapper = mapperForYAML(); Map map = new HashMap(); map.put("a", 3); mapper.writeValue(f, map); assertTrue(f.canRead()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream( f), "UTF-8")); String doc = br.readLine(); String str = br.readLine(); if (str != null) { doc += "\n" + str; } doc = trimDocMarker(doc); assertEquals("a: 3", doc); br.close(); f.delete(); } public void testWithFile2() throws Exception { File f = File.createTempFile("test", ".yml"); f.deleteOnExit(); ObjectMapper mapper = mapperForYAML(); ObjectNode root = mapper.createObjectNode(); root.put("name", "Foobar"); mapper.writeValue(f, root); // and get it back Map result = mapper.readValue(f, Map.class); assertEquals(1, result.size()); assertEquals("Foobar", result.get("name")); } @SuppressWarnings("resource") public void testStartMarker() throws Exception { YAMLFactory f = new YAMLFactory(); // Ok, first, assume we do get the marker: StringWriter w = new StringWriter(); assertTrue(f.isEnabled(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)); YAMLGenerator gen = f.createGenerator(w); assertTrue(gen.isEnabled(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)); _writeBradDoc(gen); String yaml = w.toString().trim(); assertEquals("---\nname: \"Brad\"\nage: 39", yaml); // and then, disabling, and not any more f.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER); assertFalse(f.isEnabled(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)); w = new StringWriter(); gen = f.createGenerator(w); assertFalse(gen.isEnabled(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)); _writeBradDoc(gen); yaml = w.toString().trim(); assertEquals("name: \"Brad\"\nage: 39", yaml); } public void testSplitLines() throws Exception { final String TEXT = "1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890"; final String[] INPUT = new String[] { TEXT }; YAMLFactory f = new YAMLFactory(); // verify default settings assertTrue(f.isEnabled(YAMLGenerator.Feature.SPLIT_LINES)); // and first write with splitting enabled YAMLMapper mapper = new YAMLMapper(f); String yaml = mapper.writeValueAsString(INPUT).trim(); assertEquals("---\n" + "- \"1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890\\\n" + " \\ 1234567890\"", yaml); // and then with splitting disabled f.disable(YAMLGenerator.Feature.SPLIT_LINES); yaml = mapper.writeValueAsString(INPUT).trim(); assertEquals("---\n" + "- \"1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890\"", yaml); } public void testLiteralStringsSingleLine() throws Exception { YAMLFactory f = new YAMLFactory(); // verify default settings assertFalse(f.isEnabled(YAMLGenerator.Feature.MINIMIZE_QUOTES)); f.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true); YAMLMapper mapper = new YAMLMapper(f); Map content = new HashMap(); content.put("key", "some value"); String yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: some value", yaml); } public void testMinimizeQuotesWithBooleanContent() throws Exception { YAMLFactory f = new YAMLFactory(); f.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true); YAMLMapper mapper = new YAMLMapper(f); Map content = new HashMap(); content.put("key", "true"); String yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: \"true\"", yaml); content.clear(); content.put("key", "false"); yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: \"false\"", yaml); content.clear(); content.put("key", "something else"); yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: something else", yaml); content.clear(); content.put("key", Boolean.TRUE); yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: true", yaml); } public void testLiteralStringsMultiLine() throws Exception { YAMLFactory f = new YAMLFactory(); // verify default settings assertFalse(f.isEnabled(YAMLGenerator.Feature.MINIMIZE_QUOTES)); f.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true); YAMLMapper mapper = new YAMLMapper(f); Map content = new HashMap(); content.put("key", "first\nsecond\nthird"); String yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: |-\n first\n second\n third", yaml); } public void testQuoteNumberStoredAsString() throws Exception { YAMLFactory f = new YAMLFactory(); // verify default settings assertFalse(f.isEnabled(YAMLGenerator.Feature.MINIMIZE_QUOTES)); assertFalse(f.isEnabled(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS)); f.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true); f.configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true); YAMLMapper mapper = new YAMLMapper(f); Map content = new HashMap(); content.put("key", "20"); String yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: \"20\"", yaml); content.clear(); content.put("key", "2.0"); yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: \"2.0\"", yaml); content.clear(); content.put("key", "2.0.1.2.3"); yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: 2.0.1.2.3", yaml); } public void testNonQuoteNumberStoredAsString() throws Exception { YAMLFactory f = new YAMLFactory(); // verify default settings assertFalse(f.isEnabled(YAMLGenerator.Feature.MINIMIZE_QUOTES)); assertFalse(f.isEnabled(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS)); f.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true); YAMLMapper mapper = new YAMLMapper(f); Map content = new HashMap(); content.put("key", "20"); String yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: 20", yaml); content.clear(); content.put("key", "2.0"); yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: 2.0", yaml); content.clear(); content.put("key", "2.0.1.2.3"); yaml = mapper.writeValueAsString(content).trim(); assertEquals("---\n" + "key: 2.0.1.2.3", yaml); } /* /********************************************************************** /* Helper methods /********************************************************************** */ protected void _writeBradDoc(JsonGenerator gen) throws IOException { gen.writeStartObject(); gen.writeStringField("name", "Brad"); gen.writeNumberField("age", 39); gen.writeEndObject(); gen.close(); } } SimpleParseTest.java000066400000000000000000000355671314745570600407120ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import java.io.StringWriter; import java.math.BigInteger; /** * Unit tests for checking functioning of the underlying * parser implementation. */ public class SimpleParseTest extends ModuleTestBase { final YAMLFactory YAML_F = new YAMLFactory(); // Parsing large numbers around the transition from int->long and long->BigInteger public void testIntParsing() throws Exception { String YAML; JsonParser p; // Test positive max-int YAML = "num: 2147483647"; p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(Integer.MAX_VALUE, p.getIntValue()); assertEquals(JsonParser.NumberType.INT, p.getNumberType()); assertEquals("2147483647", p.getText()); p.close(); // Test negative max-int YAML = "num: -2147483648"; p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(Integer.MIN_VALUE, p.getIntValue()); assertEquals(JsonParser.NumberType.INT, p.getNumberType()); assertEquals("-2147483648", p.getText()); p.close(); // Test positive max-int + 1 YAML = "num: 2147483648"; p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(Integer.MAX_VALUE + 1L, p.getLongValue()); assertEquals(JsonParser.NumberType.LONG, p.getNumberType()); assertEquals("2147483648", p.getText()); p.close(); // Test negative max-int - 1 YAML = "num: -2147483649"; p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(Integer.MIN_VALUE - 1L, p.getLongValue()); assertEquals(JsonParser.NumberType.LONG, p.getNumberType()); assertEquals("-2147483649", p.getText()); p.close(); // Test positive max-long YAML = "num: 9223372036854775807"; p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(Long.MAX_VALUE, p.getLongValue()); assertEquals(JsonParser.NumberType.LONG, p.getNumberType()); assertEquals("9223372036854775807", p.getText()); p.close(); // Test negative max-long YAML = "num: -9223372036854775808"; p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(Long.MIN_VALUE, p.getLongValue()); assertEquals(JsonParser.NumberType.LONG, p.getNumberType()); assertEquals("-9223372036854775808", p.getText()); p.close(); // Test positive max-long + 1 YAML = "num: 9223372036854775808"; p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE), p.getBigIntegerValue()); assertEquals(JsonParser.NumberType.BIG_INTEGER, p.getNumberType()); assertEquals("9223372036854775808", p.getText()); p.close(); // Test negative max-long - 1 YAML = "num: -9223372036854775809"; p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE), p.getBigIntegerValue()); assertEquals(JsonParser.NumberType.BIG_INTEGER, p.getNumberType()); assertEquals("-9223372036854775809", p.getText()); p.close(); } // [cbor#4]: accidental recognition as double, with multiple dots public void testDoubleParsing() throws Exception { // First, test out valid use case. String YAML; YAML = "num: +1_000.25"; // note underscores; legal in YAML apparently JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); StringWriter w = new StringWriter(); assertEquals(3, p.getText(w)); assertEquals("num", w.toString()); // should be considered a String... assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); assertEquals(1000.25, p.getDoubleValue()); // let's retain exact representation text however: assertEquals("+1_000.25", p.getText()); p.close(); // and then non-number that may be mistaken final String IP = "10.12.45.127"; YAML = "ip: "+IP+"\n"; p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("ip", p.getCurrentName()); // should be considered a String... assertToken(JsonToken.VALUE_STRING, p.nextToken()); w = new StringWriter(); assertEquals(IP.length(), p.getText(w)); assertEquals(IP, w.toString()); assertEquals(IP, p.getText()); p.close(); } // [Issue#7] // looks like colons in content can be problematic, if unquoted public void testColons() throws Exception { // First, test out valid use case. NOTE: spaces matter! String YAML = "section:\n" +" text: foo:bar\n"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("section", p.getCurrentName()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("text", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("foo:bar", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } /** * How should YAML Anchors be exposed? */ public void testAnchorParsing() throws Exception { // silly doc, just to expose an id (anchor) and ref to it final String YAML = "---\n" +"parent: &id1\n" +" name: Bob\n" +"child: &id2\n" +" name: Bill\n" +" parentRef: *id1" ; YAMLParser yp = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, yp.nextToken()); assertFalse(yp.isCurrentAlias()); assertNull(yp.getObjectId()); assertToken(JsonToken.FIELD_NAME, yp.nextToken()); assertEquals("parent", yp.getCurrentName()); assertFalse(yp.isCurrentAlias()); assertNull(yp.getObjectId()); assertToken(JsonToken.START_OBJECT, yp.nextToken()); assertFalse(yp.isCurrentAlias()); assertEquals("id1", yp.getObjectId()); assertToken(JsonToken.FIELD_NAME, yp.nextToken()); assertEquals("name", yp.getCurrentName()); assertToken(JsonToken.VALUE_STRING, yp.nextToken()); assertEquals("Bob", yp.getText()); assertFalse(yp.isCurrentAlias()); assertToken(JsonToken.END_OBJECT, yp.nextToken()); assertToken(JsonToken.FIELD_NAME, yp.nextToken()); assertEquals("child", yp.getCurrentName()); assertFalse(yp.isCurrentAlias()); assertToken(JsonToken.START_OBJECT, yp.nextToken()); assertFalse(yp.isCurrentAlias()); assertEquals("id2", yp.getObjectId()); assertToken(JsonToken.FIELD_NAME, yp.nextToken()); assertEquals("name", yp.getCurrentName()); assertToken(JsonToken.VALUE_STRING, yp.nextToken()); assertEquals("Bill", yp.getText()); assertToken(JsonToken.FIELD_NAME, yp.nextToken()); assertEquals("parentRef", yp.getCurrentName()); assertToken(JsonToken.VALUE_STRING, yp.nextToken()); assertEquals("id1", yp.getText()); assertTrue(yp.isCurrentAlias()); assertToken(JsonToken.END_OBJECT, yp.nextToken()); assertToken(JsonToken.END_OBJECT, yp.nextToken()); assertNull(yp.nextToken()); yp.close(); } // [Issue#10] // Scalars should not be parsed when not in the plain flow style. public void testQuotedStyles() throws Exception { String YAML = "strings: [\"true\", 'false']"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("strings", p.getCurrentName()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("true", p.getText()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("false", p.getText()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } // Scalars should be parsed when in the plain flow style. public void testUnquotedStyles() throws Exception { String YAML = "booleans: [true, false]"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("booleans", p.getCurrentName()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertToken(JsonToken.VALUE_FALSE, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } public void testObjectWithNumbers() throws Exception { String YAML = "---\n" +"content:\n" +" uri: \"http://javaone.com/keynote.mpg\"\n" +" title: \"Javaone Keynote\"\n" +" width: 640\n" +" height: 480\n" +" persons:\n" +" - \"Foo Bar\"\n" +" - \"Max Power\"\n" ; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("content", p.getCurrentName()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("uri", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("title", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("width", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(640, p.getIntValue()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("height", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(480, p.getIntValue()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("persons", p.getCurrentName()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("Foo Bar", p.getText()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("Max Power", p.getText()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } public void testNulls() throws Exception { String YAML = "nulls: [!!null \"null\" ]"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("nulls", p.getCurrentName()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } public void testTildeNulls() throws Exception { String YAML = "nulls: [~ ]"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("nulls", p.getCurrentName()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } // for [dataformat-yaml#69] public void testTimeLikeValues() throws Exception { final String YAML = "value: 3:00\n"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("value", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("3:00", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } } TestVersions.java000066400000000000000000000030011314745570600402500ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import java.io.*; import com.fasterxml.jackson.core.*; public class TestVersions extends ModuleTestBase { @SuppressWarnings("resource") public void testMapperVersions() throws IOException { YAMLFactory f = new YAMLFactory(); assertVersion(f); YAMLParser jp = (YAMLParser) f.createParser("123"); assertVersion(jp); jp.close(); YAMLGenerator jgen = (YAMLGenerator) f.createGenerator(new ByteArrayOutputStream()); assertVersion(jgen); } public void testDefaults() throws Exception { YAMLFactory f = new YAMLFactory(); assertFalse(f.canHandleBinaryNatively()); assertFalse(f.canUseCharArrays()); JsonParser p = f.createParser(new StringReader("")); assertTrue(p.canReadObjectId()); assertTrue(p.canReadTypeId()); p.close(); @SuppressWarnings("resource") JsonGenerator g = f.createGenerator(new StringWriter()); assertTrue(g.canOmitFields()); assertTrue(g.canWriteFormattedNumbers()); assertTrue(g.canWriteObjectId()); assertTrue(g.canWriteTypeId()); assertFalse(g.canWriteBinaryNatively()); } /* /********************************************************** /* Helper methods /********************************************************** */ private void assertVersion(Versioned vers) { assertEquals(PackageVersion.VERSION, vers.version()); } } TypeIdTest.java000066400000000000000000000060531314745570600376500ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.util.TokenBuffer; public class TypeIdTest extends ModuleTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(Impl.class) }) static abstract class Base { public int a; public Base() { } public Base(int a) { this.a = a; } } @JsonTypeName("impl") static class Impl extends Base { public Impl() { } public Impl(int a) { super(a); } } /* /********************************************************** /* Test methods /********************************************************** */ public void testNativeSerialization() throws Exception { ObjectMapper mapper = mapperForYAML(); String yaml = mapper.writeValueAsString(new Impl(13)); yaml = yaml.trim(); assertEquals("--- !\na: 13", yaml); } // [Issue#22] public void testNonNativeSerialization() throws Exception { YAMLMapper mapper = new YAMLMapper(); mapper.disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID); String yaml = mapper.writeValueAsString(new Impl(13)); yaml = yaml.trim(); assertEquals("---\ntype: \"impl\"\na: 13", yaml); // Let's also round-trip it Base back = mapper.readValue(yaml, Impl.class); assertNotNull(back); assertEquals(Impl.class, back.getClass()); } public void testDeserialization() throws Exception { /* Looks like there are couple of alternative ways to indicate * type ids... so let's verify variations we know of. */ ObjectMapper mapper = mapperForYAML(); for (String typeId : new String[] { "--- !", "--- !impl", "!", "!impl", // 04-May-2014, tatu: I _think_ we should support this too but... // "---\nTYPE: impl\n", }) { final String input = typeId + "\na: 13"; Base result = mapper.readValue(input, Base.class); _verify(result); } } public void testRoundtripWithBuffer() throws Exception { ObjectMapper mapper = mapperForYAML(); TokenBuffer tbuf = mapper.readValue("--- !impl\na: 13\n", TokenBuffer.class); assertNotNull(tbuf); Base result = mapper.readValue(tbuf.asParser(), Base.class); tbuf.close(); _verify(result); } /* /********************************************************** /* Internal helper methods /********************************************************** */ private void _verify(Base result) { assertNotNull(result); assertEquals(Impl.class, result.getClass()); Impl i = (Impl) result; assertEquals(13, i.a); } } UTF8ReaderTest.java000066400000000000000000000022251314745570600403200ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlpackage com.fasterxml.jackson.dataformat.yaml; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertEquals; public class UTF8ReaderTest { @Test public void canUseMultipleUTF8ReadersInSameThread() throws IOException { String message = "we expect this message to be present after reading the contents of the reader out"; InputStream expected = new ByteArrayInputStream(("." + message).getBytes(StandardCharsets.UTF_8)); InputStream overwriter = new ByteArrayInputStream(".in older versions of Jackson, this overwrote it" .getBytes(StandardCharsets.UTF_8)); char[] result = new char[message.length()]; UTF8Reader utf8Reader = new UTF8Reader(expected, true); UTF8Reader badUtf8Reader = new UTF8Reader(overwriter, true); utf8Reader.read(); badUtf8Reader.read(); utf8Reader.read(result); assertEquals(message, new String(result)); utf8Reader.close(); badUtf8Reader.close(); } } failing/000077500000000000000000000000001314745570600363545ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlCollectionReadTest.java000066400000000000000000000016361314745570600427540ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yaml/failingpackage com.fasterxml.jackson.dataformat.yaml.failing; import java.util.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.ModuleTestBase; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; // for [dataformat-yaml#26]: not sure if it's an actual bug, but adding for now. public class CollectionReadTest extends ModuleTestBase { static class SetBean { public List sets; } public void testSet26() throws Exception { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); final String YAML = "---\n" +"sets: !!set\n" +" ? a\n" +" ? b\n"; SetBean bean = mapper.readValue(YAML, SetBean.class); assertNotNull(bean); assertNotNull(bean.sets); assertEquals(2, bean.sets.size()); assertEquals("b", bean.sets.get(1)); } } ObjectIdTest.java000066400000000000000000000036361314745570600415520ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yaml/failingpackage com.fasterxml.jackson.dataformat.yaml.failing; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.ModuleTestBase; /** * Although native Object Ids work in general, Tree Model currently * has issues with it (see [dataformat-yaml#24]) */ public class ObjectIdTest extends ModuleTestBase { @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id") static class Node { public String name; public Node next; public Node() { } public Node(String name) { this.name = name; } } /* /********************************************************** /* Test methods /********************************************************** */ private final static String SIMPLE_YAML = "---\n" +"&1 name: \"first\"\n" +"next:\n" +" &2 name: \"second\"\n" +" next: *1" ; // For issue [#24] public void testRoundtripViaTree() throws Exception { ObjectMapper mapper = mapperForYAML(); JsonNode root = mapper.readTree(SIMPLE_YAML); assertNotNull(root); Node first = mapper.treeToValue(root, Node.class); assertNotNull(first); _verify(first); } /* /********************************************************** /* Internal helper methods /********************************************************** */ private void _verify(Node first) { assertNotNull(first); assertEquals("first", first.name); assertNotNull(first.next); assertEquals("second", first.next.name); assertNotNull("Should not have null for 'first.next.next'", first.next.next); assertSame(first, first.next.next); } } failsafe/000077500000000000000000000000001314745570600365155ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yamlOSGiIT.java000066400000000000000000000051241314745570600404200ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/com/fasterxml/jackson/dataformat/yaml/failsafepackage com.fasterxml.jackson.dataformat.yaml.failsafe; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemPackages; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.url; /** * PAX-EXAM test that proves that the OSGi bundle works. This test is magically transformed into * an OSGi bundle, and additional bundles are loaded into the container as specified in * {@link #config()}. *

* NOTE: named specifically so as NOT to run as a unit test, as this is an integration test * to run after build */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class OSGiIT { @Configuration public Option[] config() { return options( mavenBundle("com.fasterxml.jackson.core", "jackson-core").versionAsInProject(), mavenBundle("com.fasterxml.jackson.core", "jackson-annotations").versionAsInProject(), mavenBundle("com.fasterxml.jackson.core", "jackson-databind").versionAsInProject(), // As of Jackson 2.8, will also need SnakeYAML, not shaded in mavenBundle("org.yaml", "snakeyaml").versionAsInProject(), /* mavenBundle talks to aether, not the reactor, so we cannot use it to access the * thing built just now. Instead, we load the file. */ url(String.format("file:%s/jackson-dataformat-yaml-%s.jar", System.getProperty("project.build.directory"), System.getProperty("project.version"))), systemPackages( "javax.annotation"), junitBundles(), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("WARN") ); } @Test public void onceOver() throws Exception { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); String yaml = mapper.writeValueAsString("Hello"); System.out.println("OSGi verification successful, result: '"+yaml+"'"); } } jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/perf/000077500000000000000000000000001314745570600264575ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/perf/DeserPerf.java000066400000000000000000000107641314745570600312110ustar00rootroot00000000000000package perf; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; /** * Micro-benchmark for comparing performance of bean deserialization */ public final class DeserPerf { /* /********************************************************** /* Actual test /********************************************************** */ private final int REPS; private DeserPerf() { // Let's try to guestimate suitable size REPS = 9000; } private MediaItem buildItem() { MediaItem.Content content = new MediaItem.Content(); content.setPlayer(MediaItem.Player.JAVA); content.setUri("http://javaone.com/keynote.mpg"); content.setTitle("Javaone Keynote"); content.setWidth(640); content.setHeight(480); content.setFormat("video/mpeg4"); content.setDuration(18000000L); content.setSize(58982400L); content.setBitrate(262144); content.setCopyright("None"); content.addPerson("Bill Gates"); content.addPerson("Steve Jobs"); MediaItem item = new MediaItem(content); item.addPhoto(new MediaItem.Photo("http://javaone.com/keynote_large.jpg", "Javaone Keynote", 1024, 768, MediaItem.Size.LARGE)); item.addPhoto(new MediaItem.Photo("http://javaone.com/keynote_small.jpg", "Javaone Keynote", 320, 240, MediaItem.Size.SMALL)); return item; } public void test() throws Exception { int sum = 0; final MediaItem item = buildItem(); // JsonFactory jsonF = new JsonFactory(); // final ObjectMapper jsonMapper = new ObjectMapper(jsonF); JsonFactory yamlF = new com.fasterxml.jackson.dataformat.yaml.YAMLFactory(); final ObjectMapper yamlMapper = new ObjectMapper(yamlF); // final ObjectMapper jsonMapper = new ObjectMapper(jsonF); // jsonMapper.configure(SerializationConfig.Feature.USE_STATIC_TYPING, true); // Use Jackson? // byte[] json = jsonMapper.writeValueAsBytes(item); byte[] yaml = yamlMapper.writeValueAsBytes(item); System.out.println("Warmed up: data size is "+yaml.length+" bytes; "+REPS+" reps -> " +((REPS * yaml.length) >> 10)+" kB per iteration"); System.out.println(); // for debugging: // System.err.println("JSON = "+jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(item)); int round = 0; while (true) { // try { Thread.sleep(100L); } catch (InterruptedException ie) { } // int round = 2; long curr = System.currentTimeMillis(); String msg; round = (++round % 2); //if (true) round = 3; boolean lf = (round == 0); switch (round) { case 0: case 1: msg = "Deserialize, bind, YAML"; sum += testDeser(yamlMapper, yaml, REPS); break; /* case 0: msg = "Deserialize, manual, YAML"; sum += testDeser(yamlMapper.getJsonFactory(), yaml, REPS); break; */ default: throw new Error("Internal error"); } curr = System.currentTimeMillis() - curr; if (lf) { System.out.println(); } System.out.println("Test '"+msg+"' -> "+curr+" msecs (" +(sum & 0xFF)+")."); } } protected int testDeser(ObjectMapper mapper, byte[] input, int reps) throws Exception { JavaType type = TypeFactory.defaultInstance().constructType(MediaItem.class); MediaItem item = null; for (int i = 0; i < reps; ++i) { item = mapper.readValue(input, 0, input.length, type); } return item.hashCode(); // just to get some non-optimizable number } protected int testDeser(JsonFactory jf, byte[] input, int reps) throws Exception { MediaItem item = null; for (int i = 0; i < reps; ++i) { JsonParser jp = jf.createParser(input); item = MediaItem.deserialize(jp); jp.close(); } return item.hashCode(); // just to get some non-optimizable number } public static void main(String[] args) throws Exception { new DeserPerf().test(); } } jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/perf/MediaItem.java000066400000000000000000000336651314745570600311750ustar00rootroot00000000000000package perf; import java.io.IOException; import java.util.*; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.*; /** * Value class for performance tests */ @JsonPropertyOrder({"content", "images"}) public class MediaItem { final static String NAME_IMAGES = "images"; final static String NAME_CONTENT = "content"; public enum Player { JAVA, FLASH; } public enum Size { SMALL, LARGE; } private List _photos; private Content _content; public MediaItem() { } public MediaItem(Content c) { _content = c; } public void addPhoto(Photo p) { if (_photos == null) { _photos = new ArrayList(); } _photos.add(p); } public List getImages() { return _photos; } public void setImages(List p) { _photos = p; } public Content getContent() { return _content; } public void setContent(Content c) { _content = c; } // Custom deser public static MediaItem deserialize(JsonParser jp) throws IOException { if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Need START_OBJECT for MediaItem"); } MediaItem item = new MediaItem(); while (jp.nextToken() == JsonToken.FIELD_NAME) { String name = jp.getCurrentName(); if (name == "images") { item._photos = deserializeImages(jp); } else if (name == "content") { item._content = Content.deserialize(jp); } else throw new IOException("Unknown field"); } if (jp.getCurrentToken() != JsonToken.END_OBJECT) { throw new IOException("Need END_OBJECT to complete MediaItem"); } return item; } private static List deserializeImages(JsonParser jp) throws IOException { if (jp.nextToken() != JsonToken.START_ARRAY) { throw new IOException("Need START_ARRAY for List of Photos"); } ArrayList images = new ArrayList(4); while (jp.nextToken() == JsonToken.START_OBJECT) { images.add(Photo.deserialize(jp)); } if (jp.getCurrentToken() != JsonToken.END_ARRAY) { throw new IOException("Need END_ARRAY to complete List of Photos"); } return images; } // Custom serializer public void serialize(JsonGenerator jgen) throws IOException { jgen.writeStartObject(); jgen.writeFieldName("content"); if (_content == null) { jgen.writeNull(); } else { _content.serialize(jgen); } if (_photos == null) { jgen.writeNullField("images"); } else { jgen.writeArrayFieldStart("images"); for (Photo photo : _photos) { photo.serialize(jgen); } jgen.writeEndArray(); } jgen.writeEndObject(); } /* /********************************************************** /* Helper types /********************************************************** */ @JsonPropertyOrder({"uri","title","width","height","size"}) public static class Photo { public final static int F_URI = 1; public final static int F_TITLE = 2; public final static int F_WIDTH = 3; public final static int F_HEIGHT = 4; public final static int F_SIZE = 5; public final static HashMap sFields = new HashMap(); static { // MediaItem fields sFields.put("uri", F_URI); sFields.put("title", F_TITLE); sFields.put("width", F_WIDTH); sFields.put("height", F_HEIGHT); sFields.put("size", F_SIZE); } private String _uri; private String _title; private int _width; private int _height; private Size _size; public Photo() {} public Photo(String uri, String title, int w, int h, Size s) { _uri = uri; _title = title; _width = w; _height = h; _size = s; } public String getUri() { return _uri; } public String getTitle() { return _title; } public int getWidth() { return _width; } public int getHeight() { return _height; } public Size getSize() { return _size; } public void setUri(String u) { _uri = u; } public void setTitle(String t) { _title = t; } public void setWidth(int w) { _width = w; } public void setHeight(int h) { _height = h; } public void setSize(Size s) { _size = s; } private static Size findSize(String id) { if (id.charAt(0) == 'L') { if ("LARGE".equals(id)) { return Size.LARGE; } } else if ("SMALL".equals(id)) { return Size.SMALL; } throw new IllegalArgumentException(); } public static Photo deserialize(JsonParser jp) throws IOException { Photo photo = new Photo(); while (jp.nextToken() == JsonToken.FIELD_NAME) { String name = jp.getCurrentName(); jp.nextToken(); Integer I = sFields.get(name); if (I != null) { switch (I.intValue()) { case F_URI: photo.setUri(jp.getText()); continue; case F_TITLE: photo.setTitle(jp.getText()); continue; case F_WIDTH: photo.setWidth(jp.getIntValue()); continue; case F_HEIGHT: photo.setHeight(jp.getIntValue()); continue; case F_SIZE: photo.setSize(findSize(jp.getText())); continue; } } throw new IOException("Unknown field '"+name+"'"); } if (jp.getCurrentToken() != JsonToken.END_OBJECT) { throw new IOException("Need END_OBJECT to complete Photo"); } return photo; } public void serialize(JsonGenerator jgen) throws IOException { jgen.writeStartObject(); jgen.writeStringField("uri", _uri); jgen.writeStringField("title", _title); jgen.writeNumberField("width", _width); jgen.writeNumberField("height", _height); jgen.writeStringField("size", (_size == null) ? null : _size.name()); jgen.writeEndObject(); } } @JsonPropertyOrder({"player","uri","title","width","height","format","duration","size","bitrate","persons","copyright"}) public static class Content { public final static int F_PLAYER = 0; public final static int F_URI = 1; public final static int F_TITLE = 2; public final static int F_WIDTH = 3; public final static int F_HEIGHT = 4; public final static int F_FORMAT = 5; public final static int F_DURATION = 6; public final static int F_SIZE = 7; public final static int F_BITRATE = 8; public final static int F_PERSONS = 9; public final static int F_COPYRIGHT = 10; public final static HashMap sFields = new HashMap(); static { sFields.put("player", F_PLAYER); sFields.put("uri", F_URI); sFields.put("title", F_TITLE); sFields.put("width", F_WIDTH); sFields.put("height", F_HEIGHT); sFields.put("format", F_FORMAT); sFields.put("duration", F_DURATION); sFields.put("size", F_SIZE); sFields.put("bitrate", F_BITRATE); sFields.put("persons", F_PERSONS); sFields.put("copyright", F_COPYRIGHT); } private Player _player; private String _uri; private String _title; private int _width; private int _height; private String _format; private long _duration; private long _size; private int _bitrate; private List _persons; private String _copyright; public Content() { } public void addPerson(String p) { if (_persons == null) { _persons = new ArrayList(); } _persons.add(p); } public Player getPlayer() { return _player; } public String getUri() { return _uri; } public String getTitle() { return _title; } public int getWidth() { return _width; } public int getHeight() { return _height; } public String getFormat() { return _format; } public long getDuration() { return _duration; } public long getSize() { return _size; } public int getBitrate() { return _bitrate; } public List getPersons() { return _persons; } public String getCopyright() { return _copyright; } public void setPlayer(Player p) { _player = p; } public void setUri(String u) { _uri = u; } public void setTitle(String t) { _title = t; } public void setWidth(int w) { _width = w; } public void setHeight(int h) { _height = h; } public void setFormat(String f) { _format = f; } public void setDuration(long d) { _duration = d; } public void setSize(long s) { _size = s; } public void setBitrate(int b) { _bitrate = b; } public void setPersons(List p) { _persons = p; } public void setCopyright(String c) { _copyright = c; } private static Player findPlayer(String id) { if ("JAVA".equals(id)) { return Player.JAVA; } if ("FLASH".equals(id)) { return Player.FLASH; } throw new IllegalArgumentException("Weird Player value of '"+id+"'"); } public static Content deserialize(JsonParser jp) throws IOException { if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Need START_OBJECT for Content"); } Content content = new Content(); while (jp.nextToken() == JsonToken.FIELD_NAME) { String name = jp.getCurrentName(); jp.nextToken(); Integer I = sFields.get(name); if (I != null) { switch (I.intValue()) { case F_PLAYER: content.setPlayer(findPlayer(jp.getText())); case F_URI: content.setUri(jp.getText()); continue; case F_TITLE: content.setTitle(jp.getText()); continue; case F_WIDTH: content.setWidth(jp.getIntValue()); continue; case F_HEIGHT: content.setHeight(jp.getIntValue()); continue; case F_FORMAT: content.setCopyright(jp.getText()); continue; case F_DURATION: content.setDuration(jp.getLongValue()); continue; case F_SIZE: content.setSize(jp.getLongValue()); continue; case F_BITRATE: content.setBitrate(jp.getIntValue()); continue; case F_PERSONS: content.setPersons(deserializePersons(jp)); continue; case F_COPYRIGHT: content.setCopyright(jp.getText()); continue; } } throw new IOException("Unknown field '"+name+"'"); } if (jp.getCurrentToken() != JsonToken.END_OBJECT) { throw new IOException("Need END_OBJECT to complete Content"); } return content; } private static List deserializePersons(JsonParser jp) throws IOException { if (jp.getCurrentToken() != JsonToken.START_ARRAY) { throw new IOException("Need START_ARRAY for List of Persons (got "+jp.getCurrentToken()+")"); } ArrayList persons = new ArrayList(4); while (jp.nextToken() == JsonToken.VALUE_STRING) { persons.add(jp.getText()); } if (jp.getCurrentToken() != JsonToken.END_ARRAY) { throw new IOException("Need END_ARRAY to complete List of Persons"); } return persons; } public void serialize(JsonGenerator jgen) throws IOException { jgen.writeStartObject(); jgen.writeStringField("player", (_player == null) ? null : _player.name()); jgen.writeStringField("uri", _uri); jgen.writeStringField("title", _title); jgen.writeNumberField("width", _width); jgen.writeNumberField("height", _height); jgen.writeStringField("format", _format); jgen.writeNumberField("duration", _duration); jgen.writeNumberField("size", _size); jgen.writeNumberField("bitrate", _bitrate); jgen.writeStringField("copyright", _copyright); if (_persons == null) { jgen.writeNullField("persons"); } else { jgen.writeArrayFieldStart("persons"); for (String p : _persons) { jgen.writeString(p); } jgen.writeEndArray(); } jgen.writeEndObject(); } } } jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/java/perf/SerPerf.java000066400000000000000000000107051314745570600306730ustar00rootroot00000000000000package perf; import java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; public final class SerPerf { /* /********************************************************** /* Actual test /********************************************************** */ private final int REPS; private SerPerf() throws Exception { // Let's try to guesstimate suitable size... REPS = 6000; } private MediaItem buildItem() { MediaItem.Content content = new MediaItem.Content(); content.setPlayer(MediaItem.Player.JAVA); content.setUri("http://javaone.com/keynote.mpg"); content.setTitle("Javaone Keynote"); content.setWidth(640); content.setHeight(480); content.setFormat("video/mpeg4"); content.setDuration(18000000L); content.setSize(58982400L); content.setBitrate(262144); content.setCopyright("None"); content.addPerson("Bill Gates"); content.addPerson("Steve Jobs"); MediaItem item = new MediaItem(content); item.addPhoto(new MediaItem.Photo("http://javaone.com/keynote_large.jpg", "Javaone Keynote", 1024, 768, MediaItem.Size.LARGE)); item.addPhoto(new MediaItem.Photo("http://javaone.com/keynote_small.jpg", "Javaone Keynote", 320, 240, MediaItem.Size.SMALL)); return item; } public void test() throws Exception { int i = 0; int sum = 0; ByteArrayOutputStream result = new ByteArrayOutputStream(); final MediaItem item = buildItem(); final JsonFactory jsonF = new YAMLFactory(); final ObjectMapper jsonMapper = new ObjectMapper(jsonF); JsonNode root = jsonMapper.valueToTree(item); while (true) { // Thread.sleep(150L); ++i; int round = (i % 3); // override? round = 0; long curr = System.currentTimeMillis(); String msg; switch (round) { case 0: msg = "Serialize, JSON"; sum += testObjectSer(jsonMapper, item, REPS+REPS, result); break; case 1: msg = "Serialize, JSON/manual"; sum += testObjectSer(jsonMapper.getFactory(), item, REPS+REPS, result); break; case 2: msg = "Serialize, JsonNode"; sum += testNodeSer(jsonMapper, root, REPS+REPS, result); // sum += testNodeSer(smileMapper, root, REPS+REPS, result); break; default: throw new Error("Internal error"); } curr = System.currentTimeMillis() - curr; if (round == 0) { System.out.println(); } System.out.println("Test '"+msg+"' -> "+curr+" msecs ("+(sum & 0xFF)+")."); if ((i & 0x1F) == 0) { // GC every 64 rounds System.out.println("[GC]"); Thread.sleep(20L); System.gc(); Thread.sleep(20L); } } } protected int testObjectSer(ObjectMapper mapper, Object value, int reps, ByteArrayOutputStream result) throws Exception { for (int i = 0; i < reps; ++i) { result.reset(); mapper.writeValue(result, value); } return result.size(); // just to get some non-optimizable number } protected int testNodeSer(ObjectMapper mapper, JsonNode value, int reps, ByteArrayOutputStream result) throws Exception { for (int i = 0; i < reps; ++i) { result.reset(); mapper.writeValue(result, value); } return result.size(); // just to get some non-optimizable number } protected int testObjectSer(JsonFactory jf, MediaItem value, int reps, ByteArrayOutputStream result) throws Exception { for (int i = 0; i < reps; ++i) { result.reset(); JsonGenerator jgen = jf.createGenerator(result, JsonEncoding.UTF8); value.serialize(jgen); jgen.close(); } return result.size(); // just to get some non-optimizable number } public static void main(String[] args) throws Exception { new SerPerf().test(); } } jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/resources/000077500000000000000000000000001314745570600266145ustar00rootroot00000000000000jackson-dataformat-yaml-jackson-dataformat-yaml-2.8.10/src/test/resources/log4j.properties000066400000000000000000000004551314745570600317550ustar00rootroot00000000000000log4j.rootLogger=WARN, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.Encoding=UTF-8 # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n